From 4239beb82573a7c13ef05d7cdbf4407a16ab7553 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 3 May 2025 18:26:56 +0200 Subject: [PATCH 01/94] de-dupe code --- .../model/gamedata/Common.java | 100 +++++++++ .../atcontentstudio/model/gamedata/Item.java | 175 +++++---------- .../atcontentstudio/model/gamedata/NPC.java | 200 ++++-------------- .../ui/gamedataeditors/ItemEditor.java | 125 +++++------ .../ui/gamedataeditors/NPCEditor.java | 107 +++++----- .../atcontentstudio/ui/tools/GDEVisitor.java | 19 +- 6 files changed, 324 insertions(+), 402 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java new file mode 100644 index 0000000..3f34836 --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -0,0 +1,100 @@ +package com.gpl.rpg.atcontentstudio.model.gamedata; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public final class Common { + + public static class TimedConditionEffect extends ConditionEffect { + //Available from parsed state + public Integer duration = null; + public Double chance = null; + } + + public static class ConditionEffect { + //Available from parsed state + public Integer magnitude = null; + public String condition_id = null; + + //Available from linked state + public ActorCondition condition = null; + } + + @SuppressWarnings("rawtypes") + public static ArrayList parseTimedConditionEffects(List conditionsSourceJson) { + ArrayList conditions_source; + if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { + conditions_source = new ArrayList(); + for (Object conditionJsonObj : conditionsSourceJson) { + Map conditionJson = (Map) conditionJsonObj; + TimedConditionEffect condition = new TimedConditionEffect(); + condition.condition_id = (String) conditionJson.get("condition"); + condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); + condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); + if (conditionJson.get("chance") != null) + condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); + conditions_source.add(condition); + } + } else { + conditions_source = null; + } + return conditions_source; + } + + @SuppressWarnings("rawtypes") + public static HitReceivedEffect parseHitReceivedEffect(Map hitReceivedEffect) { + if (hitReceivedEffect == null) { + return null; + } + + HitReceivedEffect hit_received_effect = new Common.HitReceivedEffect(); + if (hitReceivedEffect.get("increaseCurrentHP") != null) { + hit_received_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentHP")).get("max"))); + hit_received_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentHP")).get("min"))); + } + if (hitReceivedEffect.get("increaseCurrentAP") != null) { + hit_received_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentAP")).get("max"))); + hit_received_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentAP")).get("min"))); + } + if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) { + hit_received_effect.hp_boost_max_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max"))); + hit_received_effect.hp_boost_min_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min"))); + } + if (hitReceivedEffect.get("increaseAttackerCurrentAP") != null) { + hit_received_effect.ap_boost_max_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max"))); + hit_received_effect.ap_boost_min_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min"))); + } + List conditionsSourceJson = (List) hitReceivedEffect.get("conditionsSource"); + hit_received_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); + List conditionsTargetJson = (List) hitReceivedEffect.get("conditionsTarget"); + hit_received_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); + return hit_received_effect; + } + + + + + public static class DeathEffect { + //Available from parsed state + public Integer hp_boost_min = null; + public Integer hp_boost_max = null; + public Integer ap_boost_min = null; + public Integer ap_boost_max = null; + public List conditions_source = null; + } + + public static class HitEffect extends DeathEffect { + //Available from parsed state + public List conditions_target = null; + } + + public static class HitReceivedEffect extends Common.HitEffect { + //Available from parsed state + public Integer hp_boost_min_target = null; + public Integer hp_boost_max_target = null; + public Integer ap_boost_min_target = null; + public Integer ap_boost_max_target = null; + } + +} diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 853ffaa..6b54005 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -33,39 +33,14 @@ public class Item extends JSONElement { public Integer base_market_cost = null; public String category_id = null; public String description = null; - public HitEffect hit_effect = null; - public HitReceivedEffect hit_received_effect = null; - public KillEffect kill_effect = null; + public Common.HitEffect hit_effect = null; + public Common.HitReceivedEffect hit_received_effect = null; + public Common.DeathEffect kill_effect = null; public EquipEffect equip_effect = null; //Available from linked state public ItemCategory category = null; - - - - public static class KillEffect { - //Available from parsed state - public Integer hp_boost_min = null; - public Integer hp_boost_max = null; - public Integer ap_boost_min = null; - public Integer ap_boost_max = null; - public List conditions_source = null; - - } - - //Inheritance for code compactness, not semantically correct. - public static class HitEffect extends KillEffect { - //Available from parsed state - public List conditions_target = null; - } - - public static class HitReceivedEffect extends HitEffect { - //Available from parsed state - public Integer hp_boost_min_target = null; - public Integer hp_boost_max_target = null; - public Integer ap_boost_min_target = null; - public Integer ap_boost_max_target = null; - } + public static class EquipEffect { //Available from parsed state @@ -73,7 +48,7 @@ public class Item extends JSONElement { public Integer damage_boost_max = null; public Integer max_hp_boost = null; public Integer max_ap_boost = null; - public List conditions = null; + public List conditions = null; public Integer increase_move_cost = null; public Integer increase_use_item_cost = null; public Integer increase_reequip_cost = null; @@ -85,21 +60,7 @@ public class Item extends JSONElement { public Double critical_multiplier = null; public Integer damage_modifier = null; } - - public static class ConditionEffect { - //Available from parsed state - public Integer magnitude = null; - public String condition_id = null; - - //Available from linked state - public ActorCondition condition = null; - } - - public static class TimedConditionEffect extends ConditionEffect { - //Available from parsed state - public Integer duration = null; - public Double chance = null; - } + public static enum DisplayType { ordinary, @@ -207,10 +168,10 @@ public class Item extends JSONElement { List conditionsJson = (List) equipEffect.get("addedConditions"); if (conditionsJson != null && !conditionsJson.isEmpty()) { - this.equip_effect.conditions = new ArrayList(); + this.equip_effect.conditions = new ArrayList<>(); for (Object conditionJsonObj : conditionsJson) { Map conditionJson = (Map)conditionJsonObj; - ConditionEffect condition = new ConditionEffect(); + Common.ConditionEffect condition = new Common.ConditionEffect(); condition.condition_id = (String) conditionJson.get("condition"); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); this.equip_effect.conditions.add(condition); @@ -221,46 +182,24 @@ public class Item extends JSONElement { Map hitEffect = (Map) itemJson.get("hitEffect"); if (hitEffect != null) { - this.hit_effect = new HitEffect(); + this.hit_effect = new Common.HitEffect(); if (hitEffect.get("increaseCurrentHP") != null) { this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("min"))); this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("max"))); } if (hitEffect.get("increaseCurrentAP") != null) { this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("min"))); - this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("max"))); + this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("max"))); } List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); - if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.hit_effect.conditions_source = new ArrayList(); - for (Object conditionJsonObj : conditionsSourceJson) { - Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_effect.conditions_source.add(condition); - } - } + this.hit_effect.conditions_source = Common.parseTimedConditionEffects(conditionsSourceJson); List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); - if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) { - this.hit_effect.conditions_target = new ArrayList(); - for (Object conditionJsonObj : conditionsTargetJson) { - Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_effect.conditions_target.add(condition); - } - } + this.hit_effect.conditions_target = Common.parseTimedConditionEffects(conditionsTargetJson); } Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); if (hitReceivedEffect != null) { - this.hit_received_effect = new HitReceivedEffect(); + this.hit_received_effect = new Common.HitReceivedEffect(); if (hitReceivedEffect.get("increaseCurrentHP") != null) { this.hit_received_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("min"))); this.hit_received_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("max"))); @@ -279,10 +218,10 @@ public class Item extends JSONElement { } List conditionsSourceJson = (List) hitReceivedEffect.get("conditionsSource"); if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.hit_received_effect.conditions_source = new ArrayList(); + this.hit_received_effect.conditions_source = new ArrayList<>(); for (Object conditionJsonObj : conditionsSourceJson) { Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); condition.condition_id = (String) conditionJson.get("condition"); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); @@ -292,10 +231,10 @@ public class Item extends JSONElement { } List conditionsTargetJson = (List) hitReceivedEffect.get("conditionsTarget"); if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) { - this.hit_received_effect.conditions_target = new ArrayList(); + this.hit_received_effect.conditions_target = new ArrayList<>(); for (Object conditionJsonObj : conditionsTargetJson) { Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); condition.condition_id = (String) conditionJson.get("condition"); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); @@ -310,7 +249,7 @@ public class Item extends JSONElement { killEffect = (Map) itemJson.get("useEffect"); } if (killEffect != null) { - this.kill_effect = new KillEffect(); + this.kill_effect = new Common.DeathEffect(); if (killEffect.get("increaseCurrentHP") != null) { this.kill_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentHP")).get("min"))); this.kill_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentHP")).get("max"))); @@ -321,10 +260,10 @@ public class Item extends JSONElement { } List conditionsSourceJson = (List) killEffect.get("conditionsSource"); if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.kill_effect.conditions_source = new ArrayList(); + this.kill_effect.conditions_source = new ArrayList<>(); for (Object conditionJsonObj : conditionsSourceJson) { Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); condition.condition_id = (String) conditionJson.get("condition"); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); @@ -363,37 +302,37 @@ public class Item extends JSONElement { if (this.category_id != null) this.category = proj.getItemCategory(this.category_id); if (this.category != null) this.category.addBacklink(this); if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (ConditionEffect ce : this.equip_effect.conditions) { + for (Common.ConditionEffect ce : this.equip_effect.conditions) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect ce : this.hit_effect.conditions_source) { + for (Common.TimedConditionEffect ce : this.hit_effect.conditions_source) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect ce : this.hit_effect.conditions_target) { + for (Common.TimedConditionEffect ce : this.hit_effect.conditions_target) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.hit_received_effect != null && this.hit_received_effect.conditions_source != null) { - for (TimedConditionEffect ce : this.hit_received_effect.conditions_source) { + for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_source) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.hit_received_effect != null && this.hit_received_effect.conditions_target != null) { - for (TimedConditionEffect ce : this.hit_received_effect.conditions_target) { + for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_target) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (TimedConditionEffect ce : this.kill_effect.conditions_source) { + for (Common.TimedConditionEffect ce : this.kill_effect.conditions_source) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } @@ -444,9 +383,9 @@ public class Item extends JSONElement { clone.equip_effect.max_ap_boost = this.equip_effect.max_ap_boost; clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; if (this.equip_effect.conditions != null) { - clone.equip_effect.conditions = new ArrayList(); - for (ConditionEffect c : this.equip_effect.conditions) { - ConditionEffect cclone = new ConditionEffect(); + clone.equip_effect.conditions = new ArrayList<>(); + for (Common.ConditionEffect c : this.equip_effect.conditions) { + Common.ConditionEffect cclone = new Common.ConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -458,15 +397,15 @@ public class Item extends JSONElement { } } if (this.hit_effect != null) { - clone.hit_effect = new HitEffect(); + clone.hit_effect = new Common.HitEffect(); clone.hit_effect.ap_boost_max = this.hit_effect.ap_boost_max; clone.hit_effect.ap_boost_min = this.hit_effect.ap_boost_min; clone.hit_effect.hp_boost_max = this.hit_effect.hp_boost_max; clone.hit_effect.hp_boost_min = this.hit_effect.hp_boost_min; if (this.hit_effect.conditions_source != null) { - clone.hit_effect.conditions_source = new ArrayList(); - for (TimedConditionEffect c : this.hit_effect.conditions_source) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_effect.conditions_source = new ArrayList<>(); + for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -479,9 +418,9 @@ public class Item extends JSONElement { } } if (this.hit_effect.conditions_target != null) { - clone.hit_effect.conditions_target = new ArrayList(); - for (TimedConditionEffect c : this.hit_effect.conditions_target) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_effect.conditions_target = new ArrayList<>(); + for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -495,7 +434,7 @@ public class Item extends JSONElement { } } if (this.hit_received_effect != null) { - clone.hit_received_effect = new HitReceivedEffect(); + clone.hit_received_effect = new Common.HitReceivedEffect(); clone.hit_received_effect.ap_boost_max = this.hit_received_effect.ap_boost_max; clone.hit_received_effect.ap_boost_min = this.hit_received_effect.ap_boost_min; clone.hit_received_effect.hp_boost_max = this.hit_received_effect.hp_boost_max; @@ -505,9 +444,9 @@ public class Item extends JSONElement { clone.hit_received_effect.hp_boost_max_target = this.hit_received_effect.hp_boost_max_target; clone.hit_received_effect.hp_boost_min_target = this.hit_received_effect.hp_boost_min_target; if (this.hit_received_effect.conditions_source != null) { - clone.hit_received_effect.conditions_source = new ArrayList(); - for (TimedConditionEffect c : this.hit_received_effect.conditions_source) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_received_effect.conditions_source = new ArrayList<>(); + for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_source) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -520,9 +459,9 @@ public class Item extends JSONElement { } } if (this.hit_received_effect.conditions_target != null) { - clone.hit_received_effect.conditions_target = new ArrayList(); - for (TimedConditionEffect c : this.hit_received_effect.conditions_target) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_received_effect.conditions_target = new ArrayList<>(); + for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_target) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -536,15 +475,15 @@ public class Item extends JSONElement { } } if (this.kill_effect != null) { - clone.kill_effect = new KillEffect(); + clone.kill_effect = new Common.DeathEffect(); clone.kill_effect.ap_boost_max = this.kill_effect.ap_boost_max; clone.kill_effect.ap_boost_min = this.kill_effect.ap_boost_min; clone.kill_effect.hp_boost_max = this.kill_effect.hp_boost_max; clone.kill_effect.hp_boost_min = this.kill_effect.hp_boost_min; if (this.kill_effect.conditions_source != null) { - clone.kill_effect.conditions_source = new ArrayList(); - for (TimedConditionEffect c : this.kill_effect.conditions_source) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.kill_effect.conditions_source = new ArrayList<>(); + for (Common.TimedConditionEffect c : this.kill_effect.conditions_source) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -568,7 +507,7 @@ public class Item extends JSONElement { if (newOne != null) newOne.addBacklink(this); } else { if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (ConditionEffect c : this.equip_effect.conditions) { + for (Common.ConditionEffect c : this.equip_effect.conditions) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -577,7 +516,7 @@ public class Item extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect c : this.hit_effect.conditions_source) { + for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -586,7 +525,7 @@ public class Item extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect c : this.hit_effect.conditions_target) { + for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -596,7 +535,7 @@ public class Item extends JSONElement { } if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (TimedConditionEffect c : this.kill_effect.conditions_source) { + for (Common.TimedConditionEffect c : this.kill_effect.conditions_source) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -650,7 +589,7 @@ public class Item extends JSONElement { if (this.equip_effect.conditions != null) { List conditionsJson = new ArrayList(); equipEffectJson.put("addedConditions", conditionsJson); - for (ConditionEffect condition : this.equip_effect.conditions) { + for (Common.ConditionEffect condition : this.equip_effect.conditions) { Map conditionJson = new LinkedHashMap(); conditionsJson.add(conditionJson); if (condition.condition != null) { @@ -684,7 +623,7 @@ public class Item extends JSONElement { if (this.hit_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_source) { + for (Common.TimedConditionEffect condition : this.hit_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -700,7 +639,7 @@ public class Item extends JSONElement { if (this.hit_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_target) { + for (Common.TimedConditionEffect condition : this.hit_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -752,7 +691,7 @@ public class Item extends JSONElement { if (this.hit_received_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -768,7 +707,7 @@ public class Item extends JSONElement { if (this.hit_received_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -808,7 +747,7 @@ public class Item extends JSONElement { if (this.kill_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); killEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.kill_effect.conditions_source) { + for (Common.TimedConditionEffect condition : this.kill_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index aa39ee1..4529da5 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -18,6 +18,9 @@ import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.Project; +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.parseHitReceivedEffect; +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.parseTimedConditionEffects; + public class NPC extends JSONElement { private static final long serialVersionUID = 1093728879485491933L; @@ -46,9 +49,9 @@ public class NPC extends JSONElement { public Double critical_multiplier = null; public Integer block_chance = null; public Integer damage_resistance = null; - public HitEffect hit_effect = null; - public HitReceivedEffect hit_received_effect = null; - public DeathEffect death_effect = null; + public Common.HitEffect hit_effect = null; + public Common.HitReceivedEffect hit_received_effect = null; + public Common.DeathEffect death_effect = null; //Available from linked state public Dialogue dialogue = null; @@ -73,40 +76,6 @@ public class NPC extends JSONElement { wholeMap } - public static class DeathEffect { - //Available from parsed state - public Integer hp_boost_min = null; - public Integer hp_boost_max = null; - public Integer ap_boost_min = null; - public Integer ap_boost_max = null; - public List conditions_source = null; - } - - public static class HitEffect extends DeathEffect { - //Available from parsed state - public List conditions_target = null; - } - - public static class HitReceivedEffect extends HitEffect { - //Available from parsed state - public Integer hp_boost_min_target = null; - public Integer hp_boost_max_target = null; - public Integer ap_boost_min_target = null; - public Integer ap_boost_max_target = null; - } - - public static class TimedConditionEffect { - //Available from parsed state - public Integer magnitude = null; - public String condition_id = null; - public Integer duration = null; - public Double chance = null; - - //Available from linked state - public ActorCondition condition = null; - - } - @Override public String getDesc() { return (needsSaving() ? "*" : "")+name+" ("+id+")"; @@ -201,7 +170,7 @@ public class NPC extends JSONElement { Map hitEffect = (Map) npcJson.get("hitEffect"); if (hitEffect != null) { - this.hit_effect = new HitEffect(); + this.hit_effect = new Common.HitEffect(); if (hitEffect.get("increaseCurrentHP") != null) { this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("max"))); this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("min"))); @@ -211,83 +180,17 @@ public class NPC extends JSONElement { this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("min"))); } List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); - if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.hit_effect.conditions_source = new ArrayList(); - for (Object conditionJsonObj : conditionsSourceJson) { - Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_effect.conditions_source.add(condition); - } - } + this.hit_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); - if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) { - this.hit_effect.conditions_target = new ArrayList(); - for (Object conditionJsonObj : conditionsTargetJson) { - Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_effect.conditions_target.add(condition); - } - } + this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); } - Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); - if (hitReceivedEffect != null) { - this.hit_received_effect = new HitReceivedEffect(); - if (hitReceivedEffect.get("increaseCurrentHP") != null) { - this.hit_received_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("max"))); - this.hit_received_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("min"))); - } - if (hitReceivedEffect.get("increaseCurrentAP") != null) { - this.hit_received_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("max"))); - this.hit_received_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("min"))); - } - if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) { - this.hit_received_effect.hp_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max"))); - this.hit_received_effect.hp_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min"))); - } - if (hitReceivedEffect.get("increaseAttackerCurrentAP") != null) { - this.hit_received_effect.ap_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max"))); - this.hit_received_effect.ap_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min"))); - } - List conditionsSourceJson = (List) hitReceivedEffect.get("conditionsSource"); - if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.hit_received_effect.conditions_source = new ArrayList(); - for (Object conditionJsonObj : conditionsSourceJson) { - Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_received_effect.conditions_source.add(condition); - } - } - List conditionsTargetJson = (List) hitReceivedEffect.get("conditionsTarget"); - if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) { - this.hit_received_effect.conditions_target = new ArrayList(); - for (Object conditionJsonObj : conditionsTargetJson) { - Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_received_effect.conditions_target.add(condition); - } - } - } - + Map hitReceivedEffect = (Map) npcJson.get("Common.HitReceivedEffect"); + this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); + Map deathEffect = (Map) npcJson.get("deathEffect"); if (deathEffect != null) { - this.death_effect = new HitEffect(); + this.death_effect = new Common.HitEffect(); if (deathEffect.get("increaseCurrentHP") != null) { this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("max"))); this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("min"))); @@ -297,22 +200,11 @@ public class NPC extends JSONElement { this.death_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentAP")).get("min"))); } List conditionsSourceJson = (List) deathEffect.get("conditionsSource"); - if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.death_effect.conditions_source = new ArrayList(); - for (Object conditionJsonObj : conditionsSourceJson) { - Map conditionJson = (Map)conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.death_effect.conditions_source.add(condition); - } - } + this.death_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); } } - + @Override public void link() { if (this.state == State.created || this.state == State.modified || this.state == State.saved) { @@ -343,31 +235,31 @@ public class NPC extends JSONElement { if (this.droplist != null) this.droplist.addBacklink(this); if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect ce : this.hit_effect.conditions_source) { + for (Common.TimedConditionEffect ce : this.hit_effect.conditions_source) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect ce : this.hit_effect.conditions_target) { + for (Common.TimedConditionEffect ce : this.hit_effect.conditions_target) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.hit_received_effect != null && this.hit_received_effect.conditions_source != null) { - for (TimedConditionEffect ce : this.hit_received_effect.conditions_source) { + for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_source) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.hit_received_effect != null && this.hit_received_effect.conditions_target != null) { - for (TimedConditionEffect ce : this.hit_received_effect.conditions_target) { + for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_target) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } } if (this.death_effect != null && this.death_effect.conditions_source != null) { - for (TimedConditionEffect ce : this.death_effect.conditions_source) { + for (Common.TimedConditionEffect ce : this.death_effect.conditions_source) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(this); } @@ -412,15 +304,15 @@ public class NPC extends JSONElement { clone.droplist_id = this.droplist_id; clone.faction_id = this.faction_id; if (this.hit_effect != null) { - clone.hit_effect = new HitEffect(); + clone.hit_effect = new Common.HitEffect(); clone.hit_effect.ap_boost_max = this.hit_effect.ap_boost_max; clone.hit_effect.ap_boost_min = this.hit_effect.ap_boost_min; clone.hit_effect.hp_boost_max = this.hit_effect.hp_boost_max; clone.hit_effect.hp_boost_min = this.hit_effect.hp_boost_min; if (this.hit_effect.conditions_source != null) { - clone.hit_effect.conditions_source = new ArrayList(); - for (TimedConditionEffect c : this.hit_effect.conditions_source) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_effect.conditions_source = new ArrayList(); + for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -433,9 +325,9 @@ public class NPC extends JSONElement { } } if (this.hit_effect.conditions_target != null) { - clone.hit_effect.conditions_target = new ArrayList(); - for (TimedConditionEffect c : this.hit_effect.conditions_target) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_effect.conditions_target = new ArrayList(); + for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -449,7 +341,7 @@ public class NPC extends JSONElement { } } if (this.hit_received_effect != null) { - clone.hit_received_effect = new HitReceivedEffect(); + clone.hit_received_effect = new Common.HitReceivedEffect(); clone.hit_received_effect.ap_boost_max = this.hit_received_effect.ap_boost_max; clone.hit_received_effect.ap_boost_min = this.hit_received_effect.ap_boost_min; clone.hit_received_effect.hp_boost_max = this.hit_received_effect.hp_boost_max; @@ -459,9 +351,9 @@ public class NPC extends JSONElement { clone.hit_received_effect.hp_boost_max_target = this.hit_received_effect.hp_boost_max_target; clone.hit_received_effect.hp_boost_min_target = this.hit_received_effect.hp_boost_min_target; if (this.hit_received_effect.conditions_source != null) { - clone.hit_received_effect.conditions_source = new ArrayList(); - for (TimedConditionEffect c : this.hit_received_effect.conditions_source) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_received_effect.conditions_source = new ArrayList(); + for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_source) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -474,9 +366,9 @@ public class NPC extends JSONElement { } } if (this.hit_received_effect.conditions_target != null) { - clone.hit_received_effect.conditions_target = new ArrayList(); - for (TimedConditionEffect c : this.hit_received_effect.conditions_target) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.hit_received_effect.conditions_target = new ArrayList(); + for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_target) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -490,15 +382,15 @@ public class NPC extends JSONElement { } } if (this.death_effect != null) { - clone.death_effect = new DeathEffect(); + clone.death_effect = new Common.DeathEffect(); clone.death_effect.ap_boost_max = this.death_effect.ap_boost_max; clone.death_effect.ap_boost_min = this.death_effect.ap_boost_min; clone.death_effect.hp_boost_max = this.death_effect.hp_boost_max; clone.death_effect.hp_boost_min = this.death_effect.hp_boost_min; if (this.death_effect.conditions_source != null) { - clone.death_effect.conditions_source = new ArrayList(); - for (TimedConditionEffect c : this.death_effect.conditions_source) { - TimedConditionEffect cclone = new TimedConditionEffect(); + clone.death_effect.conditions_source = new ArrayList(); + for (Common.TimedConditionEffect c : this.death_effect.conditions_source) { + Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -534,7 +426,7 @@ public class NPC extends JSONElement { if (newOne != null) newOne.addBacklink(this); } else { if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect tce : this.hit_effect.conditions_source) { + for (Common.TimedConditionEffect tce : this.hit_effect.conditions_source) { if (tce.condition == oldOne) { oldOne.removeBacklink(this); tce.condition = (ActorCondition) newOne; @@ -543,7 +435,7 @@ public class NPC extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect tce : this.hit_effect.conditions_target) { + for (Common.TimedConditionEffect tce : this.hit_effect.conditions_target) { if (tce.condition == oldOne) { oldOne.removeBacklink(this); tce.condition = (ActorCondition) newOne; @@ -616,7 +508,7 @@ public class NPC extends JSONElement { if (this.hit_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_source) { + for (Common.TimedConditionEffect condition : this.hit_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -632,7 +524,7 @@ public class NPC extends JSONElement { if (this.hit_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_target) { + for (Common.TimedConditionEffect condition : this.hit_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -675,7 +567,7 @@ public class NPC extends JSONElement { } if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); + hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); if (this.hit_received_effect.ap_boost_min_target != null) apJson.put("min", this.hit_received_effect.ap_boost_min_target); else apJson.put("min", 0); if (this.hit_received_effect.ap_boost_max_target != null) apJson.put("max", this.hit_received_effect.ap_boost_max_target); @@ -684,7 +576,7 @@ public class NPC extends JSONElement { if (this.hit_received_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -700,7 +592,7 @@ public class NPC extends JSONElement { if (this.hit_received_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -736,7 +628,7 @@ public class NPC extends JSONElement { if (this.death_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); deathEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.death_effect.conditions_source) { + for (Common.TimedConditionEffect condition : this.death_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 55e8db3..e84ca30 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -32,6 +32,7 @@ import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; +import com.gpl.rpg.atcontentstudio.model.gamedata.Common; import com.gpl.rpg.atcontentstudio.model.gamedata.Item; import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; @@ -53,12 +54,12 @@ public class ItemEditor extends JSONElementEditor { private static final String useLabel = "Effect on use: "; - private Item.ConditionEffect selectedEquipEffectCondition; - private Item.TimedConditionEffect selectedHitEffectSourceCondition; - private Item.TimedConditionEffect selectedHitEffectTargetCondition; - private Item.TimedConditionEffect selectedKillEffectCondition; - private Item.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private Item.TimedConditionEffect selectedHitReceivedEffectTargetCondition; + private Common.ConditionEffect selectedEquipEffectCondition; + private Common.TimedConditionEffect selectedHitEffectSourceCondition; + private Common.TimedConditionEffect selectedHitEffectTargetCondition; + private Common.TimedConditionEffect selectedKillEffectCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; private JButton itemIcon; @@ -97,7 +98,7 @@ public class ItemEditor extends JSONElementEditor { private JSpinner equipConditionMagnitude; private CollapsiblePanel hitEffectPane; - private Item.HitEffect hitEffect; + private Common.HitEffect hitEffect; private JSpinner hitHPMin; private JSpinner hitHPMax; private JSpinner hitAPMin; @@ -128,7 +129,7 @@ public class ItemEditor extends JSONElementEditor { private JSpinner hitTargetConditionDuration; private CollapsiblePanel killEffectPane; - private Item.KillEffect killEffect; + private Common.DeathEffect killEffect; private JSpinner killHPMin; private JSpinner killHPMax; private JSpinner killAPMin; @@ -147,7 +148,7 @@ public class ItemEditor extends JSONElementEditor { private JSpinner killSourceConditionDuration; private CollapsiblePanel hitReceivedEffectPane; - private Item.HitReceivedEffect hitReceivedEffect; + private Common.HitReceivedEffect hitReceivedEffect; private JSpinner hitReceivedHPMin; private JSpinner hitReceivedHPMax; private JSpinner hitReceivedAPMin; @@ -243,7 +244,7 @@ public class ItemEditor extends JSONElementEditor { equipConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedEquipEffectCondition = (Item.ConditionEffect) equipConditionsList.getSelectedValue(); + selectedEquipEffectCondition = (Common.ConditionEffect) equipConditionsList.getSelectedValue(); if (selectedEquipEffectCondition == null) { deleteEquipCondition.setEnabled(false); } else { @@ -258,7 +259,7 @@ public class ItemEditor extends JSONElementEditor { createEquipCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Item.ConditionEffect condition = new Item.ConditionEffect(); + Common.ConditionEffect condition = new Common.ConditionEffect(); equipConditionsModel.addItem(condition); equipConditionsList.setSelectedValue(condition, true); listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -295,7 +296,7 @@ public class ItemEditor extends JSONElementEditor { hitEffectPane = new CollapsiblePanel("Effect on every hit: "); hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); if (item.hit_effect == null) { - hitEffect = new Item.HitEffect(); + hitEffect = new Common.HitEffect(); } else { hitEffect = item.hit_effect; } @@ -316,7 +317,7 @@ public class ItemEditor extends JSONElementEditor { hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (Item.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); + selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); updateHitSourceTimedConditionEditorPane(sourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); if (selectedHitEffectSourceCondition == null) { deleteHitSourceCondition.setEnabled(false); @@ -331,7 +332,7 @@ public class ItemEditor extends JSONElementEditor { createHitSourceCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Item.TimedConditionEffect condition = new Item.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitSourceConditionsModel.addItem(condition); hitSourceConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -373,7 +374,7 @@ public class ItemEditor extends JSONElementEditor { hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (Item.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); + selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); updateHitTargetTimedConditionEditorPane(targetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); if (selectedHitEffectTargetCondition == null) { deleteHitTargetCondition.setEnabled(false); @@ -388,7 +389,7 @@ public class ItemEditor extends JSONElementEditor { createHitTargetCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Item.TimedConditionEffect condition = new Item.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitTargetConditionsModel.addItem(condition); hitTargetConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -427,7 +428,7 @@ public class ItemEditor extends JSONElementEditor { killEffectPane = new CollapsiblePanel(killLabel); killEffectPane.setLayout(new JideBoxLayout(killEffectPane, JideBoxLayout.PAGE_AXIS)); if (item.kill_effect == null) { - killEffect = new Item.KillEffect(); + killEffect = new Common.DeathEffect(); } else { killEffect = item.kill_effect; } @@ -448,7 +449,7 @@ public class ItemEditor extends JSONElementEditor { killSourceConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedKillEffectCondition = (Item.TimedConditionEffect) killSourceConditionsList.getSelectedValue(); + selectedKillEffectCondition = (Common.TimedConditionEffect) killSourceConditionsList.getSelectedValue(); updateKillSourceTimedConditionEditorPane(killSourceTimedConditionsEditorPane, selectedKillEffectCondition, listener); if (selectedKillEffectCondition == null) { deleteKillSourceCondition.setEnabled(false); @@ -463,7 +464,7 @@ public class ItemEditor extends JSONElementEditor { createKillSourceCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Item.TimedConditionEffect condition = new Item.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); killSourceConditionsModel.addItem(condition); killSourceConditionsList.setSelectedValue(condition, true); listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -501,7 +502,7 @@ public class ItemEditor extends JSONElementEditor { hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); if (item.hit_received_effect == null) { - hitReceivedEffect = new Item.HitReceivedEffect(); + hitReceivedEffect = new Common.HitReceivedEffect(); } else { hitReceivedEffect = item.hit_received_effect; } @@ -526,7 +527,7 @@ public class ItemEditor extends JSONElementEditor { hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (Item.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); + selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); if (selectedHitReceivedEffectSourceCondition == null) { deleteHitReceivedSourceCondition.setEnabled(false); @@ -541,7 +542,7 @@ public class ItemEditor extends JSONElementEditor { createHitReceivedSourceCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Item.TimedConditionEffect condition = new Item.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitReceivedSourceConditionsModel.addItem(condition); hitReceivedSourceConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -583,7 +584,7 @@ public class ItemEditor extends JSONElementEditor { hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (Item.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); + selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); if (selectedHitReceivedEffectTargetCondition == null) { deleteHitReceivedTargetCondition.setEnabled(false); @@ -598,7 +599,7 @@ public class ItemEditor extends JSONElementEditor { createHitReceivedTargetCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - Item.TimedConditionEffect condition = new Item.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitReceivedTargetConditionsModel.addItem(condition); hitReceivedTargetConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -655,7 +656,7 @@ public class ItemEditor extends JSONElementEditor { } - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Item.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitSourceConditionBox != null) { removeElementListener(hitSourceConditionBox); @@ -733,7 +734,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitSourceTimedConditionWidgets(Item.TimedConditionEffect condition) { + public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -751,7 +752,7 @@ public class ItemEditor extends JSONElementEditor { hitSourceConditionForever.setEnabled(!clear); } - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Item.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitTargetConditionBox != null) { removeElementListener(hitTargetConditionBox); @@ -829,7 +830,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitTargetTimedConditionWidgets(Item.TimedConditionEffect condition) { + public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -847,7 +848,7 @@ public class ItemEditor extends JSONElementEditor { hitTargetConditionForever.setEnabled(!clear); } - public void updateKillSourceTimedConditionEditorPane(JPanel pane, Item.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (killSourceConditionBox != null) { removeElementListener(killSourceConditionBox); @@ -925,7 +926,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateKillSourceTimedConditionWidgets(Item.TimedConditionEffect condition) { + public void updateKillSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -943,7 +944,7 @@ public class ItemEditor extends JSONElementEditor { killSourceConditionForever.setEnabled(!clear); } - public void updateEquipConditionEditorPane(JPanel pane, Item.ConditionEffect condition, final FieldUpdateListener listener) { + public void updateEquipConditionEditorPane(JPanel pane, Common.ConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (equipConditionBox != null) { removeElementListener(equipConditionBox); @@ -991,7 +992,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Item.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedSourceConditionBox != null) { removeElementListener(hitReceivedSourceConditionBox); @@ -1069,7 +1070,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedSourceTimedConditionWidgets(Item.TimedConditionEffect condition) { + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -1087,7 +1088,7 @@ public class ItemEditor extends JSONElementEditor { hitReceivedSourceConditionForever.setEnabled(!clear); } - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Item.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedTargetConditionBox != null) { removeElementListener(hitReceivedTargetConditionBox); @@ -1165,7 +1166,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedTargetTimedConditionWidgets(Item.TimedConditionEffect condition) { + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -1184,11 +1185,11 @@ public class ItemEditor extends JSONElementEditor { } - public static class SourceTimedConditionsListModel implements ListModel { + public static class SourceTimedConditionsListModel implements ListModel { - Item.KillEffect source; + Common.DeathEffect source; - public SourceTimedConditionsListModel(Item.KillEffect effect) { + public SourceTimedConditionsListModel(Common.DeathEffect effect) { this.source = effect;; } @@ -1199,14 +1200,14 @@ public class ItemEditor extends JSONElementEditor { } @Override - public Item.TimedConditionEffect getElementAt(int index) { + public Common.TimedConditionEffect getElementAt(int index) { if (source.conditions_source == null) return null; return source.conditions_source.get(index); } - public void addItem(Item.TimedConditionEffect item) { + public void addItem(Common.TimedConditionEffect item) { if (source.conditions_source == null) { - source.conditions_source = new ArrayList(); + source.conditions_source = new ArrayList(); } source.conditions_source.add(item); int index = source.conditions_source.indexOf(item); @@ -1215,7 +1216,7 @@ public class ItemEditor extends JSONElementEditor { } } - public void removeItem(Item.TimedConditionEffect item) { + public void removeItem(Common.TimedConditionEffect item) { int index = source.conditions_source.indexOf(item); source.conditions_source.remove(item); if (source.conditions_source.isEmpty()) { @@ -1226,7 +1227,7 @@ public class ItemEditor extends JSONElementEditor { } } - public void itemChanged(Item.TimedConditionEffect item) { + public void itemChanged(Common.TimedConditionEffect item) { int index = source.conditions_source.indexOf(item); for (ListDataListener l : listeners) { l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); @@ -1246,11 +1247,11 @@ public class ItemEditor extends JSONElementEditor { } } - public static class TargetTimedConditionsListModel implements ListModel { + public static class TargetTimedConditionsListModel implements ListModel { - Item.HitEffect source; + Common.HitEffect source; - public TargetTimedConditionsListModel(Item.HitEffect effect) { + public TargetTimedConditionsListModel(Common.HitEffect effect) { this.source = effect;; } @@ -1261,14 +1262,14 @@ public class ItemEditor extends JSONElementEditor { } @Override - public Item.TimedConditionEffect getElementAt(int index) { + public Common.TimedConditionEffect getElementAt(int index) { if (source.conditions_target == null) return null; return source.conditions_target.get(index); } - public void addItem(Item.TimedConditionEffect item) { + public void addItem(Common.TimedConditionEffect item) { if (source.conditions_target == null) { - source.conditions_target = new ArrayList(); + source.conditions_target = new ArrayList(); } source.conditions_target.add(item); int index = source.conditions_target.indexOf(item); @@ -1277,7 +1278,7 @@ public class ItemEditor extends JSONElementEditor { } } - public void removeItem(Item.TimedConditionEffect item) { + public void removeItem(Common.TimedConditionEffect item) { int index = source.conditions_target.indexOf(item); source.conditions_target.remove(item); if (source.conditions_target.isEmpty()) { @@ -1288,7 +1289,7 @@ public class ItemEditor extends JSONElementEditor { } } - public void itemChanged(Item.TimedConditionEffect item) { + public void itemChanged(Common.TimedConditionEffect item) { int index = source.conditions_target.indexOf(item); for (ListDataListener l : listeners) { l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); @@ -1316,7 +1317,7 @@ public class ItemEditor extends JSONElementEditor { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JLabel) { JLabel label = ((JLabel)c); - Item.TimedConditionEffect effect = (Item.TimedConditionEffect) value; + Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; if (effect.condition != null) { @@ -1342,7 +1343,7 @@ public class ItemEditor extends JSONElementEditor { } } - public static class ConditionsListModel implements ListModel { + public static class ConditionsListModel implements ListModel { Item.EquipEffect source; @@ -1357,14 +1358,14 @@ public class ItemEditor extends JSONElementEditor { } @Override - public Item.ConditionEffect getElementAt(int index) { + public Common.ConditionEffect getElementAt(int index) { if (source.conditions == null) return null; return source.conditions.get(index); } - public void addItem(Item.ConditionEffect item) { + public void addItem(Common.ConditionEffect item) { if (source.conditions == null) { - source.conditions = new ArrayList(); + source.conditions = new ArrayList(); } source.conditions.add(item); int index = source.conditions.indexOf(item); @@ -1373,7 +1374,7 @@ public class ItemEditor extends JSONElementEditor { } } - public void removeItem(Item.ConditionEffect item) { + public void removeItem(Common.ConditionEffect item) { int index = source.conditions.indexOf(item); source.conditions.remove(item); if (source.conditions.isEmpty()) { @@ -1384,7 +1385,7 @@ public class ItemEditor extends JSONElementEditor { } } - public void itemChanged(Item.ConditionEffect item) { + public void itemChanged(Common.ConditionEffect item) { int index = source.conditions.indexOf(item); for (ListDataListener l : listeners) { l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); @@ -1412,7 +1413,7 @@ public class ItemEditor extends JSONElementEditor { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JLabel) { JLabel label = ((JLabel)c); - Item.ConditionEffect effect = (Item.ConditionEffect) value; + Common.ConditionEffect effect = (Common.ConditionEffect) value; if (effect.condition != null) { if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { @@ -1450,7 +1451,7 @@ public class ItemEditor extends JSONElementEditor { } - public static boolean isNull(Item.HitEffect effect) { + public static boolean isNull(Common.HitEffect effect) { if (effect.ap_boost_min != null) return false; if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; @@ -1461,7 +1462,7 @@ public class ItemEditor extends JSONElementEditor { } - public static boolean isNull(Item.KillEffect effect) { + public static boolean isNull(Common.DeathEffect effect) { if (effect.ap_boost_min != null) return false; if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; @@ -1470,7 +1471,7 @@ public class ItemEditor extends JSONElementEditor { return true; } - public static boolean isNull(Item.HitReceivedEffect effect) { + public static boolean isNull(Common.HitReceivedEffect effect) { if (effect.ap_boost_min != null) return false; if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 639c33d..fba51e1 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -32,10 +32,7 @@ import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; @@ -53,11 +50,11 @@ public class NPCEditor extends JSONElementEditor { private static final String json_view_id = "JSON"; private static final String dialogue_tree_id = "Dialogue Tree"; - private NPC.TimedConditionEffect selectedHitEffectSourceCondition; - private NPC.TimedConditionEffect selectedHitEffectTargetCondition; - private NPC.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private NPC.TimedConditionEffect selectedHitReceivedEffectTargetCondition; - private NPC.TimedConditionEffect selectedDeathEffectSourceCondition; + private Common.TimedConditionEffect selectedHitEffectSourceCondition; + private Common.TimedConditionEffect selectedHitEffectTargetCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; + private Common.TimedConditionEffect selectedDeathEffectSourceCondition; private JButton npcIcon; private JTextField idField; @@ -86,7 +83,7 @@ public class NPCEditor extends JSONElementEditor { private JSpinner blockChance; private JSpinner dmgRes; - private NPC.HitEffect hitEffect; + private Common.HitEffect hitEffect; private CollapsiblePanel hitEffectPane; private JSpinner hitEffectHPMin; private JSpinner hitEffectHPMax; @@ -119,7 +116,7 @@ public class NPCEditor extends JSONElementEditor { private JRadioButton hitTargetConditionForever; private JSpinner hitTargetConditionDuration; - private NPC.HitReceivedEffect hitReceivedEffect; + private Common.HitReceivedEffect hitReceivedEffect; private CollapsiblePanel hitReceivedEffectPane; private JSpinner hitReceivedEffectHPMin; private JSpinner hitReceivedEffectHPMax; @@ -156,7 +153,7 @@ public class NPCEditor extends JSONElementEditor { private JRadioButton hitReceivedTargetConditionForever; private JSpinner hitReceivedTargetConditionDuration; - private NPC.DeathEffect deathEffect; + private Common.DeathEffect deathEffect; private CollapsiblePanel deathEffectPane; private JSpinner deathEffectHPMin; private JSpinner deathEffectHPMax; @@ -270,7 +267,7 @@ public class NPCEditor extends JSONElementEditor { hitEffectPane = new CollapsiblePanel("Effect on every hit: "); hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); if (npc.hit_effect == null) { - hitEffect = new NPC.HitEffect(); + hitEffect = new Common.HitEffect(); } else { hitEffect = npc.hit_effect; } @@ -292,7 +289,7 @@ public class NPCEditor extends JSONElementEditor { hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (NPC.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); + selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); updateHitSourceTimedConditionEditorPane(hitSourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); } }); @@ -302,7 +299,7 @@ public class NPCEditor extends JSONElementEditor { createHitSourceCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - NPC.TimedConditionEffect condition = new NPC.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitSourceConditionsListModel.addItem(condition); hitSourceConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -344,7 +341,7 @@ public class NPCEditor extends JSONElementEditor { hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (NPC.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); + selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); updateHitTargetTimedConditionEditorPane(hitTargetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); } }); @@ -354,7 +351,7 @@ public class NPCEditor extends JSONElementEditor { createHitTargetCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - NPC.TimedConditionEffect condition = new NPC.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitTargetConditionsListModel.addItem(condition); hitTargetConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -388,7 +385,7 @@ public class NPCEditor extends JSONElementEditor { hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); if (npc.hit_received_effect == null) { - hitReceivedEffect = new NPC.HitReceivedEffect(); + hitReceivedEffect = new Common.HitReceivedEffect(); } else { hitReceivedEffect = npc.hit_received_effect; } @@ -414,7 +411,7 @@ public class NPCEditor extends JSONElementEditor { hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (NPC.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); + selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); } }); @@ -424,7 +421,7 @@ public class NPCEditor extends JSONElementEditor { createHitReceivedSourceCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - NPC.TimedConditionEffect condition = new NPC.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitReceivedSourceConditionsListModel.addItem(condition); hitReceivedSourceConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -466,7 +463,7 @@ public class NPCEditor extends JSONElementEditor { hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (NPC.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); + selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); } }); @@ -476,7 +473,7 @@ public class NPCEditor extends JSONElementEditor { createHitReceivedTargetCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - NPC.TimedConditionEffect condition = new NPC.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); hitReceivedTargetConditionsListModel.addItem(condition); hitReceivedTargetConditionsList.setSelectedValue(condition, true); listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -510,7 +507,7 @@ public class NPCEditor extends JSONElementEditor { deathEffectPane = new CollapsiblePanel("Effect when killed: "); deathEffectPane.setLayout(new JideBoxLayout(deathEffectPane, JideBoxLayout.PAGE_AXIS)); if (npc.death_effect == null) { - deathEffect = new NPC.DeathEffect(); + deathEffect = new Common.DeathEffect(); } else { deathEffect = npc.death_effect; } @@ -532,7 +529,7 @@ public class NPCEditor extends JSONElementEditor { deathSourceConditionsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { - selectedDeathEffectSourceCondition = (NPC.TimedConditionEffect) deathSourceConditionsList.getSelectedValue(); + selectedDeathEffectSourceCondition = (Common.TimedConditionEffect) deathSourceConditionsList.getSelectedValue(); updateDeathSourceTimedConditionEditorPane(deathSourceTimedConditionsEditorPane, selectedDeathEffectSourceCondition, listener); } }); @@ -542,7 +539,7 @@ public class NPCEditor extends JSONElementEditor { createDeathSourceCondition.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - NPC.TimedConditionEffect condition = new NPC.TimedConditionEffect(); + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); deathSourceConditionsListModel.addItem(condition); deathSourceConditionsList.setSelectedValue(condition, true); listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. @@ -577,7 +574,7 @@ public class NPCEditor extends JSONElementEditor { pane.add(combatTraitPane, JideBoxLayout.FIX); } - public void updateHitSourceTimedConditionEditorPane(JPanel pane, NPC.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitSourceConditionBox != null) { removeElementListener(hitSourceConditionBox); @@ -649,7 +646,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitSourceTimedConditionWidgets(NPC.TimedConditionEffect condition) { + public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -668,7 +665,7 @@ public class NPCEditor extends JSONElementEditor { } - public void updateHitTargetTimedConditionEditorPane(JPanel pane, NPC.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitTargetConditionBox != null) { removeElementListener(hitTargetConditionBox); @@ -739,7 +736,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitTargetTimedConditionWidgets(NPC.TimedConditionEffect condition) { + public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -758,7 +755,7 @@ public class NPCEditor extends JSONElementEditor { } - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, NPC.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedSourceConditionBox != null) { removeElementListener(hitReceivedSourceConditionBox); @@ -830,7 +827,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedSourceTimedConditionWidgets(NPC.TimedConditionEffect condition) { + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -849,7 +846,7 @@ public class NPCEditor extends JSONElementEditor { } - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, NPC.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedTargetConditionBox != null) { removeElementListener(hitReceivedTargetConditionBox); @@ -920,7 +917,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedTargetTimedConditionWidgets(NPC.TimedConditionEffect condition) { + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -938,7 +935,7 @@ public class NPCEditor extends JSONElementEditor { hitReceivedTargetConditionForever.setEnabled(!clear); } - public void updateDeathSourceTimedConditionEditorPane(JPanel pane, NPC.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (deathSourceConditionBox != null) { removeElementListener(deathSourceConditionBox); @@ -1010,7 +1007,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateDeathSourceTimedConditionWidgets(NPC.TimedConditionEffect condition) { + public void updateDeathSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -1028,11 +1025,11 @@ public class NPCEditor extends JSONElementEditor { deathSourceConditionForever.setEnabled(!clear); } - public static class TargetTimedConditionsListModel implements ListModel { + public static class TargetTimedConditionsListModel implements ListModel { - NPC.HitEffect source; + Common.HitEffect source; - public TargetTimedConditionsListModel(NPC.HitEffect effect) { + public TargetTimedConditionsListModel(Common.HitEffect effect) { this.source = effect; } @@ -1043,14 +1040,14 @@ public class NPCEditor extends JSONElementEditor { } @Override - public NPC.TimedConditionEffect getElementAt(int index) { + public Common.TimedConditionEffect getElementAt(int index) { if (source.conditions_target == null) return null; return source.conditions_target.get(index); } - public void addItem(NPC.TimedConditionEffect item) { + public void addItem(Common.TimedConditionEffect item) { if (source.conditions_target == null) { - source.conditions_target = new ArrayList(); + source.conditions_target = new ArrayList(); } source.conditions_target.add(item); int index = source.conditions_target.indexOf(item); @@ -1059,7 +1056,7 @@ public class NPCEditor extends JSONElementEditor { } } - public void removeItem(NPC.TimedConditionEffect item) { + public void removeItem(Common.TimedConditionEffect item) { int index = source.conditions_target.indexOf(item); source.conditions_target.remove(item); if (source.conditions_target.isEmpty()) { @@ -1070,7 +1067,7 @@ public class NPCEditor extends JSONElementEditor { } } - public void itemChanged(NPC.TimedConditionEffect item) { + public void itemChanged(Common.TimedConditionEffect item) { int index = source.conditions_target.indexOf(item); for (ListDataListener l : listeners) { l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); @@ -1090,11 +1087,11 @@ public class NPCEditor extends JSONElementEditor { } } - public static class SourceTimedConditionsListModel implements ListModel { + public static class SourceTimedConditionsListModel implements ListModel { - NPC.DeathEffect source; + Common.DeathEffect source; - public SourceTimedConditionsListModel(NPC.DeathEffect effect) { + public SourceTimedConditionsListModel(Common.DeathEffect effect) { this.source = effect; } @@ -1105,14 +1102,14 @@ public class NPCEditor extends JSONElementEditor { } @Override - public NPC.TimedConditionEffect getElementAt(int index) { + public Common.TimedConditionEffect getElementAt(int index) { if (source.conditions_source == null) return null; return source.conditions_source.get(index); } - public void addItem(NPC.TimedConditionEffect item) { + public void addItem(Common.TimedConditionEffect item) { if (source.conditions_source == null) { - source.conditions_source = new ArrayList(); + source.conditions_source = new ArrayList(); } source.conditions_source.add(item); int index = source.conditions_source.indexOf(item); @@ -1121,7 +1118,7 @@ public class NPCEditor extends JSONElementEditor { } } - public void removeItem(NPC.TimedConditionEffect item) { + public void removeItem(Common.TimedConditionEffect item) { int index = source.conditions_source.indexOf(item); source.conditions_source.remove(item); if (source.conditions_source.isEmpty()) { @@ -1132,7 +1129,7 @@ public class NPCEditor extends JSONElementEditor { } } - public void itemChanged(NPC.TimedConditionEffect item) { + public void itemChanged(Common.TimedConditionEffect item) { int index = source.conditions_source.indexOf(item); for (ListDataListener l : listeners) { l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); @@ -1160,7 +1157,7 @@ public class NPCEditor extends JSONElementEditor { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JLabel) { JLabel label = ((JLabel)c); - NPC.TimedConditionEffect effect = (NPC.TimedConditionEffect) value; + Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; if (effect.condition != null) { @@ -1186,7 +1183,7 @@ public class NPCEditor extends JSONElementEditor { } } - public static boolean isNull(NPC.HitEffect effect) { + public static boolean isNull(Common.HitEffect effect) { if (effect.ap_boost_min != null) return false; if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; @@ -1196,7 +1193,7 @@ public class NPCEditor extends JSONElementEditor { return true; } - public static boolean isNull(NPC.HitReceivedEffect effect) { + public static boolean isNull(Common.HitReceivedEffect effect) { if (effect.ap_boost_min != null) return false; if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; @@ -1210,7 +1207,7 @@ public class NPCEditor extends JSONElementEditor { return true; } - public static boolean isNull(NPC.DeathEffect effect) { + public static boolean isNull(Common.DeathEffect effect) { if (effect.ap_boost_min != null) return false; if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java index 4a9205e..1df2fc9 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java @@ -5,14 +5,7 @@ import java.util.List; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.maps.ContainerArea; import com.gpl.rpg.atcontentstudio.model.maps.KeyArea; import com.gpl.rpg.atcontentstudio.model.maps.MapChange; @@ -111,18 +104,18 @@ public class GDEVisitor { visit(element.category, visited, includeSource); if (element.icon_id != null) visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); if (element.equip_effect != null && element.equip_effect.conditions != null) { - for (Item.ConditionEffect condEffect : element.equip_effect.conditions) { + for (Common.ConditionEffect condEffect : element.equip_effect.conditions) { visit(condEffect.condition, visited, includeSource); } } if (element.hit_effect != null) { if (element.hit_effect.conditions_source != null) { - for (Item.ConditionEffect condEffect : element.hit_effect.conditions_source) { + for (Common.ConditionEffect condEffect : element.hit_effect.conditions_source) { visit(condEffect.condition, visited, includeSource); } } if (element.hit_effect.conditions_target != null) { - for (Item.ConditionEffect condEffect : element.hit_effect.conditions_target) { + for (Common.ConditionEffect condEffect : element.hit_effect.conditions_target) { visit(condEffect.condition, visited, includeSource); } } @@ -144,12 +137,12 @@ public class GDEVisitor { if (element.icon_id != null) visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); if (element.hit_effect != null) { if (element.hit_effect.conditions_source != null) { - for (NPC.TimedConditionEffect condEffect : element.hit_effect.conditions_source) { + for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_source) { visit(condEffect.condition, visited, includeSource); } } if (element.hit_effect.conditions_target != null) { - for (NPC.TimedConditionEffect condEffect : element.hit_effect.conditions_target) { + for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_target) { visit(condEffect.condition, visited, includeSource); } } From e232c333392380e8f5f19a47f6c909a1ee372b6d Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 3 May 2025 19:22:50 +0200 Subject: [PATCH 02/94] more de-duplication --- .../model/gamedata/Common.java | 117 +++++++++-- .../atcontentstudio/model/gamedata/Item.java | 194 ++---------------- .../atcontentstudio/model/gamedata/NPC.java | 105 +--------- 3 files changed, 121 insertions(+), 295 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 3f34836..c7425a6 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -1,5 +1,7 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -10,6 +12,16 @@ public final class Common { //Available from parsed state public Integer duration = null; public Double chance = null; + + public TimedConditionEffect createClone() { + TimedConditionEffect cclone = new TimedConditionEffect(); + cclone.magnitude = this.magnitude; + cclone.condition_id = this.condition_id; + cclone.condition = this.condition; + cclone.chance = this.chance; + cclone.duration = this.duration; + return cclone; + } } public static class ConditionEffect { @@ -25,12 +37,11 @@ public final class Common { public static ArrayList parseTimedConditionEffects(List conditionsSourceJson) { ArrayList conditions_source; if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - conditions_source = new ArrayList(); + conditions_source = new ArrayList<>(); for (Object conditionJsonObj : conditionsSourceJson) { Map conditionJson = (Map) conditionJsonObj; TimedConditionEffect condition = new TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); + readConditionEffect(condition, conditionJson); condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); @@ -43,20 +54,29 @@ public final class Common { } @SuppressWarnings("rawtypes") - public static HitReceivedEffect parseHitReceivedEffect(Map hitReceivedEffect) { - if (hitReceivedEffect == null) { - return null; - } + private static void readConditionEffect(ConditionEffect condition, Map conditionJson) { + condition.condition_id = (String) conditionJson.get("condition"); + condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); + } + @SuppressWarnings("rawtypes") + public static Common.DeathEffect parseDeathEffect(Map killEffect) { + Common.DeathEffect kill_effect = new Common.DeathEffect(); + readDeathEffect(killEffect, kill_effect); + return kill_effect; + } + + @SuppressWarnings("rawtypes") + public static HitEffect parseHitEffect(Map hitEffect) { + Common.HitEffect hit_effect = new Common.HitEffect(); + readHitEffect(hitEffect, hit_effect); + return hit_effect; + } + + @SuppressWarnings("rawtypes") + public static HitReceivedEffect parseHitReceivedEffect(Map hitReceivedEffect) { HitReceivedEffect hit_received_effect = new Common.HitReceivedEffect(); - if (hitReceivedEffect.get("increaseCurrentHP") != null) { - hit_received_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentHP")).get("max"))); - hit_received_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentHP")).get("min"))); - } - if (hitReceivedEffect.get("increaseCurrentAP") != null) { - hit_received_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentAP")).get("max"))); - hit_received_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseCurrentAP")).get("min"))); - } + readHitEffect(hitReceivedEffect, hit_received_effect); if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) { hit_received_effect.hp_boost_max_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max"))); hit_received_effect.hp_boost_min_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min"))); @@ -65,14 +85,29 @@ public final class Common { hit_received_effect.ap_boost_max_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max"))); hit_received_effect.ap_boost_min_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min"))); } - List conditionsSourceJson = (List) hitReceivedEffect.get("conditionsSource"); - hit_received_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); - List conditionsTargetJson = (List) hitReceivedEffect.get("conditionsTarget"); - hit_received_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); return hit_received_effect; } + @SuppressWarnings("rawtypes") + private static void readDeathEffect(Map killEffect, DeathEffect kill_effect) { + if (killEffect.get("increaseCurrentHP") != null) { + kill_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentHP")).get("min"))); + kill_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentHP")).get("max"))); + } + if (killEffect.get("increaseCurrentAP") != null) { + kill_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentAP")).get("min"))); + kill_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) killEffect.get("increaseCurrentAP")).get("max"))); + } + List conditionsSourceJson = (List) killEffect.get("conditionsSource"); + kill_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); + } + @SuppressWarnings("rawtypes") + private static void readHitEffect(Map hitEffect, HitEffect hit_effect) { + readDeathEffect(hitEffect, hit_effect); + List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); + hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); + } public static class DeathEffect { @@ -81,12 +116,12 @@ public final class Common { public Integer hp_boost_max = null; public Integer ap_boost_min = null; public Integer ap_boost_max = null; - public List conditions_source = null; + public List conditions_source = null; } public static class HitEffect extends DeathEffect { //Available from parsed state - public List conditions_target = null; + public List conditions_target = null; } public static class HitReceivedEffect extends Common.HitEffect { @@ -97,4 +132,44 @@ public final class Common { public Integer ap_boost_max_target = null; } + + public static void copyDeathEffectValues(Common.DeathEffect target, Common.DeathEffect source, GameDataElement backlink) { + target.ap_boost_max = source.ap_boost_max; + target.ap_boost_min = source.ap_boost_min; + target.hp_boost_max = source.hp_boost_max; + target.hp_boost_min = source.hp_boost_min; + if (source.conditions_source != null) { + target.conditions_source = new ArrayList<>(); + for (Common.TimedConditionEffect c : source.conditions_source) { + Common.TimedConditionEffect cclone = c.createClone(); + if (cclone.condition != null) { + cclone.condition.addBacklink(backlink); + } + target.conditions_source.add(cclone); + } + } + } + + public static void copyHitEffectValues(Common.HitEffect target, Common.HitEffect source, GameDataElement backlink) { + copyDeathEffectValues(target, source, backlink); + if (source.conditions_target != null) { + target.conditions_target = new ArrayList<>(); + for (Common.TimedConditionEffect c : source.conditions_target) { + Common.TimedConditionEffect cclone = c.createClone(); + if (cclone.condition != null) { + cclone.condition.addBacklink(backlink); + } + target.conditions_target.add(cclone); + } + } + } + + public static void copyHitReceivedEffectValues(Common.HitReceivedEffect target, Common.HitReceivedEffect source, GameDataElement backlink) { + copyHitEffectValues(target, source, backlink); + target.ap_boost_max_target = source.ap_boost_max_target; + target.ap_boost_min_target = source.ap_boost_min_target; + target.hp_boost_max_target = source.hp_boost_max_target; + target.hp_boost_min_target = source.hp_boost_min_target; + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 6b54005..0747586 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -18,6 +18,8 @@ import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.Project; +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; + public class Item extends JSONElement { private static final long serialVersionUID = -516874303672548638L; @@ -33,9 +35,9 @@ public class Item extends JSONElement { public Integer base_market_cost = null; public String category_id = null; public String description = null; - public Common.HitEffect hit_effect = null; - public Common.HitReceivedEffect hit_received_effect = null; - public Common.DeathEffect kill_effect = null; + public HitEffect hit_effect = null; + public HitReceivedEffect hit_received_effect = null; + public DeathEffect kill_effect = null; public EquipEffect equip_effect = null; //Available from linked state @@ -182,66 +184,12 @@ public class Item extends JSONElement { Map hitEffect = (Map) itemJson.get("hitEffect"); if (hitEffect != null) { - this.hit_effect = new Common.HitEffect(); - if (hitEffect.get("increaseCurrentHP") != null) { - this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("min"))); - this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("max"))); - } - if (hitEffect.get("increaseCurrentAP") != null) { - this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("min"))); - this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("max"))); - } - List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); - this.hit_effect.conditions_source = Common.parseTimedConditionEffects(conditionsSourceJson); - List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); - this.hit_effect.conditions_target = Common.parseTimedConditionEffects(conditionsTargetJson); + this.hit_effect = Common.parseHitEffect(hitEffect); } Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); if (hitReceivedEffect != null) { - this.hit_received_effect = new Common.HitReceivedEffect(); - if (hitReceivedEffect.get("increaseCurrentHP") != null) { - this.hit_received_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("min"))); - this.hit_received_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentHP")).get("max"))); - } - if (hitReceivedEffect.get("increaseCurrentAP") != null) { - this.hit_received_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("min"))); - this.hit_received_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseCurrentAP")).get("max"))); - } - if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) { - this.hit_received_effect.hp_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min"))); - this.hit_received_effect.hp_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max"))); - } - if (hitReceivedEffect.get("increaseAttackerCurrentAP") != null) { - this.hit_received_effect.ap_boost_min_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min"))); - this.hit_received_effect.ap_boost_max_target = JSONElement.getInteger((Number) (((Map)hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max"))); - } - List conditionsSourceJson = (List) hitReceivedEffect.get("conditionsSource"); - if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.hit_received_effect.conditions_source = new ArrayList<>(); - for (Object conditionJsonObj : conditionsSourceJson) { - Map conditionJson = (Map)conditionJsonObj; - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_received_effect.conditions_source.add(condition); - } - } - List conditionsTargetJson = (List) hitReceivedEffect.get("conditionsTarget"); - if (conditionsTargetJson != null && !conditionsTargetJson.isEmpty()) { - this.hit_received_effect.conditions_target = new ArrayList<>(); - for (Object conditionJsonObj : conditionsTargetJson) { - Map conditionJson = (Map)conditionJsonObj; - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.hit_received_effect.conditions_target.add(condition); - } - } + this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); } Map killEffect = (Map) itemJson.get("killEffect"); @@ -249,33 +197,13 @@ public class Item extends JSONElement { killEffect = (Map) itemJson.get("useEffect"); } if (killEffect != null) { - this.kill_effect = new Common.DeathEffect(); - if (killEffect.get("increaseCurrentHP") != null) { - this.kill_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentHP")).get("min"))); - this.kill_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentHP")).get("max"))); - } - if (killEffect.get("increaseCurrentAP") != null) { - this.kill_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentAP")).get("min"))); - this.kill_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)killEffect.get("increaseCurrentAP")).get("max"))); - } - List conditionsSourceJson = (List) killEffect.get("conditionsSource"); - if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { - this.kill_effect.conditions_source = new ArrayList<>(); - for (Object conditionJsonObj : conditionsSourceJson) { - Map conditionJson = (Map)conditionJsonObj; - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); - if (conditionJson.get("chance") != null) condition.chance = JSONElement.parseChance(conditionJson.get("chance").toString()); - this.kill_effect.conditions_source.add(condition); - } - } + this.kill_effect = Common.parseDeathEffect(killEffect); } this.state = State.parsed; } - - + + + @Override public void link() { if (this.state == State.created || this.state == State.modified || this.state == State.saved) { @@ -397,104 +325,16 @@ public class Item extends JSONElement { } } if (this.hit_effect != null) { - clone.hit_effect = new Common.HitEffect(); - clone.hit_effect.ap_boost_max = this.hit_effect.ap_boost_max; - clone.hit_effect.ap_boost_min = this.hit_effect.ap_boost_min; - clone.hit_effect.hp_boost_max = this.hit_effect.hp_boost_max; - clone.hit_effect.hp_boost_min = this.hit_effect.hp_boost_min; - if (this.hit_effect.conditions_source != null) { - clone.hit_effect.conditions_source = new ArrayList<>(); - for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_effect.conditions_source.add(cclone); - } - } - if (this.hit_effect.conditions_target != null) { - clone.hit_effect.conditions_target = new ArrayList<>(); - for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_effect.conditions_target.add(cclone); - } - } + clone.hit_effect = new HitEffect(); + copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); } if (this.hit_received_effect != null) { - clone.hit_received_effect = new Common.HitReceivedEffect(); - clone.hit_received_effect.ap_boost_max = this.hit_received_effect.ap_boost_max; - clone.hit_received_effect.ap_boost_min = this.hit_received_effect.ap_boost_min; - clone.hit_received_effect.hp_boost_max = this.hit_received_effect.hp_boost_max; - clone.hit_received_effect.hp_boost_min = this.hit_received_effect.hp_boost_min; - clone.hit_received_effect.ap_boost_max_target = this.hit_received_effect.ap_boost_max_target; - clone.hit_received_effect.ap_boost_min_target = this.hit_received_effect.ap_boost_min_target; - clone.hit_received_effect.hp_boost_max_target = this.hit_received_effect.hp_boost_max_target; - clone.hit_received_effect.hp_boost_min_target = this.hit_received_effect.hp_boost_min_target; - if (this.hit_received_effect.conditions_source != null) { - clone.hit_received_effect.conditions_source = new ArrayList<>(); - for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_source) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_received_effect.conditions_source.add(cclone); - } - } - if (this.hit_received_effect.conditions_target != null) { - clone.hit_received_effect.conditions_target = new ArrayList<>(); - for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_target) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_received_effect.conditions_target.add(cclone); - } - } + clone.hit_received_effect = new HitReceivedEffect(); + copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); } if (this.kill_effect != null) { - clone.kill_effect = new Common.DeathEffect(); - clone.kill_effect.ap_boost_max = this.kill_effect.ap_boost_max; - clone.kill_effect.ap_boost_min = this.kill_effect.ap_boost_min; - clone.kill_effect.hp_boost_max = this.kill_effect.hp_boost_max; - clone.kill_effect.hp_boost_min = this.kill_effect.hp_boost_min; - if (this.kill_effect.conditions_source != null) { - clone.kill_effect.conditions_source = new ArrayList<>(); - for (Common.TimedConditionEffect c : this.kill_effect.conditions_source) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.kill_effect.conditions_source.add(cclone); - } - } + clone.kill_effect = new DeathEffect(); + copyDeathEffectValues(clone.kill_effect, this.kill_effect, clone); } return clone; } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 4529da5..da1fb19 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -18,8 +18,7 @@ import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.Project; -import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.parseHitReceivedEffect; -import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.parseTimedConditionEffects; +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; public class NPC extends JSONElement { @@ -304,104 +303,16 @@ public class NPC extends JSONElement { clone.droplist_id = this.droplist_id; clone.faction_id = this.faction_id; if (this.hit_effect != null) { - clone.hit_effect = new Common.HitEffect(); - clone.hit_effect.ap_boost_max = this.hit_effect.ap_boost_max; - clone.hit_effect.ap_boost_min = this.hit_effect.ap_boost_min; - clone.hit_effect.hp_boost_max = this.hit_effect.hp_boost_max; - clone.hit_effect.hp_boost_min = this.hit_effect.hp_boost_min; - if (this.hit_effect.conditions_source != null) { - clone.hit_effect.conditions_source = new ArrayList(); - for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_effect.conditions_source.add(cclone); - } - } - if (this.hit_effect.conditions_target != null) { - clone.hit_effect.conditions_target = new ArrayList(); - for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_effect.conditions_target.add(cclone); - } - } + clone.hit_effect = new HitEffect(); + copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); } if (this.hit_received_effect != null) { - clone.hit_received_effect = new Common.HitReceivedEffect(); - clone.hit_received_effect.ap_boost_max = this.hit_received_effect.ap_boost_max; - clone.hit_received_effect.ap_boost_min = this.hit_received_effect.ap_boost_min; - clone.hit_received_effect.hp_boost_max = this.hit_received_effect.hp_boost_max; - clone.hit_received_effect.hp_boost_min = this.hit_received_effect.hp_boost_min; - clone.hit_received_effect.ap_boost_max_target = this.hit_received_effect.ap_boost_max_target; - clone.hit_received_effect.ap_boost_min_target = this.hit_received_effect.ap_boost_min_target; - clone.hit_received_effect.hp_boost_max_target = this.hit_received_effect.hp_boost_max_target; - clone.hit_received_effect.hp_boost_min_target = this.hit_received_effect.hp_boost_min_target; - if (this.hit_received_effect.conditions_source != null) { - clone.hit_received_effect.conditions_source = new ArrayList(); - for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_source) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_received_effect.conditions_source.add(cclone); - } - } - if (this.hit_received_effect.conditions_target != null) { - clone.hit_received_effect.conditions_target = new ArrayList(); - for (Common.TimedConditionEffect c : this.hit_received_effect.conditions_target) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.hit_received_effect.conditions_target.add(cclone); - } - } + clone.hit_received_effect = new HitReceivedEffect(); + copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); } if (this.death_effect != null) { - clone.death_effect = new Common.DeathEffect(); - clone.death_effect.ap_boost_max = this.death_effect.ap_boost_max; - clone.death_effect.ap_boost_min = this.death_effect.ap_boost_min; - clone.death_effect.hp_boost_max = this.death_effect.hp_boost_max; - clone.death_effect.hp_boost_min = this.death_effect.hp_boost_min; - if (this.death_effect.conditions_source != null) { - clone.death_effect.conditions_source = new ArrayList(); - for (Common.TimedConditionEffect c : this.death_effect.conditions_source) { - Common.TimedConditionEffect cclone = new Common.TimedConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - cclone.chance = c.chance; - cclone.duration = c.duration; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.death_effect.conditions_source.add(cclone); - } - } + clone.death_effect = new DeathEffect(); + copyDeathEffectValues(clone.death_effect, this.death_effect, clone); } clone.max_ap = this.max_ap; clone.max_hp = this.max_hp; @@ -412,7 +323,7 @@ public class NPC extends JSONElement { clone.unique = this.unique; return clone; } - + @Override public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { if (dialogue == oldOne) { From 3f1f988808d638f3a8dd85d70a48f8d43c1143d2 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 3 May 2025 19:27:43 +0200 Subject: [PATCH 03/94] fix missed null check --- src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index da1fb19..c1357c0 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -183,9 +183,11 @@ public class NPC extends JSONElement { List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); } - + Map hitReceivedEffect = (Map) npcJson.get("Common.HitReceivedEffect"); - this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); + if (hitReceivedEffect != null) { + this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); + } Map deathEffect = (Map) npcJson.get("deathEffect"); if (deathEffect != null) { From 04b704daf061a75e121dce37c14ddb80eb0c7ee2 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 3 May 2025 19:49:38 +0200 Subject: [PATCH 04/94] more de-duplication --- .../model/gamedata/Common.java | 9 + .../atcontentstudio/model/gamedata/Item.java | 1363 ++++++++--------- .../atcontentstudio/model/gamedata/NPC.java | 37 +- 3 files changed, 690 insertions(+), 719 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index c7425a6..2a8b305 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -1,6 +1,7 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Project; import java.util.ArrayList; import java.util.List; @@ -8,6 +9,14 @@ import java.util.Map; public final class Common { + public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { + if (conditions != null) { + for (ConditionEffect ce : conditions) { + if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); + if (ce.condition != null) ce.condition.addBacklink(backlink); + } + } + } public static class TimedConditionEffect extends ConditionEffect { //Available from parsed state public Integer duration = null; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 0747586..3f2ccff 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -1,691 +1,672 @@ -package com.gpl.rpg.atcontentstudio.model.gamedata; - -import java.awt.Image; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; - -import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; - -public class Item extends JSONElement { - - private static final long serialVersionUID = -516874303672548638L; - - //Available from init state - //public String id = null; inherited. - public String name = null; - public DisplayType display_type = null; - public String icon_id = null; - - //Available from parsed state - public Integer has_manual_price = null; - public Integer base_market_cost = null; - public String category_id = null; - public String description = null; - public HitEffect hit_effect = null; - public HitReceivedEffect hit_received_effect = null; - public DeathEffect kill_effect = null; - public EquipEffect equip_effect = null; - - //Available from linked state - public ItemCategory category = null; - - - public static class EquipEffect { - //Available from parsed state - public Integer damage_boost_min = null; - public Integer damage_boost_max = null; - public Integer max_hp_boost = null; - public Integer max_ap_boost = null; - public List conditions = null; - public Integer increase_move_cost = null; - public Integer increase_use_item_cost = null; - public Integer increase_reequip_cost = null; - public Integer increase_attack_cost = null; - public Integer increase_attack_chance = null; - public Integer increase_critical_skill = null; - public Integer increase_block_chance = null; - public Integer increase_damage_resistance = null; - public Double critical_multiplier = null; - public Integer damage_modifier = null; - } - - - public static enum DisplayType { - ordinary, - quest, - extraordinary, - legendary, - rare - } - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+name+" ("+id+")"; - } - - public static String getStaticDesc() { - return "Items"; - } - - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List items = (List) parser.parse(reader); - for (Object obj : items) { - Map itemJson = (Map)obj; - Item item = fromJson(itemJson); - item.jsonFile = jsonFile; - item.parent = category; - if (item.getDataType() == GameSource.Type.created || item.getDataType() == GameSource.Type.altered) { - item.writable = true; - } - category.add(item); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static Item fromJson(String jsonString) throws ParseException { - Map itemJson = (Map) new JSONParser().parse(jsonString); - Item item = fromJson(itemJson); - item.parse(itemJson); - return item; - } - - @SuppressWarnings("rawtypes") - public static Item fromJson(Map itemJson) { - Item item = new Item(); - item.icon_id = (String) itemJson.get("iconID"); - item.id = (String) itemJson.get("id"); - item.name = (String) itemJson.get("name"); - if (itemJson.get("displaytype") != null) item.display_type = DisplayType.valueOf((String) itemJson.get("displaytype")); - return item; - } - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map itemJson) { - - this.has_manual_price = JSONElement.getInteger((Number) itemJson.get("hasManualPrice")); - this.base_market_cost = JSONElement.getInteger((Number) itemJson.get("baseMarketCost")); - //TODO change the debug json data.... -// this.category_id = (String) itemJson.get("category"); - if (itemJson.get("category") != null) this.category_id = (String) itemJson.get("category").toString(); - this.description = (String) itemJson.get("description"); - - Map equipEffect = (Map) itemJson.get("equipEffect"); - if (equipEffect != null) { - this.equip_effect = new EquipEffect(); - if (equipEffect.get("increaseAttackDamage") != null) { - this.equip_effect.damage_boost_min = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("min"))); - this.equip_effect.damage_boost_max = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("max"))); - } - this.equip_effect.max_hp_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxHP")); - this.equip_effect.max_ap_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxAP")); - this.equip_effect.increase_move_cost = JSONElement.getInteger((Number) equipEffect.get("increaseMoveCost")); - this.equip_effect.increase_use_item_cost = JSONElement.getInteger((Number) equipEffect.get("increaseUseItemCost")); - this.equip_effect.increase_reequip_cost = JSONElement.getInteger((Number) equipEffect.get("increaseReequipCost")); - this.equip_effect.increase_attack_cost = JSONElement.getInteger((Number) equipEffect.get("increaseAttackCost")); - this.equip_effect.increase_attack_chance = JSONElement.getInteger((Number) equipEffect.get("increaseAttackChance")); - this.equip_effect.increase_critical_skill = JSONElement.getInteger((Number) equipEffect.get("increaseCriticalSkill")); - this.equip_effect.increase_block_chance = JSONElement.getInteger((Number) equipEffect.get("increaseBlockChance")); - this.equip_effect.increase_damage_resistance = JSONElement.getInteger((Number) equipEffect.get("increaseDamageResistance")); - //TODO correct game data, to unify format. -// this.equip_effect.critical_multiplier = JSONElement.getDouble((Number) equipEffect.get("setCriticalMultiplier")); - if (equipEffect.get("setCriticalMultiplier") != null) this.equip_effect.critical_multiplier = JSONElement.getDouble(Double.parseDouble(equipEffect.get("setCriticalMultiplier").toString())); - this.equip_effect.damage_modifier = JSONElement.getInteger((Number) equipEffect.get("setNonWeaponDamageModifier")); - - List conditionsJson = (List) equipEffect.get("addedConditions"); - if (conditionsJson != null && !conditionsJson.isEmpty()) { - this.equip_effect.conditions = new ArrayList<>(); - for (Object conditionJsonObj : conditionsJson) { - Map conditionJson = (Map)conditionJsonObj; - Common.ConditionEffect condition = new Common.ConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - this.equip_effect.conditions.add(condition); - } - } - } - - - Map hitEffect = (Map) itemJson.get("hitEffect"); - if (hitEffect != null) { - this.hit_effect = Common.parseHitEffect(hitEffect); - } - - Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); - if (hitReceivedEffect != null) { - this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); - } - - Map killEffect = (Map) itemJson.get("killEffect"); - if (killEffect == null) { - killEffect = (Map) itemJson.get("useEffect"); - } - if (killEffect != null) { - this.kill_effect = Common.parseDeathEffect(killEffect); - } - this.state = State.parsed; - } - - - - @Override - public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } - Project proj = getProject(); - if (proj == null) { - Notification.addError("Error linking item "+id+". No parent project found."); - return; - } - - if (this.icon_id != null) { - String spritesheetId = this.icon_id.split(":")[0]; - proj.getSpritesheet(spritesheetId).addBacklink(this); - } - if (this.category_id != null) this.category = proj.getItemCategory(this.category_id); - if (this.category != null) this.category.addBacklink(this); - if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (Common.ConditionEffect ce : this.equip_effect.conditions) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (Common.TimedConditionEffect ce : this.hit_effect.conditions_source) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (Common.TimedConditionEffect ce : this.hit_effect.conditions_target) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - if (this.hit_received_effect != null && this.hit_received_effect.conditions_source != null) { - for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_source) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - if (this.hit_received_effect != null && this.hit_received_effect.conditions_target != null) { - for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_target) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (Common.TimedConditionEffect ce : this.kill_effect.conditions_source) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - this.state = State.linked; - } - - @Override - public Image getIcon() { - return getProject().getIcon(icon_id); - } - - public Image getImage() { - return getProject().getImage(icon_id); - } - - @Override - public GameDataElement clone() { - Item clone = new Item(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.name = this.name; - clone.icon_id = this.icon_id; - clone.base_market_cost = this.base_market_cost; - clone.category = this.category; - if (clone.category != null) { - clone.category.addBacklink(clone); - } - clone.category_id = this.category_id; - clone.description = this.description; - clone.display_type = this.display_type; - clone.has_manual_price = this.has_manual_price; - if (this.equip_effect != null) { - clone.equip_effect = new EquipEffect(); - clone.equip_effect.damage_modifier = this.equip_effect.damage_modifier; - clone.equip_effect.critical_multiplier = this.equip_effect.critical_multiplier; - clone.equip_effect.damage_boost_max = this.equip_effect.damage_boost_max; - clone.equip_effect.damage_boost_min = this.equip_effect.damage_boost_min; - clone.equip_effect.increase_attack_chance = this.equip_effect.increase_attack_chance; - clone.equip_effect.increase_attack_cost = this.equip_effect.increase_attack_cost; - clone.equip_effect.increase_block_chance = this.equip_effect.increase_block_chance; - clone.equip_effect.increase_critical_skill = this.equip_effect.increase_critical_skill; - clone.equip_effect.increase_damage_resistance = this.equip_effect.increase_damage_resistance; - clone.equip_effect.increase_move_cost = this.equip_effect.increase_move_cost; - clone.equip_effect.increase_reequip_cost = this.equip_effect.increase_reequip_cost; - clone.equip_effect.increase_use_item_cost = this.equip_effect.increase_use_item_cost; - clone.equip_effect.max_ap_boost = this.equip_effect.max_ap_boost; - clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; - if (this.equip_effect.conditions != null) { - clone.equip_effect.conditions = new ArrayList<>(); - for (Common.ConditionEffect c : this.equip_effect.conditions) { - Common.ConditionEffect cclone = new Common.ConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.equip_effect.conditions.add(cclone); - } - } - } - if (this.hit_effect != null) { - clone.hit_effect = new HitEffect(); - copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); - } - if (this.hit_received_effect != null) { - clone.hit_received_effect = new HitReceivedEffect(); - copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); - } - if (this.kill_effect != null) { - clone.kill_effect = new DeathEffect(); - copyDeathEffectValues(clone.kill_effect, this.kill_effect, clone); - } - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (this.category == oldOne) { - oldOne.removeBacklink(this); - this.category = (ItemCategory) newOne; - if (newOne != null) newOne.addBacklink(this); - } else { - if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (Common.ConditionEffect c : this.equip_effect.conditions) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - - if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (Common.TimedConditionEffect c : this.kill_effect.conditions_source) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map itemJson = new LinkedHashMap(); - itemJson.put("id", this.id); - if (this.icon_id != null) itemJson.put("iconID", this.icon_id); - if (this.name != null) itemJson.put("name", this.name); - if(this.display_type != null) itemJson.put("displaytype", this.display_type.toString()); - - if (this.has_manual_price != null) itemJson.put("hasManualPrice", this.has_manual_price); - if (this.base_market_cost != null) itemJson.put("baseMarketCost", this.base_market_cost); - if (this.category != null) { - itemJson.put("category", this.category.id); - } else if (this.category_id != null) { - itemJson.put("category", this.category_id); - } - if (this.description != null) itemJson.put("description", this.description); - if (this.equip_effect != null) { - Map equipEffectJson = new LinkedHashMap(); - itemJson.put("equipEffect", equipEffectJson); - if (this.equip_effect.damage_boost_min != null || this.equip_effect.damage_boost_max != null) { - Map damageJson = new LinkedHashMap(); - equipEffectJson.put("increaseAttackDamage", damageJson); - if (this.equip_effect.damage_boost_min != null) damageJson.put("min", this.equip_effect.damage_boost_min); - else damageJson.put("min", 0); - if (this.equip_effect.damage_boost_max != null) damageJson.put("max", this.equip_effect.damage_boost_max); - else damageJson.put("max", 0); - } - if (this.equip_effect.max_hp_boost != null) equipEffectJson.put("increaseMaxHP", this.equip_effect.max_hp_boost); - if (this.equip_effect.max_ap_boost != null) equipEffectJson.put("increaseMaxAP", this.equip_effect.max_ap_boost); - if (this.equip_effect.increase_move_cost != null) equipEffectJson.put("increaseMoveCost", this.equip_effect.increase_move_cost); - if (this.equip_effect.increase_use_item_cost != null) equipEffectJson.put("increaseUseItemCost", this.equip_effect.increase_use_item_cost); - if (this.equip_effect.increase_reequip_cost != null) equipEffectJson.put("increaseReequipCost", this.equip_effect.increase_reequip_cost); - if (this.equip_effect.increase_attack_cost != null) equipEffectJson.put("increaseAttackCost", this.equip_effect.increase_attack_cost); - if (this.equip_effect.increase_attack_chance != null) equipEffectJson.put("increaseAttackChance", this.equip_effect.increase_attack_chance); - if (this.equip_effect.increase_critical_skill != null) equipEffectJson.put("increaseCriticalSkill", this.equip_effect.increase_critical_skill); - if (this.equip_effect.increase_block_chance != null) equipEffectJson.put("increaseBlockChance", this.equip_effect.increase_block_chance); - if (this.equip_effect.increase_damage_resistance != null) equipEffectJson.put("increaseDamageResistance", this.equip_effect.increase_damage_resistance); - if (this.equip_effect.critical_multiplier != null) equipEffectJson.put("setCriticalMultiplier", this.equip_effect.critical_multiplier); - if (this.equip_effect.damage_modifier != null) equipEffectJson.put("setNonWeaponDamageModifier", this.equip_effect.damage_modifier); - if (this.equip_effect.conditions != null) { - List conditionsJson = new ArrayList(); - equipEffectJson.put("addedConditions", conditionsJson); - for (Common.ConditionEffect condition : this.equip_effect.conditions) { - Map conditionJson = new LinkedHashMap(); - conditionsJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - } - } - } - if (this.hit_effect != null) { - Map hitEffectJson = new LinkedHashMap(); - itemJson.put("hitEffect", hitEffectJson); - if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.hit_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (Common.TimedConditionEffect condition : this.hit_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.hit_received_effect != null) { - Map hitReceivedEffectJson = new LinkedHashMap(); - itemJson.put("hitReceivedEffect", hitReceivedEffectJson); - if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min != null) hpJson.put("min", this.hit_received_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max != null) hpJson.put("max", this.hit_received_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min != null) apJson.put("min", this.hit_received_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max != null) apJson.put("max", this.hit_received_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min_target != null) hpJson.put("min", this.hit_received_effect.hp_boost_min_target); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max_target != null) hpJson.put("max", this.hit_received_effect.hp_boost_max_target); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min_target != null) apJson.put("min", this.hit_received_effect.ap_boost_min_target); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max_target != null) apJson.put("max", this.hit_received_effect.ap_boost_max_target); - else apJson.put("max", 0); - } - if (this.hit_received_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_received_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.kill_effect != null) { - Map killEffectJson = new LinkedHashMap(); - if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { - itemJson.put("killEffect", killEffectJson); - } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { - itemJson.put("useEffect", killEffectJson); - } - if (this.kill_effect.hp_boost_min != null || this.kill_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - killEffectJson.put("increaseCurrentHP", hpJson); - if (this.kill_effect.hp_boost_min != null) hpJson.put("min", this.kill_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.kill_effect.hp_boost_max != null) hpJson.put("max", this.kill_effect.hp_boost_max); - else hpJson.put("min", 0); - } - if (this.kill_effect.ap_boost_min != null || this.kill_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - killEffectJson.put("increaseCurrentAP", apJson); - if (this.kill_effect.ap_boost_min != null) apJson.put("min", this.kill_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.kill_effect.ap_boost_max != null) apJson.put("max", this.kill_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.kill_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - killEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.kill_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - return itemJson; - } - - @Override - public String getProjectFilename() { - return "itemlist_"+getProject().name+".json"; - } - - public Integer computePrice() { - int price = 0; - if (category != null && category.action_type != null) { - if (category.action_type == ItemCategory.ActionType.use) { - price += kill_effect == null ? 0 : calculateUseCost(); - } else if (category.action_type == ItemCategory.ActionType.equip) { - price += equip_effect == null ? 0 : calculateEquipCost(isWeapon());; - price += hit_effect == null ? 0 : calculateHitCost(); - price += kill_effect == null ? 0 : calculateKillCost(); - } - } - return Math.max(1, price); - } - - public int zeroForNull(Integer val) { - return val == null ? 0 : val; - } - - public double zeroForNull(Double val) { - return val == null ? 0 : val; - } - - public boolean isWeapon() { - return category != null && category.action_type != null && category.action_type == ItemCategory.ActionType.equip && category.slot != null && category.slot == ItemCategory.InventorySlot.weapon; - } - - public int calculateUseCost() { - final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; - if (averageHPBoost == 0) return 0; - return (int) (0.1*Math.signum(averageHPBoost)*Math.pow(Math.abs(averageHPBoost), 2) + 3*averageHPBoost); - } - - public int calculateEquipCost(boolean isWeapon) { - final int costBC = (int) (3*Math.pow(Math.max(0, zeroForNull(equip_effect.increase_block_chance)), 2.5) + 28*zeroForNull(equip_effect.increase_block_chance)); - final int costAC = (int) (0.4*Math.pow(Math.max(0,zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6*Math.pow(Math.abs(Math.min(0,zeroForNull(equip_effect.increase_attack_chance))),2.7)); - final int costAP = isWeapon ? - (int) (0.2*Math.pow(10.0f/zeroForNull(equip_effect.increase_attack_cost), 8) - 25*zeroForNull(equip_effect.increase_attack_cost)) - :-3125 * zeroForNull(equip_effect.increase_attack_cost); - final int costDR = 1325 * zeroForNull(equip_effect.increase_damage_resistance); - final int costDMG_Min = isWeapon ? - (int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 2.5)) - :(int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 3) + zeroForNull(equip_effect.damage_boost_min)*80); - final int costDMG_Max = isWeapon ? - (int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 2.1)) - :(int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 3) + zeroForNull(equip_effect.damage_boost_max)*20); - final int costCS = (int) (2.2*Math.pow(zeroForNull(equip_effect.increase_critical_skill), 3)); - final int costCM = (int) (50*Math.pow(Math.max(0, zeroForNull(equip_effect.critical_multiplier)), 2)); - - final int costMaxHP = (int) (30*Math.pow(Math.max(0,zeroForNull(equip_effect.max_hp_boost)), 1.2) + 70*zeroForNull(equip_effect.max_hp_boost)); - final int costMaxAP = (int) (50*Math.pow(Math.max(0,zeroForNull(equip_effect.max_ap_boost)), 3) + 750*zeroForNull(equip_effect.max_ap_boost)); - final int costMovement = (int) (510*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_move_cost)), 2.5) - 350*zeroForNull(equip_effect.increase_move_cost)); - final int costUseItem = (int)(915*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_use_item_cost)), 3) - 430*zeroForNull(equip_effect.increase_use_item_cost)); - final int costReequip = (int)(450*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_reequip_cost)), 2) - 250*zeroForNull(equip_effect.increase_reequip_cost)); - - return costBC + costAC + costAP + costDR + costDMG_Min + costDMG_Max + costCS + costCM - + costMaxHP + costMaxAP - + costMovement + costUseItem + costReequip; - } - - - public int calculateHitCost() { - final float averageHPBoost = (zeroForNull(hit_effect.hp_boost_min) + zeroForNull(hit_effect.hp_boost_max)) / 2.0f; - final float averageAPBoost = (zeroForNull(hit_effect.ap_boost_min) + zeroForNull(hit_effect.ap_boost_max)) / 2.0f; - if (averageHPBoost == 0 && averageAPBoost == 0) return 0; - - final int costBoostHP = (int)(2770*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); - final int costBoostAP = (int)(3100*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); - return costBoostHP + costBoostAP; - } - - public int calculateKillCost() { - final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; - final float averageAPBoost = (zeroForNull(kill_effect.ap_boost_min) + zeroForNull(kill_effect.ap_boost_max)) / 2.0f; - if (averageHPBoost == 0 && averageAPBoost == 0) return 0; - - final int costBoostHP = (int)(923*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); - final int costBoostAP = (int)(1033*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); - return costBoostHP + costBoostAP; - } -} +package com.gpl.rpg.atcontentstudio.model.gamedata; + +import java.awt.Image; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; + +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; + +public class Item extends JSONElement { + + private static final long serialVersionUID = -516874303672548638L; + + //Available from init state + //public String id = null; inherited. + public String name = null; + public DisplayType display_type = null; + public String icon_id = null; + + //Available from parsed state + public Integer has_manual_price = null; + public Integer base_market_cost = null; + public String category_id = null; + public String description = null; + public HitEffect hit_effect = null; + public HitReceivedEffect hit_received_effect = null; + public DeathEffect kill_effect = null; + public EquipEffect equip_effect = null; + + //Available from linked state + public ItemCategory category = null; + + + public static class EquipEffect { + //Available from parsed state + public Integer damage_boost_min = null; + public Integer damage_boost_max = null; + public Integer max_hp_boost = null; + public Integer max_ap_boost = null; + public List conditions = null; + public Integer increase_move_cost = null; + public Integer increase_use_item_cost = null; + public Integer increase_reequip_cost = null; + public Integer increase_attack_cost = null; + public Integer increase_attack_chance = null; + public Integer increase_critical_skill = null; + public Integer increase_block_chance = null; + public Integer increase_damage_resistance = null; + public Double critical_multiplier = null; + public Integer damage_modifier = null; + } + + + public static enum DisplayType { + ordinary, + quest, + extraordinary, + legendary, + rare + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "")+name+" ("+id+")"; + } + + public static String getStaticDesc() { + return "Items"; + } + + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List items = (List) parser.parse(reader); + for (Object obj : items) { + Map itemJson = (Map)obj; + Item item = fromJson(itemJson); + item.jsonFile = jsonFile; + item.parent = category; + if (item.getDataType() == GameSource.Type.created || item.getDataType() == GameSource.Type.altered) { + item.writable = true; + } + category.add(item); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static Item fromJson(String jsonString) throws ParseException { + Map itemJson = (Map) new JSONParser().parse(jsonString); + Item item = fromJson(itemJson); + item.parse(itemJson); + return item; + } + + @SuppressWarnings("rawtypes") + public static Item fromJson(Map itemJson) { + Item item = new Item(); + item.icon_id = (String) itemJson.get("iconID"); + item.id = (String) itemJson.get("id"); + item.name = (String) itemJson.get("name"); + if (itemJson.get("displaytype") != null) item.display_type = DisplayType.valueOf((String) itemJson.get("displaytype")); + return item; + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map itemJson) { + + this.has_manual_price = JSONElement.getInteger((Number) itemJson.get("hasManualPrice")); + this.base_market_cost = JSONElement.getInteger((Number) itemJson.get("baseMarketCost")); + //TODO change the debug json data.... +// this.category_id = (String) itemJson.get("category"); + if (itemJson.get("category") != null) this.category_id = (String) itemJson.get("category").toString(); + this.description = (String) itemJson.get("description"); + + Map equipEffect = (Map) itemJson.get("equipEffect"); + if (equipEffect != null) { + this.equip_effect = new EquipEffect(); + if (equipEffect.get("increaseAttackDamage") != null) { + this.equip_effect.damage_boost_min = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("min"))); + this.equip_effect.damage_boost_max = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("max"))); + } + this.equip_effect.max_hp_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxHP")); + this.equip_effect.max_ap_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxAP")); + this.equip_effect.increase_move_cost = JSONElement.getInteger((Number) equipEffect.get("increaseMoveCost")); + this.equip_effect.increase_use_item_cost = JSONElement.getInteger((Number) equipEffect.get("increaseUseItemCost")); + this.equip_effect.increase_reequip_cost = JSONElement.getInteger((Number) equipEffect.get("increaseReequipCost")); + this.equip_effect.increase_attack_cost = JSONElement.getInteger((Number) equipEffect.get("increaseAttackCost")); + this.equip_effect.increase_attack_chance = JSONElement.getInteger((Number) equipEffect.get("increaseAttackChance")); + this.equip_effect.increase_critical_skill = JSONElement.getInteger((Number) equipEffect.get("increaseCriticalSkill")); + this.equip_effect.increase_block_chance = JSONElement.getInteger((Number) equipEffect.get("increaseBlockChance")); + this.equip_effect.increase_damage_resistance = JSONElement.getInteger((Number) equipEffect.get("increaseDamageResistance")); + //TODO correct game data, to unify format. +// this.equip_effect.critical_multiplier = JSONElement.getDouble((Number) equipEffect.get("setCriticalMultiplier")); + if (equipEffect.get("setCriticalMultiplier") != null) this.equip_effect.critical_multiplier = JSONElement.getDouble(Double.parseDouble(equipEffect.get("setCriticalMultiplier").toString())); + this.equip_effect.damage_modifier = JSONElement.getInteger((Number) equipEffect.get("setNonWeaponDamageModifier")); + + List conditionsJson = (List) equipEffect.get("addedConditions"); + if (conditionsJson != null && !conditionsJson.isEmpty()) { + this.equip_effect.conditions = new ArrayList<>(); + for (Object conditionJsonObj : conditionsJson) { + Map conditionJson = (Map)conditionJsonObj; + Common.ConditionEffect condition = new Common.ConditionEffect(); + condition.condition_id = (String) conditionJson.get("condition"); + condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); + this.equip_effect.conditions.add(condition); + } + } + } + + + Map hitEffect = (Map) itemJson.get("hitEffect"); + if (hitEffect != null) { + this.hit_effect = Common.parseHitEffect(hitEffect); + } + + Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); + if (hitReceivedEffect != null) { + this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); + } + + Map killEffect = (Map) itemJson.get("killEffect"); + if (killEffect == null) { + killEffect = (Map) itemJson.get("useEffect"); + } + if (killEffect != null) { + this.kill_effect = Common.parseDeathEffect(killEffect); + } + this.state = State.parsed; + } + + + + @Override + public void link() { + if (this.state == State.created || this.state == State.modified || this.state == State.saved) { + //This type of state is unrelated to parsing/linking. + return; + } + if (this.state == State.init) { + //Not parsed yet. + this.parse(); + } else if (this.state == State.linked) { + //Already linked. + return; + } + Project proj = getProject(); + if (proj == null) { + Notification.addError("Error linking item "+id+". No parent project found."); + return; + } + + if (this.icon_id != null) { + String spritesheetId = this.icon_id.split(":")[0]; + proj.getSpritesheet(spritesheetId).addBacklink(this); + } + if (this.category_id != null) this.category = proj.getItemCategory(this.category_id); + if (this.category != null) this.category.addBacklink(this); + if (this.equip_effect != null && this.equip_effect.conditions != null) { + linkConditions(this.equip_effect.conditions, proj, this); + } + + if (this.hit_effect != null) { + linkConditions(this.hit_effect.conditions_source, proj, this); + linkConditions(this.hit_effect.conditions_target, proj, this); + } + + if (this.hit_received_effect != null) { + linkConditions(this.hit_received_effect.conditions_source, proj, this); + linkConditions(this.hit_received_effect.conditions_target, proj, this); + } + + if (this.kill_effect != null) { + linkConditions(this.kill_effect.conditions_source, proj, this); + } + this.state = State.linked; + } + + @Override + public Image getIcon() { + return getProject().getIcon(icon_id); + } + + public Image getImage() { + return getProject().getImage(icon_id); + } + + @Override + public GameDataElement clone() { + Item clone = new Item(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.name = this.name; + clone.icon_id = this.icon_id; + clone.base_market_cost = this.base_market_cost; + clone.category = this.category; + if (clone.category != null) { + clone.category.addBacklink(clone); + } + clone.category_id = this.category_id; + clone.description = this.description; + clone.display_type = this.display_type; + clone.has_manual_price = this.has_manual_price; + if (this.equip_effect != null) { + clone.equip_effect = new EquipEffect(); + clone.equip_effect.damage_modifier = this.equip_effect.damage_modifier; + clone.equip_effect.critical_multiplier = this.equip_effect.critical_multiplier; + clone.equip_effect.damage_boost_max = this.equip_effect.damage_boost_max; + clone.equip_effect.damage_boost_min = this.equip_effect.damage_boost_min; + clone.equip_effect.increase_attack_chance = this.equip_effect.increase_attack_chance; + clone.equip_effect.increase_attack_cost = this.equip_effect.increase_attack_cost; + clone.equip_effect.increase_block_chance = this.equip_effect.increase_block_chance; + clone.equip_effect.increase_critical_skill = this.equip_effect.increase_critical_skill; + clone.equip_effect.increase_damage_resistance = this.equip_effect.increase_damage_resistance; + clone.equip_effect.increase_move_cost = this.equip_effect.increase_move_cost; + clone.equip_effect.increase_reequip_cost = this.equip_effect.increase_reequip_cost; + clone.equip_effect.increase_use_item_cost = this.equip_effect.increase_use_item_cost; + clone.equip_effect.max_ap_boost = this.equip_effect.max_ap_boost; + clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; + if (this.equip_effect.conditions != null) { + clone.equip_effect.conditions = new ArrayList<>(); + for (Common.ConditionEffect c : this.equip_effect.conditions) { + Common.ConditionEffect cclone = new Common.ConditionEffect(); + cclone.magnitude = c.magnitude; + cclone.condition_id = c.condition_id; + cclone.condition = c.condition; + if (cclone.condition != null) { + cclone.condition.addBacklink(clone); + } + clone.equip_effect.conditions.add(cclone); + } + } + } + if (this.hit_effect != null) { + clone.hit_effect = new HitEffect(); + copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); + } + if (this.hit_received_effect != null) { + clone.hit_received_effect = new HitReceivedEffect(); + copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); + } + if (this.kill_effect != null) { + clone.kill_effect = new DeathEffect(); + copyDeathEffectValues(clone.kill_effect, this.kill_effect, clone); + } + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (this.category == oldOne) { + oldOne.removeBacklink(this); + this.category = (ItemCategory) newOne; + if (newOne != null) newOne.addBacklink(this); + } else { + if (this.equip_effect != null && this.equip_effect.conditions != null) { + for (Common.ConditionEffect c : this.equip_effect.conditions) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + if (this.hit_effect != null && this.hit_effect.conditions_source != null) { + for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + if (this.hit_effect != null && this.hit_effect.conditions_target != null) { + for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + + if (this.kill_effect != null && this.kill_effect.conditions_source != null) { + for (Common.TimedConditionEffect c : this.kill_effect.conditions_source) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public Map toJson() { + Map itemJson = new LinkedHashMap(); + itemJson.put("id", this.id); + if (this.icon_id != null) itemJson.put("iconID", this.icon_id); + if (this.name != null) itemJson.put("name", this.name); + if(this.display_type != null) itemJson.put("displaytype", this.display_type.toString()); + + if (this.has_manual_price != null) itemJson.put("hasManualPrice", this.has_manual_price); + if (this.base_market_cost != null) itemJson.put("baseMarketCost", this.base_market_cost); + if (this.category != null) { + itemJson.put("category", this.category.id); + } else if (this.category_id != null) { + itemJson.put("category", this.category_id); + } + if (this.description != null) itemJson.put("description", this.description); + if (this.equip_effect != null) { + Map equipEffectJson = new LinkedHashMap(); + itemJson.put("equipEffect", equipEffectJson); + if (this.equip_effect.damage_boost_min != null || this.equip_effect.damage_boost_max != null) { + Map damageJson = new LinkedHashMap(); + equipEffectJson.put("increaseAttackDamage", damageJson); + if (this.equip_effect.damage_boost_min != null) damageJson.put("min", this.equip_effect.damage_boost_min); + else damageJson.put("min", 0); + if (this.equip_effect.damage_boost_max != null) damageJson.put("max", this.equip_effect.damage_boost_max); + else damageJson.put("max", 0); + } + if (this.equip_effect.max_hp_boost != null) equipEffectJson.put("increaseMaxHP", this.equip_effect.max_hp_boost); + if (this.equip_effect.max_ap_boost != null) equipEffectJson.put("increaseMaxAP", this.equip_effect.max_ap_boost); + if (this.equip_effect.increase_move_cost != null) equipEffectJson.put("increaseMoveCost", this.equip_effect.increase_move_cost); + if (this.equip_effect.increase_use_item_cost != null) equipEffectJson.put("increaseUseItemCost", this.equip_effect.increase_use_item_cost); + if (this.equip_effect.increase_reequip_cost != null) equipEffectJson.put("increaseReequipCost", this.equip_effect.increase_reequip_cost); + if (this.equip_effect.increase_attack_cost != null) equipEffectJson.put("increaseAttackCost", this.equip_effect.increase_attack_cost); + if (this.equip_effect.increase_attack_chance != null) equipEffectJson.put("increaseAttackChance", this.equip_effect.increase_attack_chance); + if (this.equip_effect.increase_critical_skill != null) equipEffectJson.put("increaseCriticalSkill", this.equip_effect.increase_critical_skill); + if (this.equip_effect.increase_block_chance != null) equipEffectJson.put("increaseBlockChance", this.equip_effect.increase_block_chance); + if (this.equip_effect.increase_damage_resistance != null) equipEffectJson.put("increaseDamageResistance", this.equip_effect.increase_damage_resistance); + if (this.equip_effect.critical_multiplier != null) equipEffectJson.put("setCriticalMultiplier", this.equip_effect.critical_multiplier); + if (this.equip_effect.damage_modifier != null) equipEffectJson.put("setNonWeaponDamageModifier", this.equip_effect.damage_modifier); + if (this.equip_effect.conditions != null) { + List conditionsJson = new ArrayList(); + equipEffectJson.put("addedConditions", conditionsJson); + for (Common.ConditionEffect condition : this.equip_effect.conditions) { + Map conditionJson = new LinkedHashMap(); + conditionsJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + } + } + } + if (this.hit_effect != null) { + Map hitEffectJson = new LinkedHashMap(); + itemJson.put("hitEffect", hitEffectJson); + if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitEffectJson.put("conditionsSource", conditionsSourceJson); + for (Common.TimedConditionEffect condition : this.hit_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitEffectJson.put("conditionsTarget", conditionsTargetJson); + for (Common.TimedConditionEffect condition : this.hit_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.hit_received_effect != null) { + Map hitReceivedEffectJson = new LinkedHashMap(); + itemJson.put("hitReceivedEffect", hitReceivedEffectJson); + if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min != null) hpJson.put("min", this.hit_received_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max != null) hpJson.put("max", this.hit_received_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min != null) apJson.put("min", this.hit_received_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max != null) apJson.put("max", this.hit_received_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min_target != null) hpJson.put("min", this.hit_received_effect.hp_boost_min_target); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max_target != null) hpJson.put("max", this.hit_received_effect.hp_boost_max_target); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min_target != null) apJson.put("min", this.hit_received_effect.ap_boost_min_target); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max_target != null) apJson.put("max", this.hit_received_effect.ap_boost_max_target); + else apJson.put("max", 0); + } + if (this.hit_received_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); + for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_received_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); + for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.kill_effect != null) { + Map killEffectJson = new LinkedHashMap(); + if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { + itemJson.put("killEffect", killEffectJson); + } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { + itemJson.put("useEffect", killEffectJson); + } + if (this.kill_effect.hp_boost_min != null || this.kill_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + killEffectJson.put("increaseCurrentHP", hpJson); + if (this.kill_effect.hp_boost_min != null) hpJson.put("min", this.kill_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.kill_effect.hp_boost_max != null) hpJson.put("max", this.kill_effect.hp_boost_max); + else hpJson.put("min", 0); + } + if (this.kill_effect.ap_boost_min != null || this.kill_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + killEffectJson.put("increaseCurrentAP", apJson); + if (this.kill_effect.ap_boost_min != null) apJson.put("min", this.kill_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.kill_effect.ap_boost_max != null) apJson.put("max", this.kill_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.kill_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + killEffectJson.put("conditionsSource", conditionsSourceJson); + for (Common.TimedConditionEffect condition : this.kill_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + return itemJson; + } + + @Override + public String getProjectFilename() { + return "itemlist_"+getProject().name+".json"; + } + + public Integer computePrice() { + int price = 0; + if (category != null && category.action_type != null) { + if (category.action_type == ItemCategory.ActionType.use) { + price += kill_effect == null ? 0 : calculateUseCost(); + } else if (category.action_type == ItemCategory.ActionType.equip) { + price += equip_effect == null ? 0 : calculateEquipCost(isWeapon());; + price += hit_effect == null ? 0 : calculateHitCost(); + price += kill_effect == null ? 0 : calculateKillCost(); + } + } + return Math.max(1, price); + } + + public int zeroForNull(Integer val) { + return val == null ? 0 : val; + } + + public double zeroForNull(Double val) { + return val == null ? 0 : val; + } + + public boolean isWeapon() { + return category != null && category.action_type != null && category.action_type == ItemCategory.ActionType.equip && category.slot != null && category.slot == ItemCategory.InventorySlot.weapon; + } + + public int calculateUseCost() { + final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; + if (averageHPBoost == 0) return 0; + return (int) (0.1*Math.signum(averageHPBoost)*Math.pow(Math.abs(averageHPBoost), 2) + 3*averageHPBoost); + } + + public int calculateEquipCost(boolean isWeapon) { + final int costBC = (int) (3*Math.pow(Math.max(0, zeroForNull(equip_effect.increase_block_chance)), 2.5) + 28*zeroForNull(equip_effect.increase_block_chance)); + final int costAC = (int) (0.4*Math.pow(Math.max(0,zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6*Math.pow(Math.abs(Math.min(0,zeroForNull(equip_effect.increase_attack_chance))),2.7)); + final int costAP = isWeapon ? + (int) (0.2*Math.pow(10.0f/zeroForNull(equip_effect.increase_attack_cost), 8) - 25*zeroForNull(equip_effect.increase_attack_cost)) + :-3125 * zeroForNull(equip_effect.increase_attack_cost); + final int costDR = 1325 * zeroForNull(equip_effect.increase_damage_resistance); + final int costDMG_Min = isWeapon ? + (int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 2.5)) + :(int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 3) + zeroForNull(equip_effect.damage_boost_min)*80); + final int costDMG_Max = isWeapon ? + (int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 2.1)) + :(int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 3) + zeroForNull(equip_effect.damage_boost_max)*20); + final int costCS = (int) (2.2*Math.pow(zeroForNull(equip_effect.increase_critical_skill), 3)); + final int costCM = (int) (50*Math.pow(Math.max(0, zeroForNull(equip_effect.critical_multiplier)), 2)); + + final int costMaxHP = (int) (30*Math.pow(Math.max(0,zeroForNull(equip_effect.max_hp_boost)), 1.2) + 70*zeroForNull(equip_effect.max_hp_boost)); + final int costMaxAP = (int) (50*Math.pow(Math.max(0,zeroForNull(equip_effect.max_ap_boost)), 3) + 750*zeroForNull(equip_effect.max_ap_boost)); + final int costMovement = (int) (510*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_move_cost)), 2.5) - 350*zeroForNull(equip_effect.increase_move_cost)); + final int costUseItem = (int)(915*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_use_item_cost)), 3) - 430*zeroForNull(equip_effect.increase_use_item_cost)); + final int costReequip = (int)(450*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_reequip_cost)), 2) - 250*zeroForNull(equip_effect.increase_reequip_cost)); + + return costBC + costAC + costAP + costDR + costDMG_Min + costDMG_Max + costCS + costCM + + costMaxHP + costMaxAP + + costMovement + costUseItem + costReequip; + } + + + public int calculateHitCost() { + final float averageHPBoost = (zeroForNull(hit_effect.hp_boost_min) + zeroForNull(hit_effect.hp_boost_max)) / 2.0f; + final float averageAPBoost = (zeroForNull(hit_effect.ap_boost_min) + zeroForNull(hit_effect.ap_boost_max)) / 2.0f; + if (averageHPBoost == 0 && averageAPBoost == 0) return 0; + + final int costBoostHP = (int)(2770*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); + final int costBoostAP = (int)(3100*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); + return costBoostHP + costBoostAP; + } + + public int calculateKillCost() { + final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; + final float averageAPBoost = (zeroForNull(kill_effect.ap_boost_min) + zeroForNull(kill_effect.ap_boost_max)) / 2.0f; + if (averageHPBoost == 0 && averageAPBoost == 0) return 0; + + final int costBoostHP = (int)(923*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); + final int costBoostAP = (int)(1033*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); + return costBoostHP + costBoostAP; + } +} diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index c1357c0..131f578 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -235,39 +235,20 @@ public class NPC extends JSONElement { if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id); if (this.droplist != null) this.droplist.addBacklink(this); - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (Common.TimedConditionEffect ce : this.hit_effect.conditions_source) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } + if (this.hit_effect != null) { + linkConditions(this.hit_effect.conditions_source, proj, this); + linkConditions(this.hit_effect.conditions_target, proj, this); } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (Common.TimedConditionEffect ce : this.hit_effect.conditions_target) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } + if (this.hit_received_effect != null) { + linkConditions(this.hit_received_effect.conditions_source, proj, this); + linkConditions(this.hit_received_effect.conditions_target, proj, this); } - if (this.hit_received_effect != null && this.hit_received_effect.conditions_source != null) { - for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_source) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - if (this.hit_received_effect != null && this.hit_received_effect.conditions_target != null) { - for (Common.TimedConditionEffect ce : this.hit_received_effect.conditions_target) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } - } - if (this.death_effect != null && this.death_effect.conditions_source != null) { - for (Common.TimedConditionEffect ce : this.death_effect.conditions_source) { - if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); - if (ce.condition != null) ce.condition.addBacklink(this); - } + if (this.death_effect != null) { + linkConditions(this.death_effect.conditions_source, proj, this); } this.state = State.linked; } - + @Override public Image getIcon() { return getProject().getIcon(icon_id); From 286d95d83d744def6235dc400d60f0c1ff071889 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 3 May 2025 20:14:35 +0200 Subject: [PATCH 05/94] improve imports --- .../atcontentstudio/model/gamedata/Item.java | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 3f2ccff..6cad8c4 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -50,7 +50,7 @@ public class Item extends JSONElement { public Integer damage_boost_max = null; public Integer max_hp_boost = null; public Integer max_ap_boost = null; - public List conditions = null; + public List conditions = null; public Integer increase_move_cost = null; public Integer increase_use_item_cost = null; public Integer increase_reequip_cost = null; @@ -173,7 +173,7 @@ public class Item extends JSONElement { this.equip_effect.conditions = new ArrayList<>(); for (Object conditionJsonObj : conditionsJson) { Map conditionJson = (Map)conditionJsonObj; - Common.ConditionEffect condition = new Common.ConditionEffect(); + ConditionEffect condition = new ConditionEffect(); condition.condition_id = (String) conditionJson.get("condition"); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); this.equip_effect.conditions.add(condition); @@ -184,12 +184,12 @@ public class Item extends JSONElement { Map hitEffect = (Map) itemJson.get("hitEffect"); if (hitEffect != null) { - this.hit_effect = Common.parseHitEffect(hitEffect); + this.hit_effect = parseHitEffect(hitEffect); } Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); if (hitReceivedEffect != null) { - this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); + this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); } Map killEffect = (Map) itemJson.get("killEffect"); @@ -197,7 +197,7 @@ public class Item extends JSONElement { killEffect = (Map) itemJson.get("useEffect"); } if (killEffect != null) { - this.kill_effect = Common.parseDeathEffect(killEffect); + this.kill_effect = parseDeathEffect(killEffect); } this.state = State.parsed; } @@ -293,8 +293,8 @@ public class Item extends JSONElement { clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; if (this.equip_effect.conditions != null) { clone.equip_effect.conditions = new ArrayList<>(); - for (Common.ConditionEffect c : this.equip_effect.conditions) { - Common.ConditionEffect cclone = new Common.ConditionEffect(); + for (ConditionEffect c : this.equip_effect.conditions) { + ConditionEffect cclone = new ConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -328,7 +328,7 @@ public class Item extends JSONElement { if (newOne != null) newOne.addBacklink(this); } else { if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (Common.ConditionEffect c : this.equip_effect.conditions) { + for (ConditionEffect c : this.equip_effect.conditions) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -337,7 +337,7 @@ public class Item extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (Common.TimedConditionEffect c : this.hit_effect.conditions_source) { + for (TimedConditionEffect c : this.hit_effect.conditions_source) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -346,7 +346,7 @@ public class Item extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (Common.TimedConditionEffect c : this.hit_effect.conditions_target) { + for (TimedConditionEffect c : this.hit_effect.conditions_target) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -356,7 +356,7 @@ public class Item extends JSONElement { } if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (Common.TimedConditionEffect c : this.kill_effect.conditions_source) { + for (TimedConditionEffect c : this.kill_effect.conditions_source) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -410,7 +410,7 @@ public class Item extends JSONElement { if (this.equip_effect.conditions != null) { List conditionsJson = new ArrayList(); equipEffectJson.put("addedConditions", conditionsJson); - for (Common.ConditionEffect condition : this.equip_effect.conditions) { + for (ConditionEffect condition : this.equip_effect.conditions) { Map conditionJson = new LinkedHashMap(); conditionsJson.add(conditionJson); if (condition.condition != null) { @@ -444,7 +444,7 @@ public class Item extends JSONElement { if (this.hit_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.hit_effect.conditions_source) { + for (TimedConditionEffect condition : this.hit_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -460,7 +460,7 @@ public class Item extends JSONElement { if (this.hit_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (Common.TimedConditionEffect condition : this.hit_effect.conditions_target) { + for (TimedConditionEffect condition : this.hit_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -512,7 +512,7 @@ public class Item extends JSONElement { if (this.hit_received_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -528,7 +528,7 @@ public class Item extends JSONElement { if (this.hit_received_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -568,7 +568,7 @@ public class Item extends JSONElement { if (this.kill_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); killEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.kill_effect.conditions_source) { + for (TimedConditionEffect condition : this.kill_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { From 70055be6d28bff679e2cb1fe31b51645ec045caf Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 3 May 2025 20:16:57 +0200 Subject: [PATCH 06/94] improve usings --- .../atcontentstudio/model/gamedata/NPC.java | 28 +++++++++---------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 131f578..0a939d0 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -48,9 +48,9 @@ public class NPC extends JSONElement { public Double critical_multiplier = null; public Integer block_chance = null; public Integer damage_resistance = null; - public Common.HitEffect hit_effect = null; - public Common.HitReceivedEffect hit_received_effect = null; - public Common.DeathEffect death_effect = null; + public HitEffect hit_effect = null; + public HitReceivedEffect hit_received_effect = null; + public DeathEffect death_effect = null; //Available from linked state public Dialogue dialogue = null; @@ -169,7 +169,7 @@ public class NPC extends JSONElement { Map hitEffect = (Map) npcJson.get("hitEffect"); if (hitEffect != null) { - this.hit_effect = new Common.HitEffect(); + this.hit_effect = new HitEffect(); if (hitEffect.get("increaseCurrentHP") != null) { this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("max"))); this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("min"))); @@ -184,14 +184,14 @@ public class NPC extends JSONElement { this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); } - Map hitReceivedEffect = (Map) npcJson.get("Common.HitReceivedEffect"); + Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); if (hitReceivedEffect != null) { - this.hit_received_effect = Common.parseHitReceivedEffect(hitReceivedEffect); + this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); } Map deathEffect = (Map) npcJson.get("deathEffect"); if (deathEffect != null) { - this.death_effect = new Common.HitEffect(); + this.death_effect = new HitEffect(); if (deathEffect.get("increaseCurrentHP") != null) { this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("max"))); this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("min"))); @@ -320,7 +320,7 @@ public class NPC extends JSONElement { if (newOne != null) newOne.addBacklink(this); } else { if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (Common.TimedConditionEffect tce : this.hit_effect.conditions_source) { + for (TimedConditionEffect tce : this.hit_effect.conditions_source) { if (tce.condition == oldOne) { oldOne.removeBacklink(this); tce.condition = (ActorCondition) newOne; @@ -329,7 +329,7 @@ public class NPC extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (Common.TimedConditionEffect tce : this.hit_effect.conditions_target) { + for (TimedConditionEffect tce : this.hit_effect.conditions_target) { if (tce.condition == oldOne) { oldOne.removeBacklink(this); tce.condition = (ActorCondition) newOne; @@ -402,7 +402,7 @@ public class NPC extends JSONElement { if (this.hit_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.hit_effect.conditions_source) { + for (TimedConditionEffect condition : this.hit_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -418,7 +418,7 @@ public class NPC extends JSONElement { if (this.hit_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (Common.TimedConditionEffect condition : this.hit_effect.conditions_target) { + for (TimedConditionEffect condition : this.hit_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -470,7 +470,7 @@ public class NPC extends JSONElement { if (this.hit_received_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -486,7 +486,7 @@ public class NPC extends JSONElement { if (this.hit_received_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (Common.TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -522,7 +522,7 @@ public class NPC extends JSONElement { if (this.death_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); deathEffectJson.put("conditionsSource", conditionsSourceJson); - for (Common.TimedConditionEffect condition : this.death_effect.conditions_source) { + for (TimedConditionEffect condition : this.death_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { From 185f168b198727dca233064ecd641928d07aa42d Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 18:52:12 +0200 Subject: [PATCH 07/94] misc --- .idea/misc.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index 901eaf0..4944549 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file From 8561415574a516a11b673b58845a47d7356708fe Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 19:01:35 +0200 Subject: [PATCH 08/94] dedup link check --- .../atcontentstudio/model/GameDataElement.java | 16 ++++++++++++++++ .../model/gamedata/ActorCondition.java | 15 +++------------ .../atcontentstudio/model/gamedata/Dialogue.java | 12 +----------- .../atcontentstudio/model/gamedata/Droplist.java | 12 +----------- .../rpg/atcontentstudio/model/gamedata/Item.java | 12 +----------- .../model/gamedata/ItemCategory.java | 12 +----------- .../rpg/atcontentstudio/model/gamedata/NPC.java | 12 +----------- .../atcontentstudio/model/gamedata/Quest.java | 12 +----------- .../model/gamedata/QuestStage.java | 12 +----------- .../model/gamedata/Requirement.java | 12 +----------- 10 files changed, 27 insertions(+), 100 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java index 5643f57..f65a961 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java @@ -39,6 +39,22 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable { private Map backlinks = new ConcurrentHashMap(); public String id = null; + + protected boolean needsToBeLinked(){ + if (this.state == State.created || this.state == State.modified || this.state == State.saved) { + //This type of state is unrelated to parsing/linking. + return false; + } + if (this.state == State.init) { + //Not parsed yet. + this.parse(); + } else if (this.state == State.linked) { + //Already linked. + return false; + } + return true; + + } @Override public Enumeration children() { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java index b171a3c..e2aa928 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java @@ -224,17 +224,7 @@ public class ActorCondition extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; if (this.icon_id != null) { String spritesheetId = this.icon_id.split(":")[0]; if (getProject().getSpritesheet(spritesheetId) == null) { @@ -250,7 +240,8 @@ public class ActorCondition extends JSONElement { this.state = State.linked; } - + + public static String getStaticDesc() { return "Actor Conditions"; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java index d316955..2493858 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java @@ -206,17 +206,7 @@ public class Dialogue extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking dialogue "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java index b83dea5..8f62df8 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java @@ -129,17 +129,7 @@ public class Droplist extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking droplist "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 6cad8c4..94ac347 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -206,17 +206,7 @@ public class Item extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java index 1c6622d..8a2110c 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java @@ -171,17 +171,7 @@ public class ItemCategory extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 0a939d0..2a7458a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -208,17 +208,7 @@ public class NPC extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java index cbb993c..c7455f8 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java @@ -113,17 +113,7 @@ public class Quest extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; for (QuestStage stage : stages) { stage.link(); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java index 61baa85..072c376 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java @@ -59,17 +59,7 @@ public class QuestStage extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java index 66e8af2..25e4974 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java @@ -153,17 +153,7 @@ public class Requirement extends JSONElement { @Override public void link() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return; - } + if (!this.needsToBeLinked()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking requirement "+getDesc()+". No parent project found."); From 8c42b498b04021056589afbcdc149b1369fb84e2 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 19:16:59 +0200 Subject: [PATCH 09/94] rename needsToBeLinked to linkCheck and continue dedupe --- .../atcontentstudio/model/GameDataElement.java | 15 +++++++++++---- .../model/gamedata/ActorCondition.java | 2 +- .../atcontentstudio/model/gamedata/Dialogue.java | 2 +- .../atcontentstudio/model/gamedata/Droplist.java | 2 +- .../rpg/atcontentstudio/model/gamedata/Item.java | 2 +- .../model/gamedata/ItemCategory.java | 2 +- .../rpg/atcontentstudio/model/gamedata/NPC.java | 2 +- .../rpg/atcontentstudio/model/gamedata/Quest.java | 2 +- .../model/gamedata/QuestStage.java | 2 +- .../model/gamedata/Requirement.java | 2 +- .../model/tools/writermode/WriterModeData.java | 7 ++----- 11 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java index f65a961..bd5a4a6 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java @@ -40,12 +40,12 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable { public String id = null; - protected boolean needsToBeLinked(){ - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { + protected boolean linkCheck(){ + if (checkNotRelatedToParseOrLink()) { //This type of state is unrelated to parsing/linking. return false; } - if (this.state == State.init) { + else if (this.state == State.init) { //Not parsed yet. this.parse(); } else if (this.state == State.linked) { @@ -55,7 +55,14 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable { return true; } - + + protected boolean checkNotRelatedToParseOrLink() { + if (this.state == State.created || this.state == State.modified || this.state == State.saved) { + //This type of state is unrelated to parsing/linking. + return true; + } + return false; + } @Override public Enumeration children() { return null; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java index e2aa928..55fac35 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java @@ -224,7 +224,7 @@ public class ActorCondition extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; if (this.icon_id != null) { String spritesheetId = this.icon_id.split(":")[0]; if (getProject().getSpritesheet(spritesheetId) == null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java index 2493858..75c9a62 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java @@ -206,7 +206,7 @@ public class Dialogue extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking dialogue "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java index 8f62df8..0ae34a0 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java @@ -129,7 +129,7 @@ public class Droplist extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking droplist "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 94ac347..5917a4e 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -206,7 +206,7 @@ public class Item extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java index 8a2110c..ecb0f8d 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java @@ -171,7 +171,7 @@ public class ItemCategory extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 2a7458a..78d2b1d 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -208,7 +208,7 @@ public class NPC extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item "+id+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java index c7455f8..1439344 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java @@ -113,7 +113,7 @@ public class Quest extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; for (QuestStage stage : stages) { stage.link(); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java index 072c376..8076707 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java @@ -59,7 +59,7 @@ public class QuestStage extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java index 25e4974..ac93ac1 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java @@ -153,7 +153,7 @@ public class Requirement extends JSONElement { @Override public void link() { - if (!this.needsToBeLinked()) return; + if (!this.linkCheck()) return; Project proj = getProject(); if (proj == null) { Notification.addError("Error linking requirement "+getDesc()+". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java index 489e6c8..432c648 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java @@ -489,10 +489,7 @@ public class WriterModeData extends GameDataElement { @SuppressWarnings("rawtypes") public void parse() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } + if (checkNotRelatedToParseOrLink()) return; JSONParser parser = new JSONParser(); FileReader reader = null; try { @@ -526,7 +523,7 @@ public class WriterModeData extends GameDataElement { } } - + @SuppressWarnings("rawtypes") public void parse(Map json) { this.id = (String) json.get("id"); From 9ed9393b16c6911af2a836d0b76ef87b427af737 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 19:23:33 +0200 Subject: [PATCH 10/94] extract wordWrap to TextUtils helper-class --- .../dialoguetree/DialogueGraphView.java | 1166 ++++++++--------- .../ui/tools/writermode/WriterModeEditor.java | 20 +- .../rpg/atcontentstudio/utils/TextUtils.java | 20 + 3 files changed, 598 insertions(+), 608 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java index d091d8b..61b1da2 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java @@ -1,590 +1,576 @@ -package com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree; - -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Image; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JToolTip; -import javax.swing.SwingConstants; -import javax.swing.ToolTipManager; - -import prefuse.Display; -import prefuse.Visualization; -import prefuse.action.ActionList; -import prefuse.action.RepaintAction; -import prefuse.action.assignment.ColorAction; -import prefuse.action.assignment.FontAction; -import prefuse.action.assignment.StrokeAction; -import prefuse.action.layout.Layout; -import prefuse.action.layout.graph.NodeLinkTreeLayout; -import prefuse.activity.Activity; -import prefuse.controls.ControlAdapter; -import prefuse.controls.PanControl; -import prefuse.controls.WheelZoomControl; -import prefuse.controls.ZoomControl; -import prefuse.data.Edge; -import prefuse.data.Graph; -import prefuse.data.Node; -import prefuse.data.Schema; -import prefuse.render.DefaultRendererFactory; -import prefuse.render.EdgeRenderer; -import prefuse.render.LabelRenderer; -import prefuse.util.ColorLib; -import prefuse.util.GraphicsLib; -import prefuse.util.PrefuseLib; -import prefuse.visual.DecoratorItem; -import prefuse.visual.EdgeItem; -import prefuse.visual.VisualItem; -import prefuse.visual.expression.InGroupPredicate; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DialogueEditor; -import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; -import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration.WeblateTranslationUnit; -import com.jidesoft.swing.JideBoxLayout; - -public class DialogueGraphView extends Display { - - private static final long serialVersionUID = -6431503090775579301L; - - public static final String GRAPH = "graph"; - public static final String NODES = "graph.nodes"; - public static final String EDGES = "graph.edges"; - public static final String EDGES_LABELS = "edgesLabels"; - - public static final String LABEL = "label"; - public static final String ICON = "icon"; - public static final String TARGET = "target"; - public static final String REPLY = "reply"; - public static final String HIDDEN_REPLY = "hidden_reply"; - public static final String HAS_REQS = "has_reqs"; - - private static final String TRANSLATION_LOADING="Loading translation..."; - private String translationHeader="\n---[ Translation from weblate ]---\n"; - - - private static final Schema DECORATOR_SCHEMA = PrefuseLib.getVisualItemSchema(); - - private Dialogue dialogue; - private Image npcIcon; - private Graph graph; - private Boolean translatorMode; - - private Map cells = new HashMap(); - - public DialogueGraphView(Dialogue dialogue, NPC npc) { - super(new Visualization()); - this.dialogue = dialogue; - if (npc != null) { - npcIcon = npc.getIcon(); - } else { - npcIcon = DefaultIcons.getNPCIcon(); - } - translatorMode = Workspace.activeWorkspace.settings.useInternet.getCurrentValue() && Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null; - if (translatorMode) { - translationHeader = "\n---[ Translation in "+Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue()+" ]---\n"; - } - loadGraph(); - - // add visual data groups - m_vis.addGraph(GRAPH, graph); - m_vis.setInteractive(EDGES, null, false); - - LabelRenderer nodeR = new MyLabelRenderer(LABEL); - nodeR.setHorizontalTextAlignment(prefuse.Constants.LEFT); - - EdgeRenderer edgeR = new EdgeRenderer(prefuse.Constants.EDGE_TYPE_LINE, prefuse.Constants.EDGE_ARROW_FORWARD); -// edgeR.setEdgeType(prefuse.Constants.EDGE_TYPE_CURVE); - - LabelRenderer edgeLabelR = new LabelRenderer(LABEL); - edgeLabelR.setRenderType(LabelRenderer.RENDER_TYPE_DRAW); - - DefaultRendererFactory drf = new DefaultRendererFactory(); - drf.setDefaultRenderer(nodeR); - drf.setDefaultEdgeRenderer(edgeR); - drf.add(new InGroupPredicate(EDGES_LABELS), edgeLabelR); - m_vis.setRendererFactory(drf); - DECORATOR_SCHEMA.setDefault(VisualItem.FILLCOLOR, ColorLib.gray(255)); - DECORATOR_SCHEMA.setDefault(VisualItem.STROKECOLOR, ColorLib.rgba(0, 0, 0, 0)); - DECORATOR_SCHEMA.setDefault(VisualItem.TEXTCOLOR, ColorLib.gray(0)); - m_vis.addDecorators(EDGES_LABELS, EDGES, DECORATOR_SCHEMA); - - // set up the visual operators - // first set up all the color actions - ColorAction nStrokeColor = new ColorAction(NODES, VisualItem.STROKECOLOR); - nStrokeColor.setDefaultColor(ColorLib.gray(100)); - nStrokeColor.add("_hover", ColorLib.rgb(255,100,100)); - StrokeAction nStroke = new EdgesStrokeAction(NODES); - - ColorAction nFill = new NPCPhraseColorAction(NODES, VisualItem.FILLCOLOR); - - ColorAction eEdges = new ConnectedEdgeColorAction(EDGES, VisualItem.STROKECOLOR); - ColorAction eArrows = new ConnectedEdgeColorAction(EDGES, VisualItem.FILLCOLOR); - ColorAction eEdgesLabels = new ConnectedEdgeColorAction(EDGES_LABELS, VisualItem.TEXTCOLOR); - - StrokeAction eStroke = new EdgesStrokeAction(EDGES); - - FontAction aFont = new FontAction(); - ColorAction aFontColor = new ColorAction(NODES, VisualItem.TEXTCOLOR); - aFontColor.setDefaultColor(ColorLib.rgb(0, 0, 0)); - - // bundle the color actions - ActionList colors = new ActionList(Activity.INFINITY); - colors.add(nStrokeColor); - colors.add(nFill); - colors.add(nStroke); - colors.add(eEdges); - colors.add(eArrows); - colors.add(eEdgesLabels); - colors.add(eStroke); - colors.add(aFont); - colors.add(aFontColor); - colors.add(new RepaintAction()); - m_vis.putAction("colors", colors); - - // now create the main layout routine - ActionList layout = new ActionList();//Activity.INFINITY); - NodeLinkTreeLayout treeLayout = new NodeLinkTreeLayout(GRAPH, prefuse.Constants.ORIENT_LEFT_RIGHT, 120, translatorMode ? 80 : 40, translatorMode ? 80 : 40); - treeLayout.setLayoutAnchor(new Point2D.Double(25,300)); - layout.add(treeLayout); - layout.add(new EdgesLabelDecoratorLayout(EDGES_LABELS)); - layout.add(new RepaintAction()); - m_vis.putAction("layout", layout); - - // set up the display - setSize(500,500); - pan(250, 250); - setHighQuality(true); - addControlListener(new TooltipControl()); - addControlListener(new DoubleClickControl()); - addControlListener(new WheelZoomControl()); - addControlListener(new ZoomControl()); - addControlListener(new PanControl()); - - // set things running - m_vis.run("colors"); - m_vis.run("layout"); - } - - public void loadGraph() { - graph = new Graph(true); - graph.addColumn(LABEL, String.class, ""); - graph.addColumn(ICON, Image.class, DefaultIcons.getNullifyIcon()); - graph.addColumn(TARGET, GameDataElement.class, null); - graph.addColumn(REPLY, Dialogue.Reply.class, null); - graph.addColumn(HIDDEN_REPLY, Dialogue.Reply.class, null); - graph.addColumn(HAS_REQS, boolean.class, false); - addDialogue(dialogue, npcIcon); - } - - public Node addDialogue(Dialogue dialogue, Image npcIcon) { - if (cells.get(dialogue) == null) { - if (dialogue.switch_to_npc != null) { - npcIcon = dialogue.switch_to_npc.getIcon(); - } - final Node dNode = graph.addNode(); - cells.put(dialogue, dNode); - String label; - Thread t = null; - if (dialogue.message == null) { - label = "[Selector]"; - } else if (translatorMode) { - label = dialogue.message+translationHeader+TRANSLATION_LOADING; - final String message = dialogue.message; - t = new Thread("Get weblate translation for "+message) { - public void run() { - WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); - dNode.setString(LABEL, message+translationHeader+unit.translatedText); - }; - }; - } else { - label = dialogue.message; - } - dNode.setString(LABEL, label); - if (t != null) t.start(); - dNode.set(ICON, npcIcon); - dNode.set(TARGET, dialogue); - if (dialogue.replies != null) { - Node rNode; - int i = 1; - for (Dialogue.Reply r : dialogue.replies) { - rNode = addReply(dialogue, r, npcIcon); - Edge e = graph.addEdge(dNode, rNode); - e.setString(LABEL, "#"+i++); - e.setBoolean(HAS_REQS, r.requirements != null && !r.requirements.isEmpty()); - } - } - } - return cells.get(dialogue); - } - - public Node addReply(Dialogue d, Dialogue.Reply r, Image npcIcon) { - final Node rNode; - if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) { - //Normal reply... - rNode = graph.addNode(); -// rNode.setString(LABEL, translatorMode ? r.text + "\n---\n" + WeblateIntegration.getTranslationUnit(r.text).translatedText : r.text); - String label; - Thread t = null; - if (translatorMode) { - label = r.text+translationHeader+TRANSLATION_LOADING; - final String message = r.text; - t = new Thread("Get weblate translation for "+message) { - public void run() { - WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); - rNode.setString(LABEL, message+translationHeader+unit.translatedText); - }; - }; - } else { - label = r.text; - } - rNode.setString(LABEL, label); - if (t != null) t.start(); - rNode.set(ICON, DefaultIcons.getHeroIcon()); - rNode.set(TARGET, d); - rNode.set(REPLY, r); - if (r.next_phrase != null) { - //...that leads to another phrase - Node dNode = addDialogue(r.next_phrase, npcIcon); - graph.addEdge(rNode, dNode); - } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { - //...that leads to a key phrase - Node kNode = addKeyPhraseNode(d, r.next_phrase_id); - kNode.set(REPLY, r); - graph.addEdge(rNode, kNode); - } - } else if (r.next_phrase != null) { - //Go directly to next phrase - rNode = addDialogue(r.next_phrase, npcIcon); - //Add a pointer to the hidden reply, in order to fetch requirements later. - rNode.set(HIDDEN_REPLY, r); - } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { - //Go directly to key phrase - rNode = addKeyPhraseNode(d, r.next_phrase_id); - rNode.set(REPLY, r); - } else { - //Incomplete. - rNode = graph.addNode(); - rNode.setString(LABEL, "[Incomplete reply]"); - rNode.set(ICON, DefaultIcons.getNullifyIcon()); - } - return rNode; - } - - public Node addKeyPhraseNode(Dialogue d, String key) { - Node kNode = graph.addNode(); - if (key.equals(Dialogue.Reply.EXIT_PHRASE_ID)) { - kNode.setString(LABEL, "[Ends dialogue]"); - kNode.set(ICON, DefaultIcons.getNullifyIcon()); - } else if (key.equals(Dialogue.Reply.FIGHT_PHRASE_ID)) { - kNode.setString(LABEL, "[Starts fight]"); - kNode.set(ICON, DefaultIcons.getCombatIcon()); - } else if (key.equals(Dialogue.Reply.REMOVE_PHRASE_ID)) { - kNode.setString(LABEL, "[NPC vanishes]"); - kNode.set(ICON, DefaultIcons.getNPCCloseIcon()); - } else if (key.equals(Dialogue.Reply.SHOP_PHRASE_ID)) { - kNode.setString(LABEL, "[Start trading]"); - kNode.set(ICON, DefaultIcons.getGoldIcon()); - } else { - //Should never reach, unless new key phrase ID are added to the model, but not here... - kNode.setString(LABEL, "[WTF !!]"+key); - } - kNode.set(TARGET, d); - return kNode; - } - - class MyLabelRenderer extends LabelRenderer { - public MyLabelRenderer(String label) { - super(label); - } - - @Override - protected Image getImage(VisualItem item) { - return (Image) item.get(ICON); - } - - @Override - protected String getText(VisualItem item) { - return wordWrap(super.getText(item), 40); - } - - public String wordWrap(String in, int length) { - final String newline = "\n"; - //:: Trim - while(in.length() > 0 && (in.charAt(0) == '\t' || in.charAt(0) == ' ')) in = in.substring(1); - //:: If Small Enough Already, Return Original - if(in.length() < length) return in; - //:: If Next length Contains Newline, Split There - if(in.substring(0, length).contains(newline)) return in.substring(0, in.indexOf(newline)).trim() + newline + wordWrap(in.substring(in.indexOf("\n") + 1), length); - //:: Otherwise, Split Along Nearest Previous Space/Tab/Dash - int spaceIndex = Math.max(Math.max( in.lastIndexOf(" ", length), in.lastIndexOf("\t", length)), in.lastIndexOf("-", length)); - //:: If No Nearest Space, Split At length - if(spaceIndex == -1) spaceIndex = length; - //:: Split - return in.substring(0, spaceIndex).trim() + newline + wordWrap(in.substring(spaceIndex), length); - } - } - - class ConnectedEdgeColorAction extends ColorAction { - - final int outgoing = ColorLib.rgb(255, 100, 100); - final int incoming = ColorLib.rgb(100, 255, 100); - final int none = ColorLib.gray(100); - - public ConnectedEdgeColorAction(String group, String field) { - super(group, field); - } - - @Override - public int getColor(VisualItem item) { - if (item instanceof DecoratorItem) { - item = ((DecoratorItem) item).getDecoratedItem(); - } - if (item instanceof EdgeItem) { - if (((EdgeItem) item).getSourceItem().isHover()) { - return outgoing; - } else if (((EdgeItem) item).getTargetItem().isHover()) { - return incoming; - } - } - - return none; - } - } - - class NPCPhraseColorAction extends ColorAction { - - final int none = ColorLib.gray(255); - final int hover = ColorLib.gray(200); - final int has_rewards = ColorLib.rgb(255, 255, 0); - final int has_rewards_hover = ColorLib.rgb(200, 200, 0); - - - public NPCPhraseColorAction(String group, String field) { - super(group, field); - } - - @Override - public int getColor(VisualItem item) { - // Change color for Dialogues, not replies. - if (item.get(TARGET) != null && item.get(REPLY) == null) { - Dialogue d = (Dialogue) item.get(TARGET); - if (d.rewards != null && !d.rewards.isEmpty()) { - if (item.isHover()) { - return has_rewards_hover; - } else { - return has_rewards; - } - } - } - if (item.isHover()) { - return hover; - } else { - return none; - } - } - } - - class EdgesStrokeAction extends StrokeAction { - - public final BasicStroke req_stroke = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); - public final BasicStroke hover_stroke = new BasicStroke(3.0f); - public final BasicStroke hover_req_stroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); - - public EdgesStrokeAction(String group) { - super(group); - } - - @Override - public BasicStroke getStroke(VisualItem item) { - if (item.getBoolean(HAS_REQS)) { - if (item instanceof EdgeItem) { - if (((EdgeItem) item).getSourceItem().isHover()) { - return hover_req_stroke; - } else if (((EdgeItem) item).getTargetItem().isHover()) { - return hover_req_stroke; - } - } - return req_stroke; - } else { - if (item.isHover()) { - return hover_stroke; - } else if (item instanceof EdgeItem) { - if (((EdgeItem) item).getSourceItem().isHover()) { - return hover_stroke; - } else if (((EdgeItem) item).getTargetItem().isHover()) { - return hover_stroke; - } - } - } - return super.getStroke(item); - } - - } - - class EdgesLabelDecoratorLayout extends Layout { - public EdgesLabelDecoratorLayout(String group) { - super(group); - } - public void run(double frac) { - Iterator iter = m_vis.items(m_group); - while ( iter.hasNext() ) { - DecoratorItem decorator = (DecoratorItem)iter.next(); - if( decorator.getDecoratedItem() instanceof EdgeItem) { - EdgeItem edgeItem = (EdgeItem) decorator.getDecoratedItem(); - double deltaX = edgeItem.getTargetItem().getX() - edgeItem.getSourceItem().getX(); - double deltaY = edgeItem.getTargetItem().getY() - edgeItem.getSourceItem().getY(); - double hypo = Math.hypot(deltaX, deltaY); - - double edgePropX = deltaX / hypo; - double edgePropY = deltaY / hypo; - - Point2D start = new Point2D.Double(edgeItem.getSourceItem().getBounds().getCenterX(), edgeItem.getSourceItem().getBounds().getCenterY()); - Point2D end = new Point2D.Double(edgeItem.getTargetItem().getBounds().getCenterX(), edgeItem.getTargetItem().getBounds().getCenterY()); - Point2D[] realStart = new Point2D[]{new Point2D.Double(), new Point2D.Double()}; -// Point2D[] realEnd = new Point2D[]{new Point2D.Double(), new Point2D.Double()}; - - int i = GraphicsLib.intersectLineRectangle(start, end, edgeItem.getSourceItem().getBounds(), realStart); - if (i > 0) { - start = realStart[0]; - } -// i = GraphicsLib.intersectLineRectangle(start, end, edgeItem.getTargetItem().getBounds(), realEnd); -// if (i > 0) { -// end = realEnd[0]; -// } - - double coef = 20 * Math.atan(hypo / 100.0) + 20; - - setX(decorator, null, start.getX() + coef * edgePropX + 6 * Math.random() - 3); - setY(decorator, null, start.getY() + coef * edgePropY + 6 * Math.random() - 3); - } else { - VisualItem decoratedItem = decorator.getDecoratedItem(); - Rectangle2D bounds = decoratedItem.getBounds(); - double x = bounds.getCenterX(); - double y = bounds.getCenterY(); - setX(decorator, null, x + 10 * Math.random() - 5); - setY(decorator, null, y + 10 * Math.random() - 5); - } - } - } - } - - class DoubleClickControl extends ControlAdapter { - @Override - public void itemClicked(VisualItem item, MouseEvent e) { - if (e.getClickCount() == 2) { - if (item.get(TARGET) != null) { - ATContentStudio.frame.openEditor((GameDataElement)item.get(TARGET)); - } - } - } - } - - class TooltipControl extends ControlAdapter { - - @Override - public void itemEntered(VisualItem item, MouseEvent e) { - if (item.get(TARGET) != null) { - tooltippedItem = item; - if (!tooltipActivated) { - setToolTipText(""); - ToolTipManager.sharedInstance().registerComponent(DialogueGraphView.this); - ToolTipManager.sharedInstance().setEnabled(true); - tooltipActivated = true; - } - } - } - @Override - public void itemExited(VisualItem item, MouseEvent e) { - //Hides the tooltip... - ToolTipManager.sharedInstance().setEnabled(false); - ToolTipManager.sharedInstance().unregisterComponent(DialogueGraphView.this); - tooltipActivated = false; - } - } - - JToolTip tt = null; - private VisualItem tooltippedItem = null; - private VisualItem lastTTItem = null; - private boolean tooltipActivated = false; - - @Override - public Point getToolTipLocation(MouseEvent event) { - return new Point(event.getX() + 5, event.getY() + 5); - } - - @Override - public JToolTip createToolTip() { - if (tt == null) tt = super.createToolTip(); - if (tooltippedItem == lastTTItem) { - return tt; - } - tt = super.createToolTip(); - lastTTItem = tooltippedItem; - tt.setLayout(new BorderLayout()); - JPanel content = new JPanel(); - content.setLayout(new JideBoxLayout(content, JideBoxLayout.PAGE_AXIS)); - JLabel label; - if (tooltippedItem != null) { - Object target = tooltippedItem.get(TARGET); - if (target != null) { - if (target instanceof Dialogue) { - Dialogue d = (Dialogue) target; - label = new JLabel(new ImageIcon(DefaultIcons.getDialogueIcon())); - label.setText(d.id); - content.add(label, JideBoxLayout.FIX); - Object replObj = tooltippedItem.get(REPLY); - if (replObj == null) { - replObj = tooltippedItem.get(HIDDEN_REPLY); - } - if (replObj != null && replObj instanceof Dialogue.Reply) { - Dialogue.Reply r = (Dialogue.Reply) replObj; - if (r.requirements != null && !r.requirements.isEmpty()) { - JLabel reqTitle = new JLabel("--Requirements--", SwingConstants.CENTER); - content.add(reqTitle, JideBoxLayout.FIX); - for (Requirement req : r.requirements) { - label = new JLabel("", SwingConstants.CENTER); - DialogueEditor.decorateRequirementJLabel(label, req); - content.add(label, JideBoxLayout.FIX); - } - } - } - if (d.rewards != null && !d.rewards.isEmpty()) { - JLabel rewTitle = new JLabel("--Rewards--", SwingConstants.CENTER); - rewTitle.setAlignmentY(CENTER_ALIGNMENT); - content.add(rewTitle, JideBoxLayout.FIX); - for (Dialogue.Reward r : d.rewards) { - label = new JLabel("", SwingConstants.CENTER); - DialogueEditor.decorateRewardJLabel(label, r); - content.add(label, JideBoxLayout.FIX); - } - } - } - } - - } - - tt.add(content, BorderLayout.CENTER); - tt.setPreferredSize(tt.getLayout().preferredLayoutSize(tt)); - return tt; - } - -} - - +package com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree; + +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Image; +import java.awt.Point; +import java.awt.event.MouseEvent; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JToolTip; +import javax.swing.SwingConstants; +import javax.swing.ToolTipManager; + +import com.gpl.rpg.atcontentstudio.utils.TextUtils; +import prefuse.Display; +import prefuse.Visualization; +import prefuse.action.ActionList; +import prefuse.action.RepaintAction; +import prefuse.action.assignment.ColorAction; +import prefuse.action.assignment.FontAction; +import prefuse.action.assignment.StrokeAction; +import prefuse.action.layout.Layout; +import prefuse.action.layout.graph.NodeLinkTreeLayout; +import prefuse.activity.Activity; +import prefuse.controls.ControlAdapter; +import prefuse.controls.PanControl; +import prefuse.controls.WheelZoomControl; +import prefuse.controls.ZoomControl; +import prefuse.data.Edge; +import prefuse.data.Graph; +import prefuse.data.Node; +import prefuse.data.Schema; +import prefuse.render.DefaultRendererFactory; +import prefuse.render.EdgeRenderer; +import prefuse.render.LabelRenderer; +import prefuse.util.ColorLib; +import prefuse.util.GraphicsLib; +import prefuse.util.PrefuseLib; +import prefuse.visual.DecoratorItem; +import prefuse.visual.EdgeItem; +import prefuse.visual.VisualItem; +import prefuse.visual.expression.InGroupPredicate; + +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Workspace; +import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; +import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; +import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DialogueEditor; +import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; +import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration.WeblateTranslationUnit; +import com.jidesoft.swing.JideBoxLayout; + +public class DialogueGraphView extends Display { + + private static final long serialVersionUID = -6431503090775579301L; + + public static final String GRAPH = "graph"; + public static final String NODES = "graph.nodes"; + public static final String EDGES = "graph.edges"; + public static final String EDGES_LABELS = "edgesLabels"; + + public static final String LABEL = "label"; + public static final String ICON = "icon"; + public static final String TARGET = "target"; + public static final String REPLY = "reply"; + public static final String HIDDEN_REPLY = "hidden_reply"; + public static final String HAS_REQS = "has_reqs"; + + private static final String TRANSLATION_LOADING="Loading translation..."; + private String translationHeader="\n---[ Translation from weblate ]---\n"; + + + private static final Schema DECORATOR_SCHEMA = PrefuseLib.getVisualItemSchema(); + + private Dialogue dialogue; + private Image npcIcon; + private Graph graph; + private Boolean translatorMode; + + private Map cells = new HashMap(); + + public DialogueGraphView(Dialogue dialogue, NPC npc) { + super(new Visualization()); + this.dialogue = dialogue; + if (npc != null) { + npcIcon = npc.getIcon(); + } else { + npcIcon = DefaultIcons.getNPCIcon(); + } + translatorMode = Workspace.activeWorkspace.settings.useInternet.getCurrentValue() && Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null; + if (translatorMode) { + translationHeader = "\n---[ Translation in "+Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue()+" ]---\n"; + } + loadGraph(); + + // add visual data groups + m_vis.addGraph(GRAPH, graph); + m_vis.setInteractive(EDGES, null, false); + + LabelRenderer nodeR = new MyLabelRenderer(LABEL); + nodeR.setHorizontalTextAlignment(prefuse.Constants.LEFT); + + EdgeRenderer edgeR = new EdgeRenderer(prefuse.Constants.EDGE_TYPE_LINE, prefuse.Constants.EDGE_ARROW_FORWARD); +// edgeR.setEdgeType(prefuse.Constants.EDGE_TYPE_CURVE); + + LabelRenderer edgeLabelR = new LabelRenderer(LABEL); + edgeLabelR.setRenderType(LabelRenderer.RENDER_TYPE_DRAW); + + DefaultRendererFactory drf = new DefaultRendererFactory(); + drf.setDefaultRenderer(nodeR); + drf.setDefaultEdgeRenderer(edgeR); + drf.add(new InGroupPredicate(EDGES_LABELS), edgeLabelR); + m_vis.setRendererFactory(drf); + DECORATOR_SCHEMA.setDefault(VisualItem.FILLCOLOR, ColorLib.gray(255)); + DECORATOR_SCHEMA.setDefault(VisualItem.STROKECOLOR, ColorLib.rgba(0, 0, 0, 0)); + DECORATOR_SCHEMA.setDefault(VisualItem.TEXTCOLOR, ColorLib.gray(0)); + m_vis.addDecorators(EDGES_LABELS, EDGES, DECORATOR_SCHEMA); + + // set up the visual operators + // first set up all the color actions + ColorAction nStrokeColor = new ColorAction(NODES, VisualItem.STROKECOLOR); + nStrokeColor.setDefaultColor(ColorLib.gray(100)); + nStrokeColor.add("_hover", ColorLib.rgb(255,100,100)); + StrokeAction nStroke = new EdgesStrokeAction(NODES); + + ColorAction nFill = new NPCPhraseColorAction(NODES, VisualItem.FILLCOLOR); + + ColorAction eEdges = new ConnectedEdgeColorAction(EDGES, VisualItem.STROKECOLOR); + ColorAction eArrows = new ConnectedEdgeColorAction(EDGES, VisualItem.FILLCOLOR); + ColorAction eEdgesLabels = new ConnectedEdgeColorAction(EDGES_LABELS, VisualItem.TEXTCOLOR); + + StrokeAction eStroke = new EdgesStrokeAction(EDGES); + + FontAction aFont = new FontAction(); + ColorAction aFontColor = new ColorAction(NODES, VisualItem.TEXTCOLOR); + aFontColor.setDefaultColor(ColorLib.rgb(0, 0, 0)); + + // bundle the color actions + ActionList colors = new ActionList(Activity.INFINITY); + colors.add(nStrokeColor); + colors.add(nFill); + colors.add(nStroke); + colors.add(eEdges); + colors.add(eArrows); + colors.add(eEdgesLabels); + colors.add(eStroke); + colors.add(aFont); + colors.add(aFontColor); + colors.add(new RepaintAction()); + m_vis.putAction("colors", colors); + + // now create the main layout routine + ActionList layout = new ActionList();//Activity.INFINITY); + NodeLinkTreeLayout treeLayout = new NodeLinkTreeLayout(GRAPH, prefuse.Constants.ORIENT_LEFT_RIGHT, 120, translatorMode ? 80 : 40, translatorMode ? 80 : 40); + treeLayout.setLayoutAnchor(new Point2D.Double(25,300)); + layout.add(treeLayout); + layout.add(new EdgesLabelDecoratorLayout(EDGES_LABELS)); + layout.add(new RepaintAction()); + m_vis.putAction("layout", layout); + + // set up the display + setSize(500,500); + pan(250, 250); + setHighQuality(true); + addControlListener(new TooltipControl()); + addControlListener(new DoubleClickControl()); + addControlListener(new WheelZoomControl()); + addControlListener(new ZoomControl()); + addControlListener(new PanControl()); + + // set things running + m_vis.run("colors"); + m_vis.run("layout"); + } + + public void loadGraph() { + graph = new Graph(true); + graph.addColumn(LABEL, String.class, ""); + graph.addColumn(ICON, Image.class, DefaultIcons.getNullifyIcon()); + graph.addColumn(TARGET, GameDataElement.class, null); + graph.addColumn(REPLY, Dialogue.Reply.class, null); + graph.addColumn(HIDDEN_REPLY, Dialogue.Reply.class, null); + graph.addColumn(HAS_REQS, boolean.class, false); + addDialogue(dialogue, npcIcon); + } + + public Node addDialogue(Dialogue dialogue, Image npcIcon) { + if (cells.get(dialogue) == null) { + if (dialogue.switch_to_npc != null) { + npcIcon = dialogue.switch_to_npc.getIcon(); + } + final Node dNode = graph.addNode(); + cells.put(dialogue, dNode); + String label; + Thread t = null; + if (dialogue.message == null) { + label = "[Selector]"; + } else if (translatorMode) { + label = dialogue.message+translationHeader+TRANSLATION_LOADING; + final String message = dialogue.message; + t = new Thread("Get weblate translation for "+message) { + public void run() { + WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); + dNode.setString(LABEL, message+translationHeader+unit.translatedText); + }; + }; + } else { + label = dialogue.message; + } + dNode.setString(LABEL, label); + if (t != null) t.start(); + dNode.set(ICON, npcIcon); + dNode.set(TARGET, dialogue); + if (dialogue.replies != null) { + Node rNode; + int i = 1; + for (Dialogue.Reply r : dialogue.replies) { + rNode = addReply(dialogue, r, npcIcon); + Edge e = graph.addEdge(dNode, rNode); + e.setString(LABEL, "#"+i++); + e.setBoolean(HAS_REQS, r.requirements != null && !r.requirements.isEmpty()); + } + } + } + return cells.get(dialogue); + } + + public Node addReply(Dialogue d, Dialogue.Reply r, Image npcIcon) { + final Node rNode; + if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) { + //Normal reply... + rNode = graph.addNode(); +// rNode.setString(LABEL, translatorMode ? r.text + "\n---\n" + WeblateIntegration.getTranslationUnit(r.text).translatedText : r.text); + String label; + Thread t = null; + if (translatorMode) { + label = r.text+translationHeader+TRANSLATION_LOADING; + final String message = r.text; + t = new Thread("Get weblate translation for "+message) { + public void run() { + WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); + rNode.setString(LABEL, message+translationHeader+unit.translatedText); + }; + }; + } else { + label = r.text; + } + rNode.setString(LABEL, label); + if (t != null) t.start(); + rNode.set(ICON, DefaultIcons.getHeroIcon()); + rNode.set(TARGET, d); + rNode.set(REPLY, r); + if (r.next_phrase != null) { + //...that leads to another phrase + Node dNode = addDialogue(r.next_phrase, npcIcon); + graph.addEdge(rNode, dNode); + } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { + //...that leads to a key phrase + Node kNode = addKeyPhraseNode(d, r.next_phrase_id); + kNode.set(REPLY, r); + graph.addEdge(rNode, kNode); + } + } else if (r.next_phrase != null) { + //Go directly to next phrase + rNode = addDialogue(r.next_phrase, npcIcon); + //Add a pointer to the hidden reply, in order to fetch requirements later. + rNode.set(HIDDEN_REPLY, r); + } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { + //Go directly to key phrase + rNode = addKeyPhraseNode(d, r.next_phrase_id); + rNode.set(REPLY, r); + } else { + //Incomplete. + rNode = graph.addNode(); + rNode.setString(LABEL, "[Incomplete reply]"); + rNode.set(ICON, DefaultIcons.getNullifyIcon()); + } + return rNode; + } + + public Node addKeyPhraseNode(Dialogue d, String key) { + Node kNode = graph.addNode(); + if (key.equals(Dialogue.Reply.EXIT_PHRASE_ID)) { + kNode.setString(LABEL, "[Ends dialogue]"); + kNode.set(ICON, DefaultIcons.getNullifyIcon()); + } else if (key.equals(Dialogue.Reply.FIGHT_PHRASE_ID)) { + kNode.setString(LABEL, "[Starts fight]"); + kNode.set(ICON, DefaultIcons.getCombatIcon()); + } else if (key.equals(Dialogue.Reply.REMOVE_PHRASE_ID)) { + kNode.setString(LABEL, "[NPC vanishes]"); + kNode.set(ICON, DefaultIcons.getNPCCloseIcon()); + } else if (key.equals(Dialogue.Reply.SHOP_PHRASE_ID)) { + kNode.setString(LABEL, "[Start trading]"); + kNode.set(ICON, DefaultIcons.getGoldIcon()); + } else { + //Should never reach, unless new key phrase ID are added to the model, but not here... + kNode.setString(LABEL, "[WTF !!]"+key); + } + kNode.set(TARGET, d); + return kNode; + } + + class MyLabelRenderer extends LabelRenderer { + public MyLabelRenderer(String label) { + super(label); + } + + @Override + protected Image getImage(VisualItem item) { + return (Image) item.get(ICON); + } + + @Override + protected String getText(VisualItem item) { + return TextUtils.wordWrap(super.getText(item), 40); + } + + } + + class ConnectedEdgeColorAction extends ColorAction { + + final int outgoing = ColorLib.rgb(255, 100, 100); + final int incoming = ColorLib.rgb(100, 255, 100); + final int none = ColorLib.gray(100); + + public ConnectedEdgeColorAction(String group, String field) { + super(group, field); + } + + @Override + public int getColor(VisualItem item) { + if (item instanceof DecoratorItem) { + item = ((DecoratorItem) item).getDecoratedItem(); + } + if (item instanceof EdgeItem) { + if (((EdgeItem) item).getSourceItem().isHover()) { + return outgoing; + } else if (((EdgeItem) item).getTargetItem().isHover()) { + return incoming; + } + } + + return none; + } + } + + class NPCPhraseColorAction extends ColorAction { + + final int none = ColorLib.gray(255); + final int hover = ColorLib.gray(200); + final int has_rewards = ColorLib.rgb(255, 255, 0); + final int has_rewards_hover = ColorLib.rgb(200, 200, 0); + + + public NPCPhraseColorAction(String group, String field) { + super(group, field); + } + + @Override + public int getColor(VisualItem item) { + // Change color for Dialogues, not replies. + if (item.get(TARGET) != null && item.get(REPLY) == null) { + Dialogue d = (Dialogue) item.get(TARGET); + if (d.rewards != null && !d.rewards.isEmpty()) { + if (item.isHover()) { + return has_rewards_hover; + } else { + return has_rewards; + } + } + } + if (item.isHover()) { + return hover; + } else { + return none; + } + } + } + + class EdgesStrokeAction extends StrokeAction { + + public final BasicStroke req_stroke = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); + public final BasicStroke hover_stroke = new BasicStroke(3.0f); + public final BasicStroke hover_req_stroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); + + public EdgesStrokeAction(String group) { + super(group); + } + + @Override + public BasicStroke getStroke(VisualItem item) { + if (item.getBoolean(HAS_REQS)) { + if (item instanceof EdgeItem) { + if (((EdgeItem) item).getSourceItem().isHover()) { + return hover_req_stroke; + } else if (((EdgeItem) item).getTargetItem().isHover()) { + return hover_req_stroke; + } + } + return req_stroke; + } else { + if (item.isHover()) { + return hover_stroke; + } else if (item instanceof EdgeItem) { + if (((EdgeItem) item).getSourceItem().isHover()) { + return hover_stroke; + } else if (((EdgeItem) item).getTargetItem().isHover()) { + return hover_stroke; + } + } + } + return super.getStroke(item); + } + + } + + class EdgesLabelDecoratorLayout extends Layout { + public EdgesLabelDecoratorLayout(String group) { + super(group); + } + public void run(double frac) { + Iterator iter = m_vis.items(m_group); + while ( iter.hasNext() ) { + DecoratorItem decorator = (DecoratorItem)iter.next(); + if( decorator.getDecoratedItem() instanceof EdgeItem) { + EdgeItem edgeItem = (EdgeItem) decorator.getDecoratedItem(); + double deltaX = edgeItem.getTargetItem().getX() - edgeItem.getSourceItem().getX(); + double deltaY = edgeItem.getTargetItem().getY() - edgeItem.getSourceItem().getY(); + double hypo = Math.hypot(deltaX, deltaY); + + double edgePropX = deltaX / hypo; + double edgePropY = deltaY / hypo; + + Point2D start = new Point2D.Double(edgeItem.getSourceItem().getBounds().getCenterX(), edgeItem.getSourceItem().getBounds().getCenterY()); + Point2D end = new Point2D.Double(edgeItem.getTargetItem().getBounds().getCenterX(), edgeItem.getTargetItem().getBounds().getCenterY()); + Point2D[] realStart = new Point2D[]{new Point2D.Double(), new Point2D.Double()}; +// Point2D[] realEnd = new Point2D[]{new Point2D.Double(), new Point2D.Double()}; + + int i = GraphicsLib.intersectLineRectangle(start, end, edgeItem.getSourceItem().getBounds(), realStart); + if (i > 0) { + start = realStart[0]; + } +// i = GraphicsLib.intersectLineRectangle(start, end, edgeItem.getTargetItem().getBounds(), realEnd); +// if (i > 0) { +// end = realEnd[0]; +// } + + double coef = 20 * Math.atan(hypo / 100.0) + 20; + + setX(decorator, null, start.getX() + coef * edgePropX + 6 * Math.random() - 3); + setY(decorator, null, start.getY() + coef * edgePropY + 6 * Math.random() - 3); + } else { + VisualItem decoratedItem = decorator.getDecoratedItem(); + Rectangle2D bounds = decoratedItem.getBounds(); + double x = bounds.getCenterX(); + double y = bounds.getCenterY(); + setX(decorator, null, x + 10 * Math.random() - 5); + setY(decorator, null, y + 10 * Math.random() - 5); + } + } + } + } + + class DoubleClickControl extends ControlAdapter { + @Override + public void itemClicked(VisualItem item, MouseEvent e) { + if (e.getClickCount() == 2) { + if (item.get(TARGET) != null) { + ATContentStudio.frame.openEditor((GameDataElement)item.get(TARGET)); + } + } + } + } + + class TooltipControl extends ControlAdapter { + + @Override + public void itemEntered(VisualItem item, MouseEvent e) { + if (item.get(TARGET) != null) { + tooltippedItem = item; + if (!tooltipActivated) { + setToolTipText(""); + ToolTipManager.sharedInstance().registerComponent(DialogueGraphView.this); + ToolTipManager.sharedInstance().setEnabled(true); + tooltipActivated = true; + } + } + } + @Override + public void itemExited(VisualItem item, MouseEvent e) { + //Hides the tooltip... + ToolTipManager.sharedInstance().setEnabled(false); + ToolTipManager.sharedInstance().unregisterComponent(DialogueGraphView.this); + tooltipActivated = false; + } + } + + JToolTip tt = null; + private VisualItem tooltippedItem = null; + private VisualItem lastTTItem = null; + private boolean tooltipActivated = false; + + @Override + public Point getToolTipLocation(MouseEvent event) { + return new Point(event.getX() + 5, event.getY() + 5); + } + + @Override + public JToolTip createToolTip() { + if (tt == null) tt = super.createToolTip(); + if (tooltippedItem == lastTTItem) { + return tt; + } + tt = super.createToolTip(); + lastTTItem = tooltippedItem; + tt.setLayout(new BorderLayout()); + JPanel content = new JPanel(); + content.setLayout(new JideBoxLayout(content, JideBoxLayout.PAGE_AXIS)); + JLabel label; + if (tooltippedItem != null) { + Object target = tooltippedItem.get(TARGET); + if (target != null) { + if (target instanceof Dialogue) { + Dialogue d = (Dialogue) target; + label = new JLabel(new ImageIcon(DefaultIcons.getDialogueIcon())); + label.setText(d.id); + content.add(label, JideBoxLayout.FIX); + Object replObj = tooltippedItem.get(REPLY); + if (replObj == null) { + replObj = tooltippedItem.get(HIDDEN_REPLY); + } + if (replObj != null && replObj instanceof Dialogue.Reply) { + Dialogue.Reply r = (Dialogue.Reply) replObj; + if (r.requirements != null && !r.requirements.isEmpty()) { + JLabel reqTitle = new JLabel("--Requirements--", SwingConstants.CENTER); + content.add(reqTitle, JideBoxLayout.FIX); + for (Requirement req : r.requirements) { + label = new JLabel("", SwingConstants.CENTER); + DialogueEditor.decorateRequirementJLabel(label, req); + content.add(label, JideBoxLayout.FIX); + } + } + } + if (d.rewards != null && !d.rewards.isEmpty()) { + JLabel rewTitle = new JLabel("--Rewards--", SwingConstants.CENTER); + rewTitle.setAlignmentY(CENTER_ALIGNMENT); + content.add(rewTitle, JideBoxLayout.FIX); + for (Dialogue.Reward r : d.rewards) { + label = new JLabel("", SwingConstants.CENTER); + DialogueEditor.decorateRewardJLabel(label, r); + content.add(label, JideBoxLayout.FIX); + } + } + } + } + + } + + tt.add(content, BorderLayout.CENTER); + tt.setPreferredSize(tt.getLayout().preferredLayoutSize(tt)); + return tt; + } + +} + + diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java index 47509d1..5d663cb 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java @@ -27,6 +27,7 @@ import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.plaf.basic.BasicInternalFrameUI; +import com.gpl.rpg.atcontentstudio.utils.TextUtils; import prefuse.Display; import prefuse.Visualization; import prefuse.action.Action; @@ -415,24 +416,7 @@ public class WriterModeEditor extends Editor { @Override protected String getText(VisualItem item) { if (!item.getBoolean(IS_REPLY) && super.getText(item) == null) return "[Selector]"; - return wordWrap(super.getText(item), 40); - } - - public String wordWrap(String in, int length) { - if (in == null) return null; - final String newline = "\n"; - //:: Trim - while(in.length() > 0 && (in.charAt(0) == '\t' || in.charAt(0) == ' ')) in = in.substring(1); - //:: If Small Enough Already, Return Original - if(in.length() < length) return in; - //:: If Next length Contains Newline, Split There - if(in.substring(0, length).contains(newline)) return in.substring(0, in.indexOf(newline)).trim() + newline + wordWrap(in.substring(in.indexOf("\n") + 1), length); - //:: Otherwise, Split Along Nearest Previous Space/Tab/Dash - int spaceIndex = Math.max(Math.max( in.lastIndexOf(" ", length), in.lastIndexOf("\t", length)), in.lastIndexOf("-", length)); - //:: If No Nearest Space, Split At length - if(spaceIndex == -1) spaceIndex = length; - //:: Split - return in.substring(0, spaceIndex).trim() + newline + wordWrap(in.substring(spaceIndex), length); + return TextUtils.wordWrap(super.getText(item), 40); } } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java new file mode 100644 index 0000000..dfc534f --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java @@ -0,0 +1,20 @@ +package com.gpl.rpg.atcontentstudio.utils; + +public class TextUtils { + public static String wordWrap(String in, int length) { + if(in == null || length <= 0) return in; + final String newline = "\n"; + //:: Trim + while(in.length() > 0 && (in.charAt(0) == '\t' || in.charAt(0) == ' ')) in = in.substring(1); + //:: If Small Enough Already, Return Original + if(in.length() < length) return in; + //:: If Next length Contains Newline, Split There + if(in.substring(0, length).contains(newline)) return in.substring(0, in.indexOf(newline)).trim() + newline + wordWrap(in.substring(in.indexOf("\n") + 1), length); + //:: Otherwise, Split Along Nearest Previous Space/Tab/Dash + int spaceIndex = Math.max(Math.max( in.lastIndexOf(" ", length), in.lastIndexOf("\t", length)), in.lastIndexOf("-", length)); + //:: If No Nearest Space, Split At length + if(spaceIndex == -1) spaceIndex = length; + //:: Split + return in.substring(0, spaceIndex).trim() + newline + wordWrap(in.substring(spaceIndex), length); + } +} From e1e85d7a9026c048e5e40211ab2d8d1eb0d4ec71 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 20:26:18 +0200 Subject: [PATCH 11/94] extract into CustomListModel --- .../atcontentstudio/ui/CustomListModel.java | 90 +++++++ .../ui/gamedataeditors/DialogueEditor.java | 234 +++--------------- .../ui/gamedataeditors/DroplistEditor.java | 63 +---- 3 files changed, 131 insertions(+), 256 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java diff --git a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java new file mode 100644 index 0000000..90dff18 --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java @@ -0,0 +1,90 @@ +package com.gpl.rpg.atcontentstudio.ui; + +import javax.swing.*; +import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +public abstract class CustomListModel implements ListModel { + protected S source; + + protected abstract List getItems(); + protected abstract void setItems(List items); + + public CustomListModel(S source) { + this.source = source; + } + + @Override + public int getSize() { + if (getItems() == null) return 0; + return getItems().size(); + } + + @Override + public E getElementAt(int index) { + if (getItems() == null) return null; + return getItems().get(index); + } + + public void addItem(E item) { + if (getItems() == null) { + setItems(new ArrayList()); + } + getItems().add(item); + int index = getItems().indexOf(item); + for (ListDataListener l : listeners) { + l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); + } + } + + public void removeItem(E item) { + int index = getItems().indexOf(item); + getItems().remove(item); + if (getItems().isEmpty()) { + setItems(null); + } + for (ListDataListener l : listeners) { + l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); + } + } + + public void moveUp(E item) { + moveUpOrDown(item, -1); + } + + public void moveDown(E item) { + moveUpOrDown(item, 1); + } + + private void moveUpOrDown(E item, int direction) { + int index = getItems().indexOf(item); + E exchanged = getItems().get(index + direction); + getItems().set(index, exchanged); + getItems().set(index + direction, item); + for (ListDataListener l : listeners) { + l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index + direction, index)); + } + } + + public void itemChanged(E item) { + int index = getItems().indexOf(item); + for (ListDataListener l : listeners) { + l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); + } + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addListDataListener(ListDataListener l) { + listeners.add(l); + } + + @Override + public void removeListDataListener(ListDataListener l) { + listeners.remove(l); + } +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index a520145..6fd50c4 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -12,7 +12,6 @@ import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.ButtonGroup; import javax.swing.DefaultListCellRenderer; @@ -28,10 +27,7 @@ import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.JTextField; -import javax.swing.ListModel; import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @@ -52,6 +48,7 @@ import com.gpl.rpg.atcontentstudio.ui.BooleanBasedCheckBox; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.gpl.rpg.atcontentstudio.ui.CustomListModel; import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; import com.jidesoft.swing.JideBoxLayout; @@ -812,65 +809,19 @@ public class DialogueEditor extends JSONElementEditor { } - public static class RewardsListModel implements ListModel { - - Dialogue source; - + public static class RewardsListModel extends CustomListModel { + @Override + protected List getItems() { + return source.rewards; + } + + @Override + protected void setItems(List items) { + source.rewards = items; + } + public RewardsListModel(Dialogue dialogue) { - this.source = dialogue; - } - - @Override - public int getSize() { - if (source.rewards == null) return 0; - return source.rewards.size(); - } - - @Override - public Dialogue.Reward getElementAt(int index) { - if (source.rewards == null) return null; - return source.rewards.get(index); - } - - public void addItem(Dialogue.Reward item) { - if (source.rewards == null) { - source.rewards = new ArrayList(); - } - source.rewards.add(item); - int index = source.rewards.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Dialogue.Reward item) { - int index = source.rewards.indexOf(item); - source.rewards.remove(item); - if (source.rewards.isEmpty()) { - source.rewards = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - public void itemChanged(Dialogue.Reward item) { - int index = source.rewards.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + super(dialogue); } } @@ -981,87 +932,19 @@ public class DialogueEditor extends JSONElementEditor { } - public static class RepliesListModel implements ListModel { + public static class RepliesListModel extends CustomListModel { + @Override + protected List getItems() { + return source.replies; + } - Dialogue source; + @Override + protected void setItems(List items) { + source.replies = items; + } public RepliesListModel(Dialogue dialogue) { - this.source = dialogue; - } - - - @Override - public int getSize() { - if (source.replies == null) return 0; - return source.replies.size(); - } - - @Override - public Dialogue.Reply getElementAt(int index) { - if (source.replies == null) return null; - return source.replies.get(index); - } - - public void addItem(Dialogue.Reply item) { - if (source.replies == null) { - source.replies = new ArrayList(); - } - source.replies.add(item); - int index = source.replies.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Dialogue.Reply item) { - int index = source.replies.indexOf(item); - source.replies.remove(item); - if (source.replies.isEmpty()) { - source.replies = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - public void itemChanged(Dialogue.Reply item) { - int index = source.replies.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - public void moveUp(Dialogue.Reply item) { - int index = source.replies.indexOf(item); - Dialogue.Reply exchanged = source.replies.get(index - 1); - source.replies.set(index, exchanged); - source.replies.set(index - 1, item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index - 1, index)); - } - } - - public void moveDown(Dialogue.Reply item) { - int index = source.replies.indexOf(item); - Dialogue.Reply exchanged = source.replies.get(index + 1); - source.replies.set(index, exchanged); - source.replies.set(index + 1, item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index + 1)); - } - } - - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + super(dialogue); } } @@ -1115,69 +998,20 @@ public class DialogueEditor extends JSONElementEditor { } } - public static class ReplyRequirementsListModel implements ListModel { + public static class ReplyRequirementsListModel extends CustomListModel { + @Override + protected List getItems() { + return source.requirements; + } + + @Override + protected void setItems(List items) { + source.requirements = items; + } - Dialogue.Reply reply; - public ReplyRequirementsListModel(Dialogue.Reply reply) { - this.reply = reply; + super(reply); } - - @Override - public int getSize() { - if (reply.requirements == null) return 0; - return reply.requirements.size(); - } - - @Override - public Requirement getElementAt(int index) { - if (reply.requirements == null) return null; - return reply.requirements.get(index); - } - - - - public void addItem(Requirement item) { - if (reply.requirements == null) { - reply.requirements = new ArrayList(); - } - reply.requirements.add(item); - int index = reply.requirements.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Requirement item) { - int index = reply.requirements.indexOf(item); - reply.requirements.remove(item); - if (reply.requirements.isEmpty()) { - reply.requirements = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - public void itemChanged(Requirement item) { - int index = reply.requirements.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - } public static class ReplyRequirementsCellRenderer extends DefaultListCellRenderer { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java index e644c17..1c69553 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java @@ -5,7 +5,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; @@ -17,10 +16,7 @@ import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; -import javax.swing.ListModel; import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @@ -34,6 +30,7 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.Item; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.gpl.rpg.atcontentstudio.ui.CustomListModel; import com.jidesoft.swing.JideBoxLayout; public class DroplistEditor extends JSONElementEditor { @@ -148,65 +145,19 @@ public class DroplistEditor extends JSONElementEditor { pane.repaint(); } - public class DroppedItemsListModel implements ListModel { - - Droplist source; - + public class DroppedItemsListModel extends CustomListModel { public DroppedItemsListModel(Droplist droplist) { - this.source = droplist; + super(droplist); } @Override - public int getSize() { - if (source.dropped_items == null) return 0; - return source.dropped_items.size(); - } - - @Override - public Droplist.DroppedItem getElementAt(int index) { - if (source.dropped_items == null) return null; - return source.dropped_items.get(index); - } - - public void addItem(Droplist.DroppedItem item) { - if (source.dropped_items == null) { - source.dropped_items = new ArrayList(); - } - source.dropped_items.add(item); - int index = source.dropped_items.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Droplist.DroppedItem item) { - int index = source.dropped_items.indexOf(item); - source.dropped_items.remove(item); - if (source.dropped_items.isEmpty()) { - source.dropped_items = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } + protected List getItems() { + return source.dropped_items; } - public void itemChanged(Droplist.DroppedItem item) { - int index = source.dropped_items.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.dropped_items = items; } } From 355bb2bc5476876e976ae3c515cd65880b0f1c5f Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 22:12:31 +0200 Subject: [PATCH 12/94] extract collapsibleItemList with buttons into method this is currently done for - items in a droplist - replies - rewards others should follow --- .../ui/gamedataeditors/DialogueEditor.java | 245 +++++++++++------- .../ui/gamedataeditors/DroplistEditor.java | 83 ++---- .../atcontentstudio/utils/BasicLambda.java | 6 + .../utils/BasicLambdaWithArg.java | 5 + .../utils/BasicLambdaWithReturn.java | 5 + .../rpg/atcontentstudio/utils/UiUtils.java | 145 +++++++++++ 6 files changed, 330 insertions(+), 159 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/utils/BasicLambda.java create mode 100644 src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArg.java create mode 100644 src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithReturn.java create mode 100644 src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index 6fd50c4..df317db 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -23,13 +23,9 @@ import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JRadioButton; -import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; @@ -51,6 +47,7 @@ import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; import com.gpl.rpg.atcontentstudio.ui.CustomListModel; import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; +import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; public class DialogueEditor extends JSONElementEditor { @@ -174,12 +171,12 @@ public class DialogueEditor extends JSONElementEditor { idField = addTextField(pane, "Internal ID: ", dialogue.id, dialogue.writable, listener); messageField = addTranslatableTextArea(pane, "Message: ", dialogue.message, dialogue.writable, listener); switchToNpcBox = addNPCBox(pane, dialogue.getProject(), "Switch active NPC to: ", dialogue.switch_to_npc, dialogue.writable, listener); - - CollapsiblePanel rewards = new CollapsiblePanel("Reaching this phrase gives the following rewards: "); + + /* + CollapsiblePanel rewards = new CollapsiblePanel(titleRewards); rewards.setLayout(new JideBoxLayout(rewards, JideBoxLayout.PAGE_AXIS)); - rewardsListModel = new RewardsListModel(dialogue); rewardsList = new JList(rewardsListModel); - rewardsList.setCellRenderer(new RewardsCellRenderer()); + rewardsList.setCellRenderer(cellRendererRewards); rewardsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); rewards.add(new JScrollPane(rewardsList), JideBoxLayout.FIX); final JPanel rewardsEditorPane = new JPanel(); @@ -227,38 +224,51 @@ public class DialogueEditor extends JSONElementEditor { listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); rewards.add(listButtonsPane, JideBoxLayout.FIX); } + rewardsEditorPane.setLayout(new JideBoxLayout(rewardsEditorPane, JideBoxLayout.PAGE_AXIS)); + rewards.add(rewardsEditorPane, JideBoxLayout.FIX); + */ + RewardsCellRenderer cellRendererRewards = new RewardsCellRenderer(); + String titleRewards = "Reaching this phrase gives the following rewards: "; + rewardsListModel = new RewardsListModel(dialogue); + + CollapsiblePanel rewards = UiUtils.getCollapsibleItemList( + listener, + rewardsListModel, + () -> selectedReward = null, + ( selectedItem) -> this.selectedReward = selectedItem, + () -> this.selectedReward, + (reward)->{}, + (editorPane) -> updateRewardsEditorPane(editorPane, this.selectedReward, listener), + dialogue.writable, + Dialogue.Reward::new, + cellRendererRewards, + titleRewards, + false + ).collapsiblePanel; if (dialogue.rewards == null || dialogue.rewards.isEmpty()) { rewards.collapse(); } - rewardsEditorPane.setLayout(new JideBoxLayout(rewardsEditorPane, JideBoxLayout.PAGE_AXIS)); - rewards.add(rewardsEditorPane, JideBoxLayout.FIX); - pane.add(rewards, JideBoxLayout.FIX); - - CollapsiblePanel replies = new CollapsiblePanel("Replies / Next Phrase: "); - replies.setLayout(new JideBoxLayout(replies, JideBoxLayout.PAGE_AXIS)); - repliesListModel = new RepliesListModel(dialogue); - repliesList = new JList(repliesListModel); - repliesList.setCellRenderer(new RepliesCellRenderer()); - repliesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - replies.add(new JScrollPane(repliesList), JideBoxLayout.FIX); - final JPanel repliesEditorPane = new JPanel(); - final JButton createReply = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteReply = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - final JButton moveReplyUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); - final JButton moveReplyDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); - deleteReply.setEnabled(false); - moveReplyUp.setEnabled(false); - moveReplyDown.setEnabled(false); - repliesList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { + + /*{ + CollapsiblePanel replies = new CollapsiblePanel(title); + replies.setLayout(new JideBoxLayout(replies, JideBoxLayout.PAGE_AXIS)); + repliesListModel = new RepliesListModel(dialogue); + repliesList = new JList(repliesListModel); + repliesList.setCellRenderer(cellRenderer); + repliesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + replies.add(new JScrollPane(repliesList), JideBoxLayout.FIX); + final JPanel repliesEditorPane = new JPanel(); + final JButton createReply = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteReply = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + final JButton moveReplyUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); + final JButton moveReplyDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); + deleteReply.setEnabled(false); + moveReplyUp.setEnabled(false); + moveReplyDown.setEnabled(false); + repliesList.addListSelectionListener(e -> { selectedReply = (Dialogue.Reply) repliesList.getSelectedValue(); - if (selectedReply != null && !Dialogue.Reply.GO_NEXT_TEXT.equals(selectedReply.text)) { - replyTextCache = selectedReply.text; - } else { - replyTextCache = null; - } + replyValueChanged(selectedReply); if (selectedReply != null) { deleteReply.setEnabled(true); moveReplyUp.setEnabled(repliesList.getSelectedIndex() > 0); @@ -269,65 +279,88 @@ public class DialogueEditor extends JSONElementEditor { moveReplyDown.setEnabled(false); } updateRepliesEditorPane(repliesEditorPane, selectedReply, listener); + }); + if (dialogue.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createReply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Dialogue.Reply reply = new Dialogue.Reply(); + repliesListModel.addItem(reply); + repliesList.setSelectedValue(reply, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteReply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedReply != null) { + repliesListModel.removeItem(selectedReply); + selectedReply = null; + repliesList.clearSelection(); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + moveReplyUp.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (selectedReply != null) { + repliesListModel.moveUp(selectedReply); + repliesList.setSelectedValue(selectedReply, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + moveReplyDown.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (selectedReply != null) { + repliesListModel.moveDown(selectedReply); + repliesList.setSelectedValue(selectedReply, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + listButtonsPane.add(createReply, JideBoxLayout.FIX); + listButtonsPane.add(deleteReply, JideBoxLayout.FIX); + listButtonsPane.add(moveReplyUp, JideBoxLayout.FIX); + listButtonsPane.add(moveReplyDown, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + replies.add(listButtonsPane, JideBoxLayout.FIX); } - }); - if (dialogue.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createReply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Dialogue.Reply reply = new Dialogue.Reply(); - repliesListModel.addItem(reply); - repliesList.setSelectedValue(reply, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteReply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedReply != null) { - repliesListModel.removeItem(selectedReply); - selectedReply = null; - repliesList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + repliesEditorPane.setLayout(new JideBoxLayout(repliesEditorPane, JideBoxLayout.PAGE_AXIS)); + replies.add(repliesEditorPane, JideBoxLayout.FIX); + }*/ + RepliesCellRenderer cellRendererReplies = new RepliesCellRenderer(); + String titleReplies = "Replies / Next Phrase: "; + repliesListModel = new RepliesListModel(dialogue); + CollapsiblePanel replies = UiUtils.getCollapsibleItemList( + listener, + repliesListModel, + () -> selectedReply = null, + ( selectedItem) -> this.selectedReply = selectedItem, + () -> this.selectedReply, + (selectedReply)-> { + if (selectedReply != null && !Dialogue.Reply.GO_NEXT_TEXT.equals(selectedReply.text)) { + replyTextCache = selectedReply.text; + } else { + replyTextCache = null; } - } - }); - moveReplyUp.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedReply != null) { - repliesListModel.moveUp(selectedReply); - repliesList.setSelectedValue(selectedReply, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveReplyDown.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedReply != null) { - repliesListModel.moveDown(selectedReply); - repliesList.setSelectedValue(selectedReply, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createReply, JideBoxLayout.FIX); - listButtonsPane.add(deleteReply, JideBoxLayout.FIX); - listButtonsPane.add(moveReplyUp, JideBoxLayout.FIX); - listButtonsPane.add(moveReplyDown, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - replies.add(listButtonsPane, JideBoxLayout.FIX); - } + }, + (editorPane) -> updateRepliesEditorPane(editorPane, this.selectedReply, listener), + dialogue.writable, + Dialogue.Reply::new, + cellRendererReplies, + titleReplies + , true + ).collapsiblePanel; if (dialogue.replies == null || dialogue.replies.isEmpty()) { replies.collapse(); } - repliesEditorPane.setLayout(new JideBoxLayout(repliesEditorPane, JideBoxLayout.PAGE_AXIS)); - replies.add(repliesEditorPane, JideBoxLayout.FIX); pane.add(replies, JideBoxLayout.FIX); @@ -582,12 +615,15 @@ public class DialogueEditor extends JSONElementEditor { pane.add(comboPane, JideBoxLayout.FIX); updateRepliesParamsEditorPane(repliesParamsPane, reply, listener); pane.add(repliesParamsPane, JideBoxLayout.FIX); - - CollapsiblePanel requirementsPane = new CollapsiblePanel("Requirements the player must fulfill to select this reply: "); - requirementsPane.setLayout(new JideBoxLayout(requirementsPane, JideBoxLayout.PAGE_AXIS)); + + String titleRequirements = "Requirements the player must fulfill to select this reply: "; requirementsListModel = new ReplyRequirementsListModel(reply); + ReplyRequirementsCellRenderer cellRendererRequirements = new ReplyRequirementsCellRenderer(); + /* + CollapsiblePanel requirementsPane = new CollapsiblePanel(titleRequirements); + requirementsPane.setLayout(new JideBoxLayout(requirementsPane, JideBoxLayout.PAGE_AXIS)); requirementsList = new JList(requirementsListModel); - requirementsList.setCellRenderer(new ReplyRequirementsCellRenderer()); + requirementsList.setCellRenderer(cellRendererRequirements); requirementsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); requirementsPane.add(new JScrollPane(requirementsList), JideBoxLayout.FIX); final JPanel requirementsEditorPane = new JPanel(); @@ -656,12 +692,31 @@ public class DialogueEditor extends JSONElementEditor { requirementsPane.add(listButtonsPane, JideBoxLayout.FIX); } requirementsEditorPane.setLayout(new JideBoxLayout(requirementsEditorPane, JideBoxLayout.PAGE_AXIS)); - requirementsPane.add(requirementsEditorPane, JideBoxLayout.FIX); + requirementsPane.add(requirementsEditorPane, JideBoxLayout.FIX);*/ + + UiUtils.CollapsibleItemListCreation itemsPane = UiUtils.getCollapsibleItemList( + listener, + requirementsListModel, + () -> selectedRequirement = null, + (selectedItem) -> this.selectedRequirement = selectedItem, + () -> this.selectedRequirement, + (selectedItem)->{}, + (droppedItemsEditorPane) -> updateRequirementsEditorPane(droppedItemsEditorPane, this.selectedRequirement, listener), + target.writable, + Requirement::new, + cellRendererRequirements, + titleRequirements, + false + ); + CollapsiblePanel requirementsPane = itemsPane.collapsiblePanel; + requirementsList = itemsPane.list; + if (reply.requirements == null || reply.requirements.isEmpty()) { requirementsPane.collapse(); } + pane.add(requirementsPane, JideBoxLayout.FIX); - + pane.revalidate(); pane.repaint(); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java index 1c69553..d70f744 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java @@ -1,24 +1,17 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; -import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; -import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; @@ -28,9 +21,9 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist.DroppedItem; import com.gpl.rpg.atcontentstudio.model.gamedata.Item; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; import com.gpl.rpg.atcontentstudio.ui.CustomListModel; +import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; public class DroplistEditor extends JSONElementEditor { @@ -65,61 +58,23 @@ public class DroplistEditor extends JSONElementEditor { createButtonPane(pane, droplist.getProject(), droplist, Droplist.class, Droplist.getImage(), null, listener); idField = addTextField(pane, "Droplist ID: ", droplist.id, droplist.writable, listener); - - CollapsiblePanel itemsPane = new CollapsiblePanel("Items in this droplist: "); - itemsPane.setLayout(new JideBoxLayout(itemsPane, JideBoxLayout.PAGE_AXIS)); - droppedItemsListModel = new DroppedItemsListModel(droplist); - final JList itemsList = new JList(droppedItemsListModel); - itemsList.setCellRenderer(new DroppedItemsCellRenderer()); - itemsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - itemsPane.add(new JScrollPane(itemsList), JideBoxLayout.FIX); - final JPanel droppedItemsEditorPane = new JPanel(); - final JButton createDroppedItem = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteDroppedItem = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deleteDroppedItem.setEnabled(false); - itemsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedItem = (Droplist.DroppedItem) itemsList.getSelectedValue(); - if (selectedItem == null) { - deleteDroppedItem.setEnabled(false); - } else { - deleteDroppedItem.setEnabled(true); - } - updateDroppedItemsEditorPane(droppedItemsEditorPane, selectedItem, listener); - } - }); - if (droplist.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createDroppedItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Droplist.DroppedItem tempItem = new Droplist.DroppedItem(); - droppedItemsListModel.addItem(tempItem); - itemsList.setSelectedValue(tempItem, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteDroppedItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedItem != null) { - droppedItemsListModel.removeItem(selectedItem); - selectedItem = null; - itemsList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createDroppedItem, JideBoxLayout.FIX); - listButtonsPane.add(deleteDroppedItem, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - itemsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - droppedItemsEditorPane.setLayout(new JideBoxLayout(droppedItemsEditorPane, JideBoxLayout.PAGE_AXIS)); - itemsPane.add(droppedItemsEditorPane, JideBoxLayout.FIX); + + + droppedItemsListModel = new DroplistEditor.DroppedItemsListModel(droplist); + CollapsiblePanel itemsPane = UiUtils.getCollapsibleItemList( + listener, + droppedItemsListModel, + () -> selectedItem = null, + (selectedItem) -> this.selectedItem = selectedItem, + () -> this.selectedItem, + (selectedItem)->{}, + (droppedItemsEditorPane) -> updateDroppedItemsEditorPane(droppedItemsEditorPane, this.selectedItem, listener), + droplist.writable, + DroppedItem::new, + new DroppedItemsCellRenderer(), + "Items in this droplist: ", + false + ).collapsiblePanel; if (droplist.dropped_items == null || droplist.dropped_items.isEmpty()) { itemsPane.collapse(); } @@ -127,7 +82,7 @@ public class DroplistEditor extends JSONElementEditor { pane.add(itemsPane, JideBoxLayout.FIX); } - + public void updateDroppedItemsEditorPane(JPanel pane, DroppedItem di, FieldUpdateListener listener) { boolean writable = ((Droplist)target).writable; Project proj = ((Droplist)target).getProject(); diff --git a/src/com/gpl/rpg/atcontentstudio/utils/BasicLambda.java b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambda.java new file mode 100644 index 0000000..14a2141 --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambda.java @@ -0,0 +1,6 @@ +package com.gpl.rpg.atcontentstudio.utils; + +public interface BasicLambda { + public void doIt(); +} + diff --git a/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArg.java b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArg.java new file mode 100644 index 0000000..66229db --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArg.java @@ -0,0 +1,5 @@ +package com.gpl.rpg.atcontentstudio.utils; + +public interface BasicLambdaWithArg { + public void doIt(T arg); +} diff --git a/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithReturn.java b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithReturn.java new file mode 100644 index 0000000..124941b --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithReturn.java @@ -0,0 +1,5 @@ +package com.gpl.rpg.atcontentstudio.utils; + +public interface BasicLambdaWithReturn { + public R doIt(); +} diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java new file mode 100644 index 0000000..0ce7573 --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -0,0 +1,145 @@ +package com.gpl.rpg.atcontentstudio.utils; + +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; +import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; +import com.gpl.rpg.atcontentstudio.ui.CustomListModel; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.jidesoft.swing.JideBoxLayout; + +import javax.swing.*; +import java.awt.event.*; +import java.util.function.Supplier; + +public class UiUtils { + public static class CollapsibleItemListCreation { + public CollapsiblePanel collapsiblePanel; + public JList list; + } + + public static > CollapsibleItemListCreation getCollapsibleItemList(FieldUpdateListener listener, + M itemsListModel, + BasicLambda selectedItemReset, + BasicLambdaWithArg setSelectedItem, + BasicLambdaWithReturn selectedItem, + BasicLambdaWithArg valueChanged, + BasicLambdaWithArg updateEditorPane, + boolean writable, + Supplier tempSupplier, + DefaultListCellRenderer cellRenderer, + String title, + boolean withMoveButtons) { + CollapsiblePanel itemsPane = new CollapsiblePanel(title); + itemsPane.setLayout(new JideBoxLayout(itemsPane, JideBoxLayout.PAGE_AXIS)); + final JList itemsList = new JList<>(itemsListModel); + itemsList.setCellRenderer(cellRenderer); + itemsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + itemsPane.add(new JScrollPane(itemsList), JideBoxLayout.FIX); + final JPanel editorPane = new JPanel(); + final JButton createBtn = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteBtn = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + final JButton moveUpBtn = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); + final JButton moveDownBtn = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); + deleteBtn.setEnabled(false); + moveUpBtn.setEnabled(false); + moveDownBtn.setEnabled(false); + itemsList.addListSelectionListener(e -> { + E selectedValue = itemsList.getSelectedValue(); + valueChanged.doIt(selectedValue); + setSelectedItem.doIt(selectedValue); + if (selectedValue == null) { + deleteBtn.setEnabled(false); + if (withMoveButtons) { + moveUpBtn.setEnabled(false); + moveDownBtn.setEnabled(false); + } + } else { + deleteBtn.setEnabled(true); + if (withMoveButtons) { + moveUpBtn.setEnabled(itemsList.getSelectedIndex() > 0); + moveDownBtn.setEnabled(itemsList.getSelectedIndex() < (itemsListModel.getSize() - 1)); + } + } + updateEditorPane.doIt(editorPane); + }); + if (writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + + createBtn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + E tempItem = tempSupplier.get(); + itemsListModel.addItem(tempItem); + itemsList.setSelectedValue(tempItem, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + listButtonsPane.add(createBtn, JideBoxLayout.FIX); + + deleteBtn.addActionListener(e -> { + if (selectedItem.doIt() != null) { + itemsListModel.removeItem(selectedItem.doIt()); + selectedItemReset.doIt(); + itemsList.clearSelection(); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + listButtonsPane.add(deleteBtn, JideBoxLayout.FIX); + if(withMoveButtons) { + moveUpBtn.addActionListener(e -> { + if (selectedItem.doIt() != null) { + itemsListModel.moveUp(selectedItem.doIt()); + itemsList.setSelectedValue(selectedItem.doIt(), true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + listButtonsPane.add(moveUpBtn, JideBoxLayout.FIX); + + moveDownBtn.addActionListener(e -> { + if (selectedItem.doIt() != null) { + itemsListModel.moveDown(selectedItem.doIt()); + itemsList.setSelectedValue(selectedItem.doIt(), true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + listButtonsPane.add(moveDownBtn, JideBoxLayout.FIX); + } + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + itemsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + //TODO: add double click to navigate to the item in the editor pane. + // TODO: figure out what ID is needed here +// itemsList.addMouseListener(new MouseAdapter() { +// @Override +// public void mouseClicked(MouseEvent e) { +// if (e.getClickCount() == 2) { +// if (itemsList.getSelectedValue() != null && ((E)itemsList.getSelectedValue()).required_obj != null) { +// ATContentStudio.frame.openEditor(((E)itemsList.getSelectedValue()).required_obj); +// ATContentStudio.frame.selectInTree(((E)itemsList.getSelectedValue()).required_obj); +// } +// } +// } +// }); +// itemsList.addKeyListener(new KeyAdapter() { +// @Override +// public void keyReleased(KeyEvent e) { +// if (e.getKeyCode() == KeyEvent.VK_ENTER) { +// ATContentStudio.frame.openEditor(((E)itemsList.getSelectedValue()).required_obj); +// ATContentStudio.frame.selectInTree(((E)itemsList.getSelectedValue()).required_obj); +// } +// } +// }); + + editorPane.setLayout(new JideBoxLayout(editorPane, JideBoxLayout.PAGE_AXIS)); + itemsPane.add(editorPane, JideBoxLayout.FIX); + + return new CollapsibleItemListCreation() { + { + collapsiblePanel = itemsPane; + list = itemsList;} + }; + } + +} \ No newline at end of file From cf8c0497bc83e577f11a30331438fd7dab68989f Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 22:51:15 +0200 Subject: [PATCH 13/94] add navigation to getCollapsibleItemList --- .../ui/gamedataeditors/DialogueEditor.java | 7 ++- .../ui/gamedataeditors/DroplistEditor.java | 1 + .../utils/BasicLambdaWithArgAndReturn.java | 5 ++ .../rpg/atcontentstudio/utils/UiUtils.java | 55 +++++++++++-------- 4 files changed, 44 insertions(+), 24 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArgAndReturn.java diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index df317db..3480137 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -243,6 +243,7 @@ public class DialogueEditor extends JSONElementEditor { Dialogue.Reward::new, cellRendererRewards, titleRewards, + (x)->null, false ).collapsiblePanel; if (dialogue.rewards == null || dialogue.rewards.isEmpty()) { @@ -355,8 +356,9 @@ public class DialogueEditor extends JSONElementEditor { dialogue.writable, Dialogue.Reply::new, cellRendererReplies, - titleReplies - , true + titleReplies, + (x)->null, + true ).collapsiblePanel; if (dialogue.replies == null || dialogue.replies.isEmpty()) { replies.collapse(); @@ -706,6 +708,7 @@ public class DialogueEditor extends JSONElementEditor { Requirement::new, cellRendererRequirements, titleRequirements, + (x)-> x.required_obj, false ); CollapsiblePanel requirementsPane = itemsPane.collapsiblePanel; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java index d70f744..6e5fefe 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java @@ -73,6 +73,7 @@ public class DroplistEditor extends JSONElementEditor { DroppedItem::new, new DroppedItemsCellRenderer(), "Items in this droplist: ", + (x)-> x.item, false ).collapsiblePanel; if (droplist.dropped_items == null || droplist.dropped_items.isEmpty()) { diff --git a/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArgAndReturn.java b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArgAndReturn.java new file mode 100644 index 0000000..69b2d2c --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/utils/BasicLambdaWithArgAndReturn.java @@ -0,0 +1,5 @@ +package com.gpl.rpg.atcontentstudio.utils; + +public interface BasicLambdaWithArgAndReturn { + public R doIt(T arg); +} diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index 0ce7573..08f8b6f 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -29,6 +29,7 @@ public class UiUtils { Supplier tempSupplier, DefaultListCellRenderer cellRenderer, String title, + BasicLambdaWithArgAndReturn getReferencedObj, boolean withMoveButtons) { CollapsiblePanel itemsPane = new CollapsiblePanel(title); itemsPane.setLayout(new JideBoxLayout(itemsPane, JideBoxLayout.PAGE_AXIS)); @@ -109,28 +110,8 @@ public class UiUtils { listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); itemsPane.add(listButtonsPane, JideBoxLayout.FIX); } - //TODO: add double click to navigate to the item in the editor pane. - // TODO: figure out what ID is needed here -// itemsList.addMouseListener(new MouseAdapter() { -// @Override -// public void mouseClicked(MouseEvent e) { -// if (e.getClickCount() == 2) { -// if (itemsList.getSelectedValue() != null && ((E)itemsList.getSelectedValue()).required_obj != null) { -// ATContentStudio.frame.openEditor(((E)itemsList.getSelectedValue()).required_obj); -// ATContentStudio.frame.selectInTree(((E)itemsList.getSelectedValue()).required_obj); -// } -// } -// } -// }); -// itemsList.addKeyListener(new KeyAdapter() { -// @Override -// public void keyReleased(KeyEvent e) { -// if (e.getKeyCode() == KeyEvent.VK_ENTER) { -// ATContentStudio.frame.openEditor(((E)itemsList.getSelectedValue()).required_obj); -// ATContentStudio.frame.selectInTree(((E)itemsList.getSelectedValue()).required_obj); -// } -// } -// }); + + addNavigationListeners(getReferencedObj, itemsList); editorPane.setLayout(new JideBoxLayout(editorPane, JideBoxLayout.PAGE_AXIS)); itemsPane.add(editorPane, JideBoxLayout.FIX); @@ -142,4 +123,34 @@ public class UiUtils { }; } + private static void addNavigationListeners(BasicLambdaWithArgAndReturn getReferencedObj, JList itemsList) { + // Add listeners to the list for double-click and Enter key to open the editor + itemsList.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + E selectedValue = itemsList.getSelectedValue(); + if (selectedValue == null) return; + GameDataElement referencedObj = getReferencedObj.doIt(selectedValue); + if (referencedObj != null) { + ATContentStudio.frame.openEditor(referencedObj); + ATContentStudio.frame.selectInTree( referencedObj); + } + } + } + }); + itemsList.addKeyListener(new KeyAdapter() { + @Override + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + E selectedValue = itemsList.getSelectedValue(); + if (selectedValue == null) return; + GameDataElement referencedObj = getReferencedObj.doIt(selectedValue); + ATContentStudio.frame.openEditor(referencedObj); + ATContentStudio.frame.selectInTree(referencedObj); + } + } + }); + } + } \ No newline at end of file From cfb906736d18a64bbdbd2969cd8951de8c2d32e0 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 1 Jun 2025 22:51:32 +0200 Subject: [PATCH 14/94] extract into sub-methods --- .../rpg/atcontentstudio/utils/UiUtils.java | 79 ++++++++++--------- 1 file changed, 43 insertions(+), 36 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index 08f8b6f..05143df 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -1,6 +1,7 @@ package com.gpl.rpg.atcontentstudio.utils; import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; import com.gpl.rpg.atcontentstudio.ui.CustomListModel; @@ -68,44 +69,10 @@ public class UiUtils { JPanel listButtonsPane = new JPanel(); listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createBtn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - E tempItem = tempSupplier.get(); - itemsListModel.addItem(tempItem); - itemsList.setSelectedValue(tempItem, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - listButtonsPane.add(createBtn, JideBoxLayout.FIX); + addRemoveAndAddButtons(listener, itemsListModel, selectedItemReset, selectedItem, tempSupplier, createBtn, itemsList, listButtonsPane, deleteBtn); - deleteBtn.addActionListener(e -> { - if (selectedItem.doIt() != null) { - itemsListModel.removeItem(selectedItem.doIt()); - selectedItemReset.doIt(); - itemsList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - listButtonsPane.add(deleteBtn, JideBoxLayout.FIX); if(withMoveButtons) { - moveUpBtn.addActionListener(e -> { - if (selectedItem.doIt() != null) { - itemsListModel.moveUp(selectedItem.doIt()); - itemsList.setSelectedValue(selectedItem.doIt(), true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - listButtonsPane.add(moveUpBtn, JideBoxLayout.FIX); - - moveDownBtn.addActionListener(e -> { - if (selectedItem.doIt() != null) { - itemsListModel.moveDown(selectedItem.doIt()); - itemsList.setSelectedValue(selectedItem.doIt(), true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - listButtonsPane.add(moveDownBtn, JideBoxLayout.FIX); + addMoveButtonListeners(listener, itemsListModel, selectedItem, moveUpBtn, itemsList, listButtonsPane, moveDownBtn); } listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); itemsPane.add(listButtonsPane, JideBoxLayout.FIX); @@ -123,6 +90,46 @@ public class UiUtils { }; } + private static > void addRemoveAndAddButtons(FieldUpdateListener listener, M itemsListModel, BasicLambda selectedItemReset, BasicLambdaWithReturn selectedItem, Supplier tempSupplier, JButton createBtn, JList itemsList, JPanel listButtonsPane, JButton deleteBtn) { + createBtn.addActionListener(e -> { + E tempItem = tempSupplier.get(); + itemsListModel.addItem(tempItem); + itemsList.setSelectedValue(tempItem, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + }); + listButtonsPane.add(createBtn, JideBoxLayout.FIX); + + deleteBtn.addActionListener(e -> { + if (selectedItem.doIt() != null) { + itemsListModel.removeItem(selectedItem.doIt()); + selectedItemReset.doIt(); + itemsList.clearSelection(); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + listButtonsPane.add(deleteBtn, JideBoxLayout.FIX); + } + + private static > void addMoveButtonListeners(FieldUpdateListener listener, M itemsListModel, BasicLambdaWithReturn selectedItem, JButton moveUpBtn, JList itemsList, JPanel listButtonsPane, JButton moveDownBtn) { + moveUpBtn.addActionListener(e -> { + if (selectedItem.doIt() != null) { + itemsListModel.moveUp(selectedItem.doIt()); + itemsList.setSelectedValue(selectedItem.doIt(), true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + listButtonsPane.add(moveUpBtn, JideBoxLayout.FIX); + + moveDownBtn.addActionListener(e -> { + if (selectedItem.doIt() != null) { + itemsListModel.moveDown(selectedItem.doIt()); + itemsList.setSelectedValue(selectedItem.doIt(), true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + listButtonsPane.add(moveDownBtn, JideBoxLayout.FIX); + } + private static void addNavigationListeners(BasicLambdaWithArgAndReturn getReferencedObj, JList itemsList) { // Add listeners to the list for double-click and Enter key to open the editor itemsList.addMouseListener(new MouseAdapter() { From 333100b19b7afef87ddd800c1ebd4a3b90f47414 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 2 Jun 2025 21:15:56 +0200 Subject: [PATCH 15/94] add more ListModel to CustomListModel changes --- .../atcontentstudio/ui/CustomListModel.java | 3 + .../ui/gamedataeditors/ItemEditor.java | 190 ++---------------- .../ui/gamedataeditors/NPCEditor.java | 122 ++--------- .../ui/gamedataeditors/QuestEditor.java | 85 +------- .../atcontentstudio/ui/map/TMXMapEditor.java | 58 +----- 5 files changed, 53 insertions(+), 405 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java index 90dff18..3754fa3 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java @@ -29,6 +29,7 @@ public abstract class CustomListModel implements ListModel { return getItems().get(index); } + public void addObject(E item) {addItem(item);} public void addItem(E item) { if (getItems() == null) { setItems(new ArrayList()); @@ -40,6 +41,7 @@ public abstract class CustomListModel implements ListModel { } } + public void removeObject(E item) {removeItem(item);} public void removeItem(E item) { int index = getItems().indexOf(item); getItems().remove(item); @@ -69,6 +71,7 @@ public abstract class CustomListModel implements ListModel { } } + public void objectChanged(E item) {itemChanged(item);} public void itemChanged(E item) { int index = getItems().indexOf(item); for (ListDataListener l : listeners) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index e84ca30..6beab6d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -31,16 +31,9 @@ import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Common; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; -import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; +import com.gpl.rpg.atcontentstudio.ui.*; import com.jidesoft.swing.JideBoxLayout; public class ItemEditor extends JSONElementEditor { @@ -1185,127 +1178,34 @@ public class ItemEditor extends JSONElementEditor { } - public static class SourceTimedConditionsListModel implements ListModel { - - Common.DeathEffect source; - + public static class SourceTimedConditionsListModel extends CustomListModel { public SourceTimedConditionsListModel(Common.DeathEffect effect) { - this.source = effect;; + super(effect);; + } + @Override + protected List getItems() { + return source.conditions_source; } @Override - public int getSize() { - if (source.conditions_source == null) return 0; - return source.conditions_source.size(); - } - - @Override - public Common.TimedConditionEffect getElementAt(int index) { - if (source.conditions_source == null) return null; - return source.conditions_source.get(index); - } - - public void addItem(Common.TimedConditionEffect item) { - if (source.conditions_source == null) { - source.conditions_source = new ArrayList(); - } - source.conditions_source.add(item); - int index = source.conditions_source.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Common.TimedConditionEffect item) { - int index = source.conditions_source.indexOf(item); - source.conditions_source.remove(item); - if (source.conditions_source.isEmpty()) { - source.conditions_source = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - public void itemChanged(Common.TimedConditionEffect item) { - int index = source.conditions_source.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.conditions_source = items; } } - public static class TargetTimedConditionsListModel implements ListModel { - - Common.HitEffect source; - + public static class TargetTimedConditionsListModel extends CustomListModel { public TargetTimedConditionsListModel(Common.HitEffect effect) { - this.source = effect;; + super(effect); } @Override - public int getSize() { - if (source.conditions_target == null) return 0; - return source.conditions_target.size(); - } - - @Override - public Common.TimedConditionEffect getElementAt(int index) { - if (source.conditions_target == null) return null; - return source.conditions_target.get(index); - } - - public void addItem(Common.TimedConditionEffect item) { - if (source.conditions_target == null) { - source.conditions_target = new ArrayList(); - } - source.conditions_target.add(item); - int index = source.conditions_target.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Common.TimedConditionEffect item) { - int index = source.conditions_target.indexOf(item); - source.conditions_target.remove(item); - if (source.conditions_target.isEmpty()) { - source.conditions_target = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } + protected List getItems() { + return source.conditions_target; } - public void itemChanged(Common.TimedConditionEffect item) { - int index = source.conditions_target.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.conditions_target = items; } } @@ -1343,65 +1243,19 @@ public class ItemEditor extends JSONElementEditor { } } - public static class ConditionsListModel implements ListModel { - - Item.EquipEffect source; - + public static class ConditionsListModel extends CustomListModel { public ConditionsListModel(Item.EquipEffect equipEffect) { - this.source = equipEffect; + super(equipEffect); } @Override - public int getSize() { - if (source.conditions == null) return 0; - return source.conditions.size(); - } - - @Override - public Common.ConditionEffect getElementAt(int index) { - if (source.conditions == null) return null; - return source.conditions.get(index); - } - - public void addItem(Common.ConditionEffect item) { - if (source.conditions == null) { - source.conditions = new ArrayList(); - } - source.conditions.add(item); - int index = source.conditions.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Common.ConditionEffect item) { - int index = source.conditions.indexOf(item); - source.conditions.remove(item); - if (source.conditions.isEmpty()) { - source.conditions = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } + protected List getItems() { + return source.conditions; } - public void itemChanged(Common.ConditionEffect item) { - int index = source.conditions.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List conditions) { + source.conditions = conditions; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index fba51e1..5fe32f3 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -34,11 +34,7 @@ import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; -import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; +import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; import com.jidesoft.swing.JideBoxLayout; @@ -1025,127 +1021,35 @@ public class NPCEditor extends JSONElementEditor { deathSourceConditionForever.setEnabled(!clear); } - public static class TargetTimedConditionsListModel implements ListModel { - - Common.HitEffect source; - + public static class TargetTimedConditionsListModel extends CustomListModel { public TargetTimedConditionsListModel(Common.HitEffect effect) { - this.source = effect; + super(effect); } @Override - public int getSize() { - if (source.conditions_target == null) return 0; - return source.conditions_target.size(); - } - - @Override - public Common.TimedConditionEffect getElementAt(int index) { - if (source.conditions_target == null) return null; - return source.conditions_target.get(index); + protected List getItems() { + return source.conditions_target; } - public void addItem(Common.TimedConditionEffect item) { - if (source.conditions_target == null) { - source.conditions_target = new ArrayList(); - } - source.conditions_target.add(item); - int index = source.conditions_target.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Common.TimedConditionEffect item) { - int index = source.conditions_target.indexOf(item); - source.conditions_target.remove(item); - if (source.conditions_target.isEmpty()) { - source.conditions_target = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - public void itemChanged(Common.TimedConditionEffect item) { - int index = source.conditions_target.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.conditions_target = items; } } - public static class SourceTimedConditionsListModel implements ListModel { - - Common.DeathEffect source; - + public static class SourceTimedConditionsListModel extends CustomListModel { public SourceTimedConditionsListModel(Common.DeathEffect effect) { - this.source = effect; + super(effect); } @Override - public int getSize() { - if (source.conditions_source == null) return 0; - return source.conditions_source.size(); - } - - @Override - public Common.TimedConditionEffect getElementAt(int index) { - if (source.conditions_source == null) return null; - return source.conditions_source.get(index); - } - - public void addItem(Common.TimedConditionEffect item) { - if (source.conditions_source == null) { - source.conditions_source = new ArrayList(); - } - source.conditions_source.add(item); - int index = source.conditions_source.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(Common.TimedConditionEffect item) { - int index = source.conditions_source.indexOf(item); - source.conditions_source.remove(item); - if (source.conditions_source.isEmpty()) { - source.conditions_source = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } + protected List getItems() { + return source.conditions_source; } - public void itemChanged(Common.TimedConditionEffect item) { - int index = source.conditions_source.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.conditions_source = items; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java index 39a0b73..1b62bea 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java @@ -28,12 +28,10 @@ import javax.swing.event.ListSelectionListener; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; +import com.gpl.rpg.atcontentstudio.model.gamedata.Common; import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; -import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; +import com.gpl.rpg.atcontentstudio.ui.*; import com.jidesoft.swing.JideBoxLayout; public class QuestEditor extends JSONElementEditor { @@ -183,88 +181,21 @@ public class QuestEditor extends JSONElementEditor { pane.revalidate(); pane.repaint(); } - - public static class StagesListModel implements ListModel { - Quest source; + public static class StagesListModel extends CustomListModel { public StagesListModel(Quest quest) { - this.source = quest; - } - - - @Override - public int getSize() { - if (source.stages == null) return 0; - return source.stages.size(); + super(quest); } @Override - public QuestStage getElementAt(int index) { - if (source.stages == null) return null; - return source.stages.get(index); - } - - public void addItem(QuestStage item) { - if (source.stages == null) { - source.stages = new ArrayList(); - } - source.stages.add(item); - int index = source.stages.indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeItem(QuestStage item) { - int index = source.stages.indexOf(item); - source.stages.remove(item); - if (source.stages.isEmpty()) { - source.stages = null; - } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - public void itemChanged(QuestStage item) { - int index = source.stages.indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - - public void moveUp(QuestStage item) { - int index = source.stages.indexOf(item); - QuestStage exchanged = source.stages.get(index - 1); - source.stages.set(index, exchanged); - source.stages.set(index - 1, item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index - 1, index)); - } - } - - public void moveDown(QuestStage item) { - int index = source.stages.indexOf(item); - QuestStage exchanged = source.stages.get(index + 1); - source.stages.set(index, exchanged); - source.stages.set(index + 1, item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index + 1)); - } - } - - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); + protected List getItems() { + return source.stages; } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.stages = items; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index aeae742..47e03d8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -62,6 +62,7 @@ import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; +import com.gpl.rpg.atcontentstudio.ui.*; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; @@ -95,13 +96,6 @@ import com.gpl.rpg.atcontentstudio.model.maps.SignArea; import com.gpl.rpg.atcontentstudio.model.maps.SpawnArea; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.BooleanBasedCheckBox; -import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.Editor; -import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; -import com.gpl.rpg.atcontentstudio.ui.ScrollablePanel; import com.gpl.rpg.atcontentstudio.utils.DesktopIntegration; import com.gpl.rpg.atcontentstudio.utils.FileUtils; import com.jidesoft.swing.JideBoxLayout; @@ -1286,58 +1280,20 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } } - public class MapObjectsListModel implements ListModel { - - public MapObjectGroup group; - + public class MapObjectsListModel extends CustomListModel { public MapObjectsListModel(MapObjectGroup group) { - this.group = group; - } - - @Override - public int getSize() { - return group.mapObjects.size(); + super(group); } @Override - public MapObject getElementAt(int index) { - return group.mapObjects.get(index); - } - - public void objectChanged(MapObject area) { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(groupObjectsList, ListDataEvent.CONTENTS_CHANGED, group.mapObjects.indexOf(area), group.mapObjects.indexOf(area))); - } - } - - public void addObject(MapObject area) { - group.mapObjects.add(area); - int index = group.mapObjects.indexOf(area); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(groupObjectsList, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeObject(MapObject area) { - int index = group.mapObjects.indexOf(area); - group.mapObjects.remove(area); - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(groupObjectsList, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); + protected List getItems() { + return source.mapObjects; } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.mapObjects = items; } - } public class GroupObjectsRenderer extends DefaultListCellRenderer { From d030e11019ae7e8286cf04031bcc6946b9fe8a79 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 16:22:50 +0200 Subject: [PATCH 16/94] change more ListModel implementations to CustomListModel --- .../model/maps/ReplaceArea.java | 22 +---- .../atcontentstudio/ui/map/TMXMapEditor.java | 91 ++++--------------- 2 files changed, 23 insertions(+), 90 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java index 20a9d4d..eaea296 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java @@ -65,26 +65,12 @@ public class ReplaceArea extends MapObject { public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { requirement.elementChanged(oldOne, newOne); } - - public ReplaceArea.Replacement addReplacement(String source, String target) { - Replacement repl = new Replacement(source, target); - addReplacement(repl); + + public ReplaceArea.Replacement createReplacement(String source, String target) { + Replacement repl = new Replacement(source, target); return repl; } - - public void addReplacement(ReplaceArea.Replacement repl) { - if (replacements == null) replacements = new ArrayList(); - replacements.add(repl); - } - -// public void removeReplacement(String source, String target) { -// replacedLayers.remove(source); -// } - - public void removeReplacement(Replacement repl) { - replacements.remove(repl); - } - + @Override public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { if (replacements != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index 47e03d8..d24adf3 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -1147,61 +1147,23 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } } - public class ReplacementsListModel implements ListModel { - - public ReplaceArea area; - + public class ReplacementsListModel extends CustomListModel { public ReplacementsListModel(ReplaceArea area) { - this.area = area; + super(area); } - @Override - public int getSize() { - if (area.replacements == null) return 0; - return area.replacements.size(); + protected List getItems() { + return source.replacements; } @Override - public ReplaceArea.Replacement getElementAt(int index) { - if (index < 0 || index > getSize()) return null; - if (area.replacements == null) return null; - return area.replacements.get(index); + protected void setItems(List items) { + source.replacements = items; } - - public void objectChanged(ReplaceArea.Replacement repl) { - int index = area.replacements.indexOf(repl); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } - } - public void addObject(String source, String target) { - ReplaceArea.Replacement repl = area.addReplacement(source, target); - int index = area.replacements.indexOf(repl); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } - } - - public void removeObject(ReplaceArea.Replacement repl) { - int index = area.replacements.indexOf(repl); - area.removeReplacement(repl); - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + ReplaceArea.Replacement repl = this.source.createReplacement(source, target); + addObject(repl); } } @@ -1308,37 +1270,22 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe return c; } } - - public class SpawnGroupNpcListModel implements ListModel { - - public SpawnArea area; - + + + public class SpawnGroupNpcListModel extends CustomListModel { public SpawnGroupNpcListModel(SpawnArea area) { - this.area = area; - } - - @Override - public int getSize() { - return area.spawnGroup.size(); + super(area); } @Override - public NPC getElementAt(int index) { - return area.spawnGroup.get(index); - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); + protected List getItems() { + return source.spawnGroup; } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + protected void setItems(List items) { + source.spawnGroup = items; } - } @@ -1588,13 +1535,13 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } public static class TMXMapSpritesheetsListModel implements ListModel { - + + TMXMap map; - + public TMXMapSpritesheetsListModel(TMXMap map) { this.map = map; } - @Override public int getSize() { return map.usedSpritesheets.size(); From fdcc4fab55fac9f1d95e4d9659d86608304f38cc Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 16:23:13 +0200 Subject: [PATCH 17/94] extract some code --- .../atcontentstudio/ui/CustomListModel.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java index 3754fa3..381e8ca 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java @@ -17,6 +17,13 @@ public abstract class CustomListModel implements ListModel { this.source = source; } + protected void notifyListeners(int event, int index0, int index1) { + for (ListDataListener l : listeners) { + l.intervalRemoved(new ListDataEvent(this, event, index0, index1)); + } + } + + @Override public int getSize() { if (getItems() == null) return 0; @@ -36,9 +43,7 @@ public abstract class CustomListModel implements ListModel { } getItems().add(item); int index = getItems().indexOf(item); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } + notifyListeners( ListDataEvent.INTERVAL_ADDED, index, index); } public void removeObject(E item) {removeItem(item);} @@ -48,11 +53,10 @@ public abstract class CustomListModel implements ListModel { if (getItems().isEmpty()) { setItems(null); } - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } + notifyListeners(ListDataEvent.INTERVAL_REMOVED, index, index); } + public void moveUp(E item) { moveUpOrDown(item, -1); } @@ -66,20 +70,16 @@ public abstract class CustomListModel implements ListModel { E exchanged = getItems().get(index + direction); getItems().set(index, exchanged); getItems().set(index + direction, item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index + direction, index)); - } + notifyListeners(ListDataEvent.CONTENTS_CHANGED, index + direction, index); } public void objectChanged(E item) {itemChanged(item);} public void itemChanged(E item) { int index = getItems().indexOf(item); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } + notifyListeners( ListDataEvent.CONTENTS_CHANGED, index, index); } - List listeners = new CopyOnWriteArrayList(); + private List listeners = new CopyOnWriteArrayList(); @Override public void addListDataListener(ListDataListener l) { From edd0160c9ddb6f69d02e8463173bfd27adfec3c0 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 17:00:04 +0200 Subject: [PATCH 18/94] extract some code into ListenerListModel interface --- .../atcontentstudio/ui/CustomListModel.java | 19 ++--------- .../atcontentstudio/ui/ListenerListModel.java | 27 +++++++++++++++ .../atcontentstudio/ui/NotificationsPane.java | 33 +++++++------------ 3 files changed, 42 insertions(+), 37 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java diff --git a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java index 381e8ca..db403c7 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java @@ -1,13 +1,12 @@ package com.gpl.rpg.atcontentstudio.ui; -import javax.swing.*; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -public abstract class CustomListModel implements ListModel { +public abstract class CustomListModel implements ListenerListModel { protected S source; protected abstract List getItems(); @@ -17,10 +16,8 @@ public abstract class CustomListModel implements ListModel { this.source = source; } - protected void notifyListeners(int event, int index0, int index1) { - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, event, index0, index1)); - } + public List getListeners() { + return listeners; } @@ -80,14 +77,4 @@ public abstract class CustomListModel implements ListModel { } private List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java new file mode 100644 index 0000000..7a6f5f6 --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java @@ -0,0 +1,27 @@ +package com.gpl.rpg.atcontentstudio.ui; + +import javax.swing.*; +import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; +import java.util.List; + +public interface ListenerListModel extends ListModel { + List getListeners(); + + default void notifyListeners(int event, int index0, int index1) { + notifyListeners(this, event, index0, index1); + } + default void notifyListeners(Object source, int event, int index0, int index1) { + for (ListDataListener l : getListeners()) { + l.intervalRemoved(new ListDataEvent(source, event, index0, index1)); + } + } + + default void addListDataListener(ListDataListener l) { + getListeners().add(l); + } + + default void removeListDataListener(ListDataListener l) { + getListeners().remove(l); + } +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java index 80436a5..c4194e3 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java @@ -14,7 +14,6 @@ import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; -import javax.swing.ListModel; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; @@ -62,15 +61,20 @@ public class NotificationsPane extends JList { }); Notification.addNotificationListener(model); } - - - private class MyListModel implements ListModel, NotificationListener { + + + private class MyListModel implements ListenerListModel, NotificationListener { @Override - public Object getElementAt(int index) { + public Notification getElementAt(int index) { return Notification.notifs.get(index); } - + + @Override + public List getListeners() { + return listeners; + } + @Override public int getSize() { return Notification.notifs.size(); @@ -78,28 +82,15 @@ public class NotificationsPane extends JList { @Override public void onNewNotification(Notification n) { - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(NotificationsPane.this, ListDataEvent.INTERVAL_ADDED, Notification.notifs.size() - 1 , Notification.notifs.size() - 1)); - } + notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_ADDED, Notification.notifs.size() - 1 , Notification.notifs.size() - 1); NotificationsPane.this.ensureIndexIsVisible(Notification.notifs.indexOf(n)); } @Override public void onListCleared(int i) { - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(NotificationsPane.this, ListDataEvent.INTERVAL_REMOVED, 0 , i)); - } + notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_REMOVED, 0 , i); } private List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - } } \ No newline at end of file From 6b049d3b7ba67ef8c4d05fb213f922eafe8e258f Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 17:38:16 +0200 Subject: [PATCH 19/94] rename CustomListModel to OrderedListenerListModel --- ...del.java => OrderedListenerListModel.java} | 4 +- .../ui/gamedataeditors/DialogueEditor.java | 12 +- .../ui/gamedataeditors/DroplistEditor.java | 4 +- .../ui/gamedataeditors/ItemEditor.java | 3920 ++++++++--------- .../ui/gamedataeditors/NPCEditor.java | 3224 +++++++------- .../ui/gamedataeditors/QuestEditor.java | 552 +-- .../atcontentstudio/ui/map/TMXMapEditor.java | 6 +- .../rpg/atcontentstudio/utils/UiUtils.java | 32 +- 8 files changed, 3875 insertions(+), 3879 deletions(-) rename src/com/gpl/rpg/atcontentstudio/ui/{CustomListModel.java => OrderedListenerListModel.java} (94%) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java similarity index 94% rename from src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java rename to src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java index db403c7..e4ceeee 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/CustomListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java @@ -6,13 +6,13 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -public abstract class CustomListModel implements ListenerListModel { +public abstract class OrderedListenerListModel implements ListenerListModel { protected S source; protected abstract List getItems(); protected abstract void setItems(List items); - public CustomListModel(S source) { + public OrderedListenerListModel(S source) { this.source = source; } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index 3480137..88e1c45 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -6,10 +6,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; @@ -44,7 +40,7 @@ import com.gpl.rpg.atcontentstudio.ui.BooleanBasedCheckBox; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.CustomListModel; +import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; import com.gpl.rpg.atcontentstudio.utils.UiUtils; @@ -867,7 +863,7 @@ public class DialogueEditor extends JSONElementEditor { } - public static class RewardsListModel extends CustomListModel { + public static class RewardsListModel extends OrderedListenerListModel { @Override protected List getItems() { return source.rewards; @@ -990,7 +986,7 @@ public class DialogueEditor extends JSONElementEditor { } - public static class RepliesListModel extends CustomListModel { + public static class RepliesListModel extends OrderedListenerListModel { @Override protected List getItems() { return source.replies; @@ -1056,7 +1052,7 @@ public class DialogueEditor extends JSONElementEditor { } } - public static class ReplyRequirementsListModel extends CustomListModel { + public static class ReplyRequirementsListModel extends OrderedListenerListModel { @Override protected List getItems() { return source.requirements; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java index 6e5fefe..e85d12c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java @@ -22,7 +22,7 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist.DroppedItem; import com.gpl.rpg.atcontentstudio.model.gamedata.Item; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.CustomListModel; +import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; @@ -101,7 +101,7 @@ public class DroplistEditor extends JSONElementEditor { pane.repaint(); } - public class DroppedItemsListModel extends CustomListModel { + public class DroppedItemsListModel extends OrderedListenerListModel { public DroppedItemsListModel(Droplist droplist) { super(droplist); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 6beab6d..49a23b6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -1,1960 +1,1960 @@ -package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTextField; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.*; -import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.*; -import com.jidesoft.swing.JideBoxLayout; - -public class ItemEditor extends JSONElementEditor { - - private static final long serialVersionUID = 7538154592029351986L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - - private static final String killLabel = "Effect on every kill: "; - private static final String useLabel = "Effect on use: "; - - - private Common.ConditionEffect selectedEquipEffectCondition; - private Common.TimedConditionEffect selectedHitEffectSourceCondition; - private Common.TimedConditionEffect selectedHitEffectTargetCondition; - private Common.TimedConditionEffect selectedKillEffectCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; - - - private JButton itemIcon; - private JTextField idField; - private JTextField nameField; - private JTextField descriptionField; - @SuppressWarnings("rawtypes") - private JComboBox typeBox; - private IntegerBasedCheckBox manualPriceBox; - private JSpinner baseCostField; - private MyComboBox categoryBox; - private Integer baseManualPrice = null; - - private CollapsiblePanel equipEffectPane; - private Item.EquipEffect equipEffect; - private JSpinner equipDmgMin; - private JSpinner equipDmgMax; - private JSpinner equipBoostHP; - private JSpinner equipBoostAP; - private JSpinner equipBoostAC; - private JSpinner equipBoostBC; - private JSpinner equipBoostCS; - private JSpinner equipSetCM; - private JSpinner equipSetDM; - private JSpinner equipBoostDR; - private JSpinner equipIncMoveCost; - private JSpinner equipIncUseCost; - private JSpinner equipIncReequipCost; - private JSpinner equipIncAttackCost; - private ConditionsListModel equipConditionsModel; - @SuppressWarnings("rawtypes") - private JList equipConditionsList; - private MyComboBox equipConditionBox; - private JRadioButton equipConditionWithMagnitude; - private JRadioButton equipConditionImmunity; - private JSpinner equipConditionMagnitude; - - private CollapsiblePanel hitEffectPane; - private Common.HitEffect hitEffect; - private JSpinner hitHPMin; - private JSpinner hitHPMax; - private JSpinner hitAPMin; - private JSpinner hitAPMax; - private SourceTimedConditionsListModel hitSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; - private MyComboBox hitSourceConditionBox; - private JSpinner hitSourceConditionChance; - private JRadioButton hitSourceConditionClear; - private JRadioButton hitSourceConditionApply; - private JRadioButton hitSourceConditionImmunity; - private JSpinner hitSourceConditionMagnitude; - private JRadioButton hitSourceConditionTimed; - private JRadioButton hitSourceConditionForever; - private JSpinner hitSourceConditionDuration; - private TargetTimedConditionsListModel hitTargetConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitTargetConditionsList; - private MyComboBox hitTargetConditionBox; - private JSpinner hitTargetConditionChance; - private JRadioButton hitTargetConditionClear; - private JRadioButton hitTargetConditionApply; - private JRadioButton hitTargetConditionImmunity; - private JSpinner hitTargetConditionMagnitude; - private JRadioButton hitTargetConditionTimed; - private JRadioButton hitTargetConditionForever; - private JSpinner hitTargetConditionDuration; - - private CollapsiblePanel killEffectPane; - private Common.DeathEffect killEffect; - private JSpinner killHPMin; - private JSpinner killHPMax; - private JSpinner killAPMin; - private JSpinner killAPMax; - private SourceTimedConditionsListModel killSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList killSourceConditionsList; - private MyComboBox killSourceConditionBox; - private JSpinner killSourceConditionChance; - private JRadioButton killSourceConditionClear; - private JRadioButton killSourceConditionApply; - private JRadioButton killSourceConditionImmunity; - private JSpinner killSourceConditionMagnitude; - private JRadioButton killSourceConditionTimed; - private JRadioButton killSourceConditionForever; - private JSpinner killSourceConditionDuration; - - private CollapsiblePanel hitReceivedEffectPane; - private Common.HitReceivedEffect hitReceivedEffect; - private JSpinner hitReceivedHPMin; - private JSpinner hitReceivedHPMax; - private JSpinner hitReceivedAPMin; - private JSpinner hitReceivedAPMax; - private JSpinner hitReceivedHPMinTarget; - private JSpinner hitReceivedHPMaxTarget; - private JSpinner hitReceivedAPMinTarget; - private JSpinner hitReceivedAPMaxTarget; - private SourceTimedConditionsListModel hitReceivedSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedSourceConditionsList; - private MyComboBox hitReceivedSourceConditionBox; - private JSpinner hitReceivedSourceConditionChance; - private JRadioButton hitReceivedSourceConditionClear; - private JRadioButton hitReceivedSourceConditionApply; - private JRadioButton hitReceivedSourceConditionImmunity; - private JSpinner hitReceivedSourceConditionMagnitude; - private JRadioButton hitReceivedSourceConditionTimed; - private JRadioButton hitReceivedSourceConditionForever; - private JSpinner hitReceivedSourceConditionDuration; - private TargetTimedConditionsListModel hitReceivedTargetConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedTargetConditionsList; - private MyComboBox hitReceivedTargetConditionBox; - private JSpinner hitReceivedTargetConditionChance; - private JRadioButton hitReceivedTargetConditionClear; - private JRadioButton hitReceivedTargetConditionApply; - private JRadioButton hitReceivedTargetConditionImmunity; - private JSpinner hitReceivedTargetConditionMagnitude; - private JRadioButton hitReceivedTargetConditionTimed; - private JRadioButton hitReceivedTargetConditionForever; - private JSpinner hitReceivedTargetConditionDuration; - - public ItemEditor(Item item) { - super(item, item.getDesc(), item.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void insertFormViewDataField(JPanel pane) { - - final Item item = (Item) target; - - final FieldUpdateListener listener = new ItemFieldUpdater(); - - itemIcon = createButtonPane(pane, item.getProject(), item, Item.class, item.getImage(), Spritesheet.Category.item, listener); - - idField = addTextField(pane, "Internal ID: ", item.id, item.writable, listener); - nameField = addTranslatableTextField(pane, "Display name: ", item.name, item.writable, listener); - descriptionField = addTranslatableTextField(pane, "Description: ", item.description, item.writable, listener); - typeBox = addEnumValueBox(pane, "Type: ", Item.DisplayType.values(), item.display_type, item.writable, listener); - manualPriceBox = addIntegerBasedCheckBox(pane, "Has manual price", item.has_manual_price, item.writable, listener); - baseManualPrice = item.base_market_cost; - baseCostField = addIntegerField(pane, "Base market cost: ", (item.has_manual_price != null && item.has_manual_price == 1) ? item.base_market_cost : item.computePrice(), false, item.writable, listener); - if (!manualPriceBox.isSelected()) { - baseCostField.setEnabled(false); - } - categoryBox = addItemCategoryBox(pane, item.getProject(), "Category: ", item.category, item.writable, listener); - - equipEffectPane = new CollapsiblePanel("Effect when equipped: "); - equipEffectPane.setLayout(new JideBoxLayout(equipEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.equip_effect == null) { - equipEffect = new Item.EquipEffect(); - } else { - equipEffect = item.equip_effect; - } - equipDmgMin = addIntegerField(equipEffectPane, "Attack Damage min: ", equipEffect.damage_boost_min, true, item.writable, listener); - equipDmgMax = addIntegerField(equipEffectPane, "Attack Damage max: ", equipEffect.damage_boost_max, true, item.writable, listener); - equipSetDM = addIntegerField(equipEffectPane, "Damage modifier %: ", equipEffect.damage_modifier, 100, false, item.writable, listener); - equipBoostHP = addIntegerField(equipEffectPane, "Boost max HP: ", equipEffect.max_hp_boost, true, item.writable, listener); - equipBoostAP = addIntegerField(equipEffectPane, "Boost max AP: ", equipEffect.max_ap_boost, true, item.writable, listener); - equipBoostAC = addIntegerField(equipEffectPane, "Boost attack chance: ", equipEffect.increase_attack_chance, true, item.writable, listener); - equipBoostBC = addIntegerField(equipEffectPane, "Boost block chance: ", equipEffect.increase_block_chance, true, item.writable, listener); - equipBoostCS = addIntegerField(equipEffectPane, "Boost critical skill: ", equipEffect.increase_critical_skill, true, item.writable, listener); - equipSetCM = addDoubleField(equipEffectPane, "Critical multiplier: ", equipEffect.critical_multiplier, item.writable, listener); - equipBoostDR = addIntegerField(equipEffectPane, "Boost damage resistance: ", equipEffect.increase_damage_resistance, true, item.writable, listener); - equipIncMoveCost = addIntegerField(equipEffectPane, "Increase move cost: ", equipEffect.increase_move_cost, true, item.writable, listener); - equipIncUseCost = addIntegerField(equipEffectPane, "Increase item use cost: ", equipEffect.increase_use_item_cost, true, item.writable, listener); - equipIncReequipCost = addIntegerField(equipEffectPane, "Increase reequip cost: ", equipEffect.increase_reequip_cost, true, item.writable, listener); - equipIncAttackCost = addIntegerField(equipEffectPane, "Increase attack cost: ", equipEffect.increase_attack_cost, true, item.writable, listener); - CollapsiblePanel equipConditionsPane = new CollapsiblePanel("Actor Conditions applied when equipped: "); - equipConditionsPane.setLayout(new JideBoxLayout(equipConditionsPane, JideBoxLayout.PAGE_AXIS)); - equipConditionsModel = new ConditionsListModel(equipEffect); - equipConditionsList = new JList(equipConditionsModel); - equipConditionsList.setCellRenderer(new ConditionsCellRenderer()); - equipConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - equipConditionsPane.add(new JScrollPane(equipConditionsList), JideBoxLayout.FIX); - final JPanel equipConditionsEditorPane = new JPanel(); - final JButton createEquipCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteEquipCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - equipConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedEquipEffectCondition = (Common.ConditionEffect) equipConditionsList.getSelectedValue(); - if (selectedEquipEffectCondition == null) { - deleteEquipCondition.setEnabled(false); - } else { - deleteEquipCondition.setEnabled(true); - } - updateEquipConditionEditorPane(equipConditionsEditorPane, selectedEquipEffectCondition, listener); - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createEquipCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.ConditionEffect condition = new Common.ConditionEffect(); - equipConditionsModel.addItem(condition); - equipConditionsList.setSelectedValue(condition, true); - listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteEquipCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedEquipEffectCondition != null) { - equipConditionsModel.removeItem(selectedEquipEffectCondition); - selectedEquipEffectCondition = null; - equipConditionsList.clearSelection(); - listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createEquipCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteEquipCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - equipConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - equipConditionsEditorPane.setLayout(new JideBoxLayout(equipConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - equipConditionsPane.add(equipConditionsEditorPane, JideBoxLayout.FIX); - if (item.equip_effect == null || item.equip_effect.conditions == null || item.equip_effect.conditions.isEmpty()) { - equipConditionsPane.collapse(); - } - equipEffectPane.add(equipConditionsPane, JideBoxLayout.FIX); - pane.add(equipEffectPane, JideBoxLayout.FIX); - if (item.equip_effect == null) { - equipEffectPane.collapse(); - } - - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = item.hit_effect; - } - hitHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, item.writable, listener); - hitHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, item.writable, listener); - hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); - hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); - final CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); - hitSourceConditionsList = new JList(hitSourceConditionsModel); - hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); - final JPanel sourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); - updateHitSourceTimedConditionEditorPane(sourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); - if (selectedHitEffectSourceCondition == null) { - deleteHitSourceCondition.setEnabled(false); - } else { - deleteHitSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitSourceConditionsModel.addItem(condition); - hitSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectSourceCondition != null) { - hitSourceConditionsModel.removeItem(selectedHitEffectSourceCondition); - selectedHitEffectSourceCondition = null; - hitSourceConditionsList.clearSelection(); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - sourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(sourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsPane.add(sourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_effect == null || item.hit_effect.conditions_source == null || item.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); - } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); - hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); - hitTargetConditionsList = new JList(hitTargetConditionsModel); - hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); - final JPanel targetTimedConditionsEditorPane = new JPanel(); - final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); - updateHitTargetTimedConditionEditorPane(targetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); - if (selectedHitEffectTargetCondition == null) { - deleteHitTargetCondition.setEnabled(false); - } else { - deleteHitTargetCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitTargetConditionsModel.addItem(condition); - hitTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectTargetCondition != null) { - hitTargetConditionsModel.removeItem(selectedHitEffectTargetCondition); - selectedHitEffectTargetCondition = null; - hitTargetConditionsList.clearSelection(); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - targetTimedConditionsEditorPane.setLayout(new JideBoxLayout(targetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsPane.add(targetTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_effect == null || item.hit_effect.conditions_target == null || item.hit_effect.conditions_target.isEmpty()) { - hitTargetConditionsPane.collapse(); - } - hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); - if (item.hit_effect == null) { - hitEffectPane.collapse(); - } - pane.add(hitEffectPane, JideBoxLayout.FIX); - - - - killEffectPane = new CollapsiblePanel(killLabel); - killEffectPane.setLayout(new JideBoxLayout(killEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.kill_effect == null) { - killEffect = new Common.DeathEffect(); - } else { - killEffect = item.kill_effect; - } - killHPMin = addIntegerField(killEffectPane, "HP bonus min: ", killEffect.hp_boost_min, true, item.writable, listener); - killHPMax = addIntegerField(killEffectPane, "HP bonus max: ", killEffect.hp_boost_max, true, item.writable, listener); - killAPMin = addIntegerField(killEffectPane, "AP bonus min: ", killEffect.ap_boost_min, true, item.writable, listener); - killAPMax = addIntegerField(killEffectPane, "AP bonus max: ", killEffect.ap_boost_max, true, item.writable, listener); - final CollapsiblePanel killSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - killSourceConditionsPane.setLayout(new JideBoxLayout(killSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); - killSourceConditionsList = new JList(killSourceConditionsModel); - killSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - killSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - killSourceConditionsPane.add(new JScrollPane(killSourceConditionsList), JideBoxLayout.FIX); - final JPanel killSourceTimedConditionsEditorPane = new JPanel(); - final JButton createKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - killSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedKillEffectCondition = (Common.TimedConditionEffect) killSourceConditionsList.getSelectedValue(); - updateKillSourceTimedConditionEditorPane(killSourceTimedConditionsEditorPane, selectedKillEffectCondition, listener); - if (selectedKillEffectCondition == null) { - deleteKillSourceCondition.setEnabled(false); - } else { - deleteKillSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createKillSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - killSourceConditionsModel.addItem(condition); - killSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteKillSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedKillEffectCondition != null) { - killSourceConditionsModel.removeItem(selectedKillEffectCondition); - selectedKillEffectCondition = null; - killSourceConditionsList.clearSelection(); - listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createKillSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteKillSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - killSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - killSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(killSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - killSourceConditionsPane.add(killSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.kill_effect == null || item.kill_effect.conditions_source == null || item.kill_effect.conditions_source.isEmpty()) { - killSourceConditionsPane.collapse(); - } - killEffectPane.add(killSourceConditionsPane, JideBoxLayout.FIX); - if (item.kill_effect == null) { - killEffectPane.collapse(); - } - pane.add(killEffectPane, JideBoxLayout.FIX); - - - hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); - hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.hit_received_effect == null) { - hitReceivedEffect = new Common.HitReceivedEffect(); - } else { - hitReceivedEffect = item.hit_received_effect; - } - hitReceivedHPMin = addIntegerField(hitReceivedEffectPane, "Player HP bonus min: ", hitReceivedEffect.hp_boost_min, true, item.writable, listener); - hitReceivedHPMax = addIntegerField(hitReceivedEffectPane, "Player HP bonus max: ", hitReceivedEffect.hp_boost_max, true, item.writable, listener); - hitReceivedAPMin = addIntegerField(hitReceivedEffectPane, "Player AP bonus min: ", hitReceivedEffect.ap_boost_min, true, item.writable, listener); - hitReceivedAPMax = addIntegerField(hitReceivedEffectPane, "Player AP bonus max: ", hitReceivedEffect.ap_boost_max, true, item.writable, listener); - hitReceivedHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, item.writable, listener); - hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, item.writable, listener); - hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, item.writable, listener); - hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, item.writable, listener); - final CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the player: "); - hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(hitReceivedEffect); - hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsModel); - hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); - updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); - if (selectedHitReceivedEffectSourceCondition == null) { - deleteHitReceivedSourceCondition.setEnabled(false); - } else { - deleteHitReceivedSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedSourceConditionsModel.addItem(condition); - hitReceivedSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectSourceCondition != null) { - hitReceivedSourceConditionsModel.removeItem(selectedHitReceivedEffectSourceCondition); - selectedHitReceivedEffectSourceCondition = null; - hitReceivedSourceConditionsList.clearSelection(); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_received_effect == null || item.hit_received_effect.conditions_source == null || item.hit_received_effect.conditions_source.isEmpty()) { - hitReceivedSourceConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); - hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); - hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsModel); - hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); - updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); - if (selectedHitReceivedEffectTargetCondition == null) { - deleteHitReceivedTargetCondition.setEnabled(false); - } else { - deleteHitReceivedTargetCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedTargetConditionsModel.addItem(condition); - hitReceivedTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectTargetCondition != null) { - hitReceivedTargetConditionsModel.removeItem(selectedHitReceivedEffectTargetCondition); - selectedHitReceivedEffectTargetCondition = null; - hitReceivedTargetConditionsList.clearSelection(); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_received_effect == null || item.hit_received_effect.conditions_target == null || item.hit_received_effect.conditions_target.isEmpty()) { - hitReceivedTargetConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); - if (item.hit_received_effect == null) { - hitReceivedEffectPane.collapse(); - } - pane.add(hitReceivedEffectPane, JideBoxLayout.FIX); - - - if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { - equipEffectPane.setVisible(false); - hitEffectPane.setVisible(false); - killEffectPane.setVisible(false); - } else if (item.category.action_type == ItemCategory.ActionType.use) { - equipEffectPane.setVisible(false); - hitEffectPane.setVisible(false); - killEffectPane.setVisible(true); - killEffectPane.setTitle(useLabel); - killEffectPane.revalidate(); - killEffectPane.repaint(); - } else if (item.category.action_type == ItemCategory.ActionType.equip) { - equipEffectPane.setVisible(true); - hitEffectPane.setVisible(true); - killEffectPane.setVisible(true); - killEffectPane.setTitle(killLabel); - killEffectPane.revalidate(); - killEffectPane.repaint(); - } - - } - - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitSourceConditionBox != null) { - removeElementListener(hitSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); - - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); - - updateHitSourceTimedConditionWidgets(condition); - - hitSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); - } - }); - hitSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); - } - }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); - } - }); - - hitSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); - } - }); - hitSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); - - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); - } - - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitTargetConditionBox != null) { - removeElementListener(hitTargetConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitTargetConditionClear, JideBoxLayout.FIX); - hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitTargetConditionApply); - radioEffectGroup.add(hitTargetConditionClear); - radioEffectGroup.add(hitTargetConditionImmunity); - - hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitTargetConditionTimed); - radioDurationGroup.add(hitTargetConditionForever); - - updateHitTargetTimedConditionWidgets(condition); - - hitTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); - } - }); - hitTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); - } - }); - hitTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); - } - }); - - hitTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); - } - }); - hitTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitTargetConditionClear.setSelected(clear); - hitTargetConditionApply.setSelected(!clear && !immunity); - hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitTargetConditionImmunity.setSelected(immunity); - - hitTargetConditionTimed.setSelected(!forever); - hitTargetConditionTimed.setEnabled(!clear); - hitTargetConditionDuration.setEnabled(!clear && !forever); - hitTargetConditionForever.setSelected(forever); - hitTargetConditionForever.setEnabled(!clear); - } - - public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (killSourceConditionBox != null) { - removeElementListener(killSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - killSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - killSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - killSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(killSourceConditionClear, JideBoxLayout.FIX); - killSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(killSourceConditionApply, JideBoxLayout.FIX); - killSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - killSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(killSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(killSourceConditionApply); - radioEffectGroup.add(killSourceConditionClear); - radioEffectGroup.add(killSourceConditionImmunity); - - killSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(killSourceConditionTimed, JideBoxLayout.FIX); - killSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - killSourceConditionForever = new JRadioButton("Forever"); - pane.add(killSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(killSourceConditionTimed); - radioDurationGroup.add(killSourceConditionForever); - - updateKillSourceTimedConditionWidgets(condition); - - killSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionClear, new Boolean(killSourceConditionClear.isSelected())); - } - }); - killSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionApply, new Boolean(killSourceConditionApply.isSelected())); - } - }); - killSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionImmunity, new Boolean(killSourceConditionImmunity.isSelected())); - } - }); - - killSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionTimed, new Boolean(killSourceConditionTimed.isSelected())); - } - }); - killSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionForever, new Boolean(killSourceConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateKillSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - killSourceConditionClear.setSelected(clear); - killSourceConditionApply.setSelected(!clear && !immunity); - killSourceConditionMagnitude.setEnabled(!clear && !immunity); - killSourceConditionImmunity.setSelected(immunity); - - killSourceConditionTimed.setSelected(!forever); - killSourceConditionTimed.setEnabled(!clear); - killSourceConditionDuration.setEnabled(!clear && !forever); - killSourceConditionForever.setSelected(forever); - killSourceConditionForever.setEnabled(!clear); - } - - public void updateEquipConditionEditorPane(JPanel pane, Common.ConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (equipConditionBox != null) { - removeElementListener(equipConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - equipConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - equipConditionWithMagnitude = new JRadioButton("Apply condition with magnitude."); - pane.add(equipConditionWithMagnitude, JideBoxLayout.FIX); - equipConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude, 1, false, writable, listener); - equipConditionImmunity = new JRadioButton("Give immunity to condition."); - pane.add(equipConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(equipConditionWithMagnitude); - radioEffectGroup.add(equipConditionImmunity); - - boolean immunity = condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR; - equipConditionImmunity.setSelected(immunity); - equipConditionWithMagnitude.setSelected(!immunity); - equipConditionMagnitude.setEnabled(!immunity); - - equipConditionWithMagnitude.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(equipConditionWithMagnitude, new Boolean(equipConditionWithMagnitude.isSelected())); - } - }); - equipConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(equipConditionImmunity, new Boolean(equipConditionImmunity.isSelected())); - } - }); - - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedSourceConditionBox != null) { - removeElementListener(hitReceivedSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); - hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); - hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedSourceConditionApply); - radioEffectGroup.add(hitReceivedSourceConditionClear); - radioEffectGroup.add(hitReceivedSourceConditionImmunity); - - hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); - hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedSourceConditionTimed); - radioDurationGroup.add(hitReceivedSourceConditionForever); - - updateHitReceivedSourceTimedConditionWidgets(condition); - - hitReceivedSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); - } - }); - hitReceivedSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); - } - }); - hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); - } - }); - - hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); - } - }); - hitReceivedSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedSourceConditionClear.setSelected(clear); - hitReceivedSourceConditionApply.setSelected(!clear && !immunity); - hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedSourceConditionImmunity.setSelected(immunity); - - hitReceivedSourceConditionTimed.setSelected(!forever); - hitReceivedSourceConditionTimed.setEnabled(!clear); - hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); - hitReceivedSourceConditionForever.setSelected(forever); - hitReceivedSourceConditionForever.setEnabled(!clear); - } - - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedTargetConditionBox != null) { - removeElementListener(hitReceivedTargetConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); - hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); - hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedTargetConditionApply); - radioEffectGroup.add(hitReceivedTargetConditionClear); - radioEffectGroup.add(hitReceivedTargetConditionImmunity); - - hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); - hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedTargetConditionTimed); - radioDurationGroup.add(hitReceivedTargetConditionForever); - - updateHitReceivedTargetTimedConditionWidgets(condition); - - hitReceivedTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); - } - }); - hitReceivedTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); - } - }); - hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); - } - }); - - hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); - } - }); - hitReceivedTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedTargetConditionClear.setSelected(clear); - hitReceivedTargetConditionApply.setSelected(!clear && !immunity); - hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedTargetConditionImmunity.setSelected(immunity); - - hitReceivedTargetConditionTimed.setSelected(!forever); - hitReceivedTargetConditionTimed.setEnabled(!clear); - hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); - hitReceivedTargetConditionForever.setSelected(forever); - hitReceivedTargetConditionForever.setEnabled(!clear); - } - - - public static class SourceTimedConditionsListModel extends CustomListModel { - public SourceTimedConditionsListModel(Common.DeathEffect effect) { - super(effect);; - } - @Override - protected List getItems() { - return source.conditions_source; - } - - @Override - protected void setItems(List items) { - source.conditions_source = items; - } - } - - public static class TargetTimedConditionsListModel extends CustomListModel { - public TargetTimedConditionsListModel(Common.HitEffect effect) { - super(effect); - } - - @Override - protected List getItems() { - return source.conditions_target; - } - - @Override - protected void setItems(List items) { - source.conditions_target = items; - } - } - - public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; - - if (effect.condition != null) { - - boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); - boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); - boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; - - if (clear) { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to clear actor condition "+effect.condition.getDesc()); - } else if (immunity) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText(effect.chance+"% chances to give immunity to "+effect.condition.getDesc()+(forever ? " forever" : " for "+effect.duration+" rounds")); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude+(forever ? " forever" : " for "+effect.duration+" rounds")); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - - public static class ConditionsListModel extends CustomListModel { - public ConditionsListModel(Item.EquipEffect equipEffect) { - super(equipEffect); - } - - @Override - protected List getItems() { - return source.conditions; - } - - @Override - protected void setItems(List conditions) { - source.conditions = conditions; - } - } - - public static class ConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Common.ConditionEffect effect = (Common.ConditionEffect) value; - - if (effect.condition != null) { - if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText("Immune to actor condition "+effect.condition.getDesc()); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText("Give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - - public static boolean isNull(Item.EquipEffect effect) { - if (effect.conditions != null) return false; - if (effect.critical_multiplier != null) return false; - if (effect.damage_modifier != null) return false; - if (effect.damage_boost_max != null) return false; - if (effect.damage_boost_min != null) return false; - if (effect.increase_attack_chance != null) return false; - if (effect.increase_attack_cost != null) return false; - if (effect.increase_block_chance != null) return false; - if (effect.increase_critical_skill != null) return false; - if (effect.increase_damage_resistance != null) return false; - if (effect.increase_move_cost != null) return false; - if (effect.increase_reequip_cost != null) return false; - if (effect.increase_use_item_cost != null) return false; - if (effect.max_ap_boost != null) return false; - if (effect.max_hp_boost != null) return false; - return true; - } - - - public static boolean isNull(Common.HitEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - - public static boolean isNull(Common.DeathEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - return true; - } - - public static boolean isNull(Common.HitReceivedEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.ap_boost_min_target != null) return false; - if (effect.ap_boost_max_target != null) return false; - if (effect.hp_boost_min_target != null) return false; - if (effect.hp_boost_max_target != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - - public class ItemFieldUpdater implements FieldUpdateListener { - - @Override - public void valueChanged(JComponent source, Object value) { - Item item = (Item)target; - boolean updatePrice, updateEquip, updateHit, updateKill, updateHitReceived; - updatePrice = updateEquip = updateHit = updateKill = updateHitReceived = false; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - item.id = (String) value; - ItemEditor.this.name = item.getDesc(); - item.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - item.name = (String) value; - ItemEditor.this.name = item.getDesc(); - item.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemEditor.this); - } else if (source == itemIcon) { - item.icon_id = (String) value; - item.childrenChanged(new ArrayList()); - ItemEditor.this.icon = new ImageIcon(item.getProject().getIcon((String) value)); - ATContentStudio.frame.editorChanged(ItemEditor.this); - itemIcon.setIcon(new ImageIcon(item.getProject().getImage((String) value))); - itemIcon.revalidate(); - itemIcon.repaint(); - } else if (source == descriptionField) { - item.description = descriptionField.getText(); - } else if (source == typeBox) { - item.display_type = (Item.DisplayType) value; - } else if (source == manualPriceBox) { - item.has_manual_price = (Integer) value; - if (!manualPriceBox.isSelected()) { - baseCostField.setEnabled(false); - updatePrice = true; - } else { - baseCostField.setEnabled(true); - if (baseManualPrice != null) { - baseCostField.setValue(baseManualPrice); - } - } - } else if (source == baseCostField) { - if (manualPriceBox.isSelected()) { - item.base_market_cost = (Integer) value; - baseManualPrice = item.base_market_cost; - } - } else if (source == categoryBox) { - if (item.category != null) { - item.category.removeBacklink(item); - } - item.category = (ItemCategory) value; - if (item.category != null) { - item.category_id = item.category.id; - item.category.addBacklink(item); - } else { - item.category_id = null; - } - if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { - equipEffectPane.setVisible(false); - item.equip_effect = null; - hitEffectPane.setVisible(false); - item.hit_effect = null; - killEffectPane.setVisible(false); - item.kill_effect = null; - hitReceivedEffectPane.setVisible(false); - item.hit_received_effect = null; - ItemEditor.this.revalidate(); - ItemEditor.this.repaint(); - } else if (item.category.action_type == ItemCategory.ActionType.use) { - equipEffectPane.setVisible(false); - item.equip_effect = null; - hitEffectPane.setVisible(false); - item.hit_effect = null; - killEffectPane.setVisible(true); - updateKill = true; - hitReceivedEffectPane.setVisible(false); - item.hit_received_effect = null; - killEffectPane.setTitle(useLabel); - ItemEditor.this.revalidate(); - ItemEditor.this.repaint(); - } else if (item.category.action_type == ItemCategory.ActionType.equip) { - equipEffectPane.setVisible(true); - updateEquip = true; - hitEffectPane.setVisible(true); - updateEquip = true; - killEffectPane.setVisible(true); - updateKill = true; - hitReceivedEffectPane.setVisible(true); - updateEquip = true; - killEffectPane.setTitle(killLabel); - ItemEditor.this.revalidate(); - ItemEditor.this.repaint(); - } - updatePrice = true; - } else if (source == equipDmgMin) { - equipEffect.damage_boost_min = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipDmgMax) { - equipEffect.damage_boost_max = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostHP) { - equipEffect.max_hp_boost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostAP) { - equipEffect.max_ap_boost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostAC) { - equipEffect.increase_attack_chance = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostBC) { - equipEffect.increase_block_chance = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostCS) { - equipEffect.increase_critical_skill = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipSetCM) { - equipEffect.critical_multiplier = (Double) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipSetDM) { - equipEffect.damage_modifier = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostDR) { - equipEffect.increase_damage_resistance = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncMoveCost) { - equipEffect.increase_move_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncUseCost) { - equipEffect.increase_use_item_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncReequipCost) { - equipEffect.increase_reequip_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncAttackCost) { - equipEffect.increase_attack_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipConditionsList) { - updateEquip = true; - } else if (source == equipConditionBox) { - if (selectedEquipEffectCondition.condition != null) { - selectedEquipEffectCondition.condition.removeBacklink(item); - } - selectedEquipEffectCondition.condition = (ActorCondition) value; - if (selectedEquipEffectCondition.condition != null) { - selectedEquipEffectCondition.condition_id = selectedEquipEffectCondition.condition.id; - selectedEquipEffectCondition.condition.addBacklink(item); - } else { - selectedEquipEffectCondition.condition_id = null; - } - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == equipConditionMagnitude) { - selectedEquipEffectCondition.magnitude = (Integer) value; - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == equipConditionImmunity && (Boolean) value) { - selectedEquipEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - equipConditionMagnitude.setEnabled(false); - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == equipConditionWithMagnitude && (Boolean) value) { - selectedEquipEffectCondition.magnitude = (Integer) equipConditionMagnitude.getValue(); - equipConditionMagnitude.setEnabled(true); - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == hitHPMin) { - hitEffect.hp_boost_min = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitHPMax) { - hitEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitAPMin) { - hitEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitAPMax) { - hitEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitSourceConditionsList) { - updateHit = true; - } else if (source == hitSourceConditionBox) { - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.removeBacklink(item); - } - selectedHitEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; - selectedHitEffectSourceCondition.condition.addBacklink(item); - } else { - selectedHitEffectSourceCondition.condition_id = null; - } - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionClear && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionApply && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionImmunity && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionMagnitude) { - selectedHitEffectSourceCondition.magnitude = (Integer) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionTimed && (Boolean) value) { - selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionForever && (Boolean) value) { - selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionDuration) { - selectedHitEffectSourceCondition.duration = (Integer) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionChance) { - selectedHitEffectSourceCondition.chance = (Double) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitTargetConditionsList) { - updateHit = true; - } else if (source == hitTargetConditionBox) { - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition.removeBacklink(item); - } - selectedHitEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; - selectedHitEffectTargetCondition.condition.addBacklink(item); - } else { - selectedHitEffectTargetCondition.condition_id = null; - } - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionClear && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionApply && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionImmunity && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionMagnitude) { - selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionTimed && (Boolean) value) { - selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionForever && (Boolean) value) { - selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionDuration) { - selectedHitEffectTargetCondition.duration = (Integer) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionChance) { - selectedHitEffectTargetCondition.chance = (Double) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == killHPMin) { - killEffect.hp_boost_min = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killHPMax) { - killEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killAPMin) { - killEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killAPMax) { - killEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killSourceConditionsList) { - updateKill = true; - } else if (source == killSourceConditionBox) { - if (selectedKillEffectCondition.condition != null) { - selectedKillEffectCondition.condition.removeBacklink(item); - } - selectedKillEffectCondition.condition = (ActorCondition) value; - if (selectedKillEffectCondition.condition != null) { - selectedKillEffectCondition.condition_id = selectedKillEffectCondition.condition.id; - selectedKillEffectCondition.condition.addBacklink(item); - } else { - selectedKillEffectCondition.condition_id = null; - } - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionClear && (Boolean) value) { - selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedKillEffectCondition.duration = null; - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionApply && (Boolean) value) { - selectedKillEffectCondition.magnitude = (Integer) killSourceConditionMagnitude.getValue(); - selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionImmunity && (Boolean) value) { - selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionMagnitude) { - selectedKillEffectCondition.magnitude = (Integer) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionTimed && (Boolean) value) { - selectedKillEffectCondition.duration = (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionForever && (Boolean) value) { - selectedKillEffectCondition.duration = ActorCondition.DURATION_FOREVER; - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionDuration) { - selectedKillEffectCondition.duration = (Integer) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionChance) { - selectedKillEffectCondition.chance = (Double) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == hitReceivedHPMin) { - hitReceivedEffect.hp_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMax) { - hitReceivedEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMin) { - hitReceivedEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMax) { - hitReceivedEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMinTarget) { - hitReceivedEffect.hp_boost_min_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMaxTarget) { - hitReceivedEffect.hp_boost_max_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMinTarget) { - hitReceivedEffect.ap_boost_min_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMaxTarget) { - hitReceivedEffect.ap_boost_max_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionBox) { - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.removeBacklink(item); - } - selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; - selectedHitReceivedEffectSourceCondition.condition.addBacklink(item); - } else { - selectedHitReceivedEffectSourceCondition.condition_id = null; - } - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = null; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionMagnitude) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionDuration) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionChance) { - selectedHitReceivedEffectSourceCondition.chance = (Double) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionBox) { - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition.removeBacklink(item); - } - selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; - selectedHitReceivedEffectTargetCondition.condition.addBacklink(item); - } else { - selectedHitReceivedEffectTargetCondition.condition_id = null; - } - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = null; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionMagnitude) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionDuration) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionChance) { - selectedHitReceivedEffectTargetCondition.chance = (Double) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } - - if (updateEquip) { - if (isNull(equipEffect)) { - item.equip_effect = null; - } else { - item.equip_effect = equipEffect; - } - } - if (updateHit) { - if (isNull(hitEffect)) { - item.hit_effect = null; - } else { - item.hit_effect = hitEffect; - } - } - if (updateKill) { - if (isNull(killEffect)) { - item.kill_effect = null; - } else { - item.kill_effect = killEffect; - } - } - if (updateHitReceived) { - if (isNull(hitReceivedEffect)) { - item.hit_received_effect = null; - } else { - item.hit_received_effect = hitReceivedEffect; - } - } - if (updatePrice && !manualPriceBox.isSelected()) { - baseCostField.setValue(item.computePrice()); - } - - - if (item.state != GameDataElement.State.modified) { - item.state = GameDataElement.State.modified; - ItemEditor.this.name = item.getDesc(); - item.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemEditor.this); - } - updateJsonViewText(item.toJsonString()); - - } - - } - -} +package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; + +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import javax.swing.ButtonGroup; +import javax.swing.DefaultListCellRenderer; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTextField; +import javax.swing.ListModel; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; +import com.gpl.rpg.atcontentstudio.ui.*; +import com.jidesoft.swing.JideBoxLayout; + +public class ItemEditor extends JSONElementEditor { + + private static final long serialVersionUID = 7538154592029351986L; + + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; + + private static final String killLabel = "Effect on every kill: "; + private static final String useLabel = "Effect on use: "; + + + private Common.ConditionEffect selectedEquipEffectCondition; + private Common.TimedConditionEffect selectedHitEffectSourceCondition; + private Common.TimedConditionEffect selectedHitEffectTargetCondition; + private Common.TimedConditionEffect selectedKillEffectCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; + + + private JButton itemIcon; + private JTextField idField; + private JTextField nameField; + private JTextField descriptionField; + @SuppressWarnings("rawtypes") + private JComboBox typeBox; + private IntegerBasedCheckBox manualPriceBox; + private JSpinner baseCostField; + private MyComboBox categoryBox; + private Integer baseManualPrice = null; + + private CollapsiblePanel equipEffectPane; + private Item.EquipEffect equipEffect; + private JSpinner equipDmgMin; + private JSpinner equipDmgMax; + private JSpinner equipBoostHP; + private JSpinner equipBoostAP; + private JSpinner equipBoostAC; + private JSpinner equipBoostBC; + private JSpinner equipBoostCS; + private JSpinner equipSetCM; + private JSpinner equipSetDM; + private JSpinner equipBoostDR; + private JSpinner equipIncMoveCost; + private JSpinner equipIncUseCost; + private JSpinner equipIncReequipCost; + private JSpinner equipIncAttackCost; + private ConditionsListModel equipConditionsModel; + @SuppressWarnings("rawtypes") + private JList equipConditionsList; + private MyComboBox equipConditionBox; + private JRadioButton equipConditionWithMagnitude; + private JRadioButton equipConditionImmunity; + private JSpinner equipConditionMagnitude; + + private CollapsiblePanel hitEffectPane; + private Common.HitEffect hitEffect; + private JSpinner hitHPMin; + private JSpinner hitHPMax; + private JSpinner hitAPMin; + private JSpinner hitAPMax; + private SourceTimedConditionsListModel hitSourceConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitSourceConditionsList; + private MyComboBox hitSourceConditionBox; + private JSpinner hitSourceConditionChance; + private JRadioButton hitSourceConditionClear; + private JRadioButton hitSourceConditionApply; + private JRadioButton hitSourceConditionImmunity; + private JSpinner hitSourceConditionMagnitude; + private JRadioButton hitSourceConditionTimed; + private JRadioButton hitSourceConditionForever; + private JSpinner hitSourceConditionDuration; + private TargetTimedConditionsListModel hitTargetConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitTargetConditionsList; + private MyComboBox hitTargetConditionBox; + private JSpinner hitTargetConditionChance; + private JRadioButton hitTargetConditionClear; + private JRadioButton hitTargetConditionApply; + private JRadioButton hitTargetConditionImmunity; + private JSpinner hitTargetConditionMagnitude; + private JRadioButton hitTargetConditionTimed; + private JRadioButton hitTargetConditionForever; + private JSpinner hitTargetConditionDuration; + + private CollapsiblePanel killEffectPane; + private Common.DeathEffect killEffect; + private JSpinner killHPMin; + private JSpinner killHPMax; + private JSpinner killAPMin; + private JSpinner killAPMax; + private SourceTimedConditionsListModel killSourceConditionsModel; + @SuppressWarnings("rawtypes") + private JList killSourceConditionsList; + private MyComboBox killSourceConditionBox; + private JSpinner killSourceConditionChance; + private JRadioButton killSourceConditionClear; + private JRadioButton killSourceConditionApply; + private JRadioButton killSourceConditionImmunity; + private JSpinner killSourceConditionMagnitude; + private JRadioButton killSourceConditionTimed; + private JRadioButton killSourceConditionForever; + private JSpinner killSourceConditionDuration; + + private CollapsiblePanel hitReceivedEffectPane; + private Common.HitReceivedEffect hitReceivedEffect; + private JSpinner hitReceivedHPMin; + private JSpinner hitReceivedHPMax; + private JSpinner hitReceivedAPMin; + private JSpinner hitReceivedAPMax; + private JSpinner hitReceivedHPMinTarget; + private JSpinner hitReceivedHPMaxTarget; + private JSpinner hitReceivedAPMinTarget; + private JSpinner hitReceivedAPMaxTarget; + private SourceTimedConditionsListModel hitReceivedSourceConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedSourceConditionsList; + private MyComboBox hitReceivedSourceConditionBox; + private JSpinner hitReceivedSourceConditionChance; + private JRadioButton hitReceivedSourceConditionClear; + private JRadioButton hitReceivedSourceConditionApply; + private JRadioButton hitReceivedSourceConditionImmunity; + private JSpinner hitReceivedSourceConditionMagnitude; + private JRadioButton hitReceivedSourceConditionTimed; + private JRadioButton hitReceivedSourceConditionForever; + private JSpinner hitReceivedSourceConditionDuration; + private TargetTimedConditionsListModel hitReceivedTargetConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedTargetConditionsList; + private MyComboBox hitReceivedTargetConditionBox; + private JSpinner hitReceivedTargetConditionChance; + private JRadioButton hitReceivedTargetConditionClear; + private JRadioButton hitReceivedTargetConditionApply; + private JRadioButton hitReceivedTargetConditionImmunity; + private JSpinner hitReceivedTargetConditionMagnitude; + private JRadioButton hitReceivedTargetConditionTimed; + private JRadioButton hitReceivedTargetConditionForever; + private JSpinner hitReceivedTargetConditionDuration; + + public ItemEditor(Item item) { + super(item, item.getDesc(), item.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public void insertFormViewDataField(JPanel pane) { + + final Item item = (Item) target; + + final FieldUpdateListener listener = new ItemFieldUpdater(); + + itemIcon = createButtonPane(pane, item.getProject(), item, Item.class, item.getImage(), Spritesheet.Category.item, listener); + + idField = addTextField(pane, "Internal ID: ", item.id, item.writable, listener); + nameField = addTranslatableTextField(pane, "Display name: ", item.name, item.writable, listener); + descriptionField = addTranslatableTextField(pane, "Description: ", item.description, item.writable, listener); + typeBox = addEnumValueBox(pane, "Type: ", Item.DisplayType.values(), item.display_type, item.writable, listener); + manualPriceBox = addIntegerBasedCheckBox(pane, "Has manual price", item.has_manual_price, item.writable, listener); + baseManualPrice = item.base_market_cost; + baseCostField = addIntegerField(pane, "Base market cost: ", (item.has_manual_price != null && item.has_manual_price == 1) ? item.base_market_cost : item.computePrice(), false, item.writable, listener); + if (!manualPriceBox.isSelected()) { + baseCostField.setEnabled(false); + } + categoryBox = addItemCategoryBox(pane, item.getProject(), "Category: ", item.category, item.writable, listener); + + equipEffectPane = new CollapsiblePanel("Effect when equipped: "); + equipEffectPane.setLayout(new JideBoxLayout(equipEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.equip_effect == null) { + equipEffect = new Item.EquipEffect(); + } else { + equipEffect = item.equip_effect; + } + equipDmgMin = addIntegerField(equipEffectPane, "Attack Damage min: ", equipEffect.damage_boost_min, true, item.writable, listener); + equipDmgMax = addIntegerField(equipEffectPane, "Attack Damage max: ", equipEffect.damage_boost_max, true, item.writable, listener); + equipSetDM = addIntegerField(equipEffectPane, "Damage modifier %: ", equipEffect.damage_modifier, 100, false, item.writable, listener); + equipBoostHP = addIntegerField(equipEffectPane, "Boost max HP: ", equipEffect.max_hp_boost, true, item.writable, listener); + equipBoostAP = addIntegerField(equipEffectPane, "Boost max AP: ", equipEffect.max_ap_boost, true, item.writable, listener); + equipBoostAC = addIntegerField(equipEffectPane, "Boost attack chance: ", equipEffect.increase_attack_chance, true, item.writable, listener); + equipBoostBC = addIntegerField(equipEffectPane, "Boost block chance: ", equipEffect.increase_block_chance, true, item.writable, listener); + equipBoostCS = addIntegerField(equipEffectPane, "Boost critical skill: ", equipEffect.increase_critical_skill, true, item.writable, listener); + equipSetCM = addDoubleField(equipEffectPane, "Critical multiplier: ", equipEffect.critical_multiplier, item.writable, listener); + equipBoostDR = addIntegerField(equipEffectPane, "Boost damage resistance: ", equipEffect.increase_damage_resistance, true, item.writable, listener); + equipIncMoveCost = addIntegerField(equipEffectPane, "Increase move cost: ", equipEffect.increase_move_cost, true, item.writable, listener); + equipIncUseCost = addIntegerField(equipEffectPane, "Increase item use cost: ", equipEffect.increase_use_item_cost, true, item.writable, listener); + equipIncReequipCost = addIntegerField(equipEffectPane, "Increase reequip cost: ", equipEffect.increase_reequip_cost, true, item.writable, listener); + equipIncAttackCost = addIntegerField(equipEffectPane, "Increase attack cost: ", equipEffect.increase_attack_cost, true, item.writable, listener); + CollapsiblePanel equipConditionsPane = new CollapsiblePanel("Actor Conditions applied when equipped: "); + equipConditionsPane.setLayout(new JideBoxLayout(equipConditionsPane, JideBoxLayout.PAGE_AXIS)); + equipConditionsModel = new ConditionsListModel(equipEffect); + equipConditionsList = new JList(equipConditionsModel); + equipConditionsList.setCellRenderer(new ConditionsCellRenderer()); + equipConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + equipConditionsPane.add(new JScrollPane(equipConditionsList), JideBoxLayout.FIX); + final JPanel equipConditionsEditorPane = new JPanel(); + final JButton createEquipCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteEquipCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + equipConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedEquipEffectCondition = (Common.ConditionEffect) equipConditionsList.getSelectedValue(); + if (selectedEquipEffectCondition == null) { + deleteEquipCondition.setEnabled(false); + } else { + deleteEquipCondition.setEnabled(true); + } + updateEquipConditionEditorPane(equipConditionsEditorPane, selectedEquipEffectCondition, listener); + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createEquipCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.ConditionEffect condition = new Common.ConditionEffect(); + equipConditionsModel.addItem(condition); + equipConditionsList.setSelectedValue(condition, true); + listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteEquipCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedEquipEffectCondition != null) { + equipConditionsModel.removeItem(selectedEquipEffectCondition); + selectedEquipEffectCondition = null; + equipConditionsList.clearSelection(); + listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createEquipCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteEquipCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + equipConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + equipConditionsEditorPane.setLayout(new JideBoxLayout(equipConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + equipConditionsPane.add(equipConditionsEditorPane, JideBoxLayout.FIX); + if (item.equip_effect == null || item.equip_effect.conditions == null || item.equip_effect.conditions.isEmpty()) { + equipConditionsPane.collapse(); + } + equipEffectPane.add(equipConditionsPane, JideBoxLayout.FIX); + pane.add(equipEffectPane, JideBoxLayout.FIX); + if (item.equip_effect == null) { + equipEffectPane.collapse(); + } + + hitEffectPane = new CollapsiblePanel("Effect on every hit: "); + hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.hit_effect == null) { + hitEffect = new Common.HitEffect(); + } else { + hitEffect = item.hit_effect; + } + hitHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, item.writable, listener); + hitHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, item.writable, listener); + hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); + hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); + final CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); + hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); + hitSourceConditionsList = new JList(hitSourceConditionsModel); + hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); + final JPanel sourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); + updateHitSourceTimedConditionEditorPane(sourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); + if (selectedHitEffectSourceCondition == null) { + deleteHitSourceCondition.setEnabled(false); + } else { + deleteHitSourceCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitSourceConditionsModel.addItem(condition); + hitSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectSourceCondition != null) { + hitSourceConditionsModel.removeItem(selectedHitEffectSourceCondition); + selectedHitEffectSourceCondition = null; + hitSourceConditionsList.clearSelection(); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + sourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(sourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsPane.add(sourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_effect == null || item.hit_effect.conditions_source == null || item.hit_effect.conditions_source.isEmpty()) { + hitSourceConditionsPane.collapse(); + } + hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); + hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); + hitTargetConditionsList = new JList(hitTargetConditionsModel); + hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); + final JPanel targetTimedConditionsEditorPane = new JPanel(); + final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); + updateHitTargetTimedConditionEditorPane(targetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); + if (selectedHitEffectTargetCondition == null) { + deleteHitTargetCondition.setEnabled(false); + } else { + deleteHitTargetCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitTargetConditionsModel.addItem(condition); + hitTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectTargetCondition != null) { + hitTargetConditionsModel.removeItem(selectedHitEffectTargetCondition); + selectedHitEffectTargetCondition = null; + hitTargetConditionsList.clearSelection(); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + targetTimedConditionsEditorPane.setLayout(new JideBoxLayout(targetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsPane.add(targetTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_effect == null || item.hit_effect.conditions_target == null || item.hit_effect.conditions_target.isEmpty()) { + hitTargetConditionsPane.collapse(); + } + hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); + if (item.hit_effect == null) { + hitEffectPane.collapse(); + } + pane.add(hitEffectPane, JideBoxLayout.FIX); + + + + killEffectPane = new CollapsiblePanel(killLabel); + killEffectPane.setLayout(new JideBoxLayout(killEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.kill_effect == null) { + killEffect = new Common.DeathEffect(); + } else { + killEffect = item.kill_effect; + } + killHPMin = addIntegerField(killEffectPane, "HP bonus min: ", killEffect.hp_boost_min, true, item.writable, listener); + killHPMax = addIntegerField(killEffectPane, "HP bonus max: ", killEffect.hp_boost_max, true, item.writable, listener); + killAPMin = addIntegerField(killEffectPane, "AP bonus min: ", killEffect.ap_boost_min, true, item.writable, listener); + killAPMax = addIntegerField(killEffectPane, "AP bonus max: ", killEffect.ap_boost_max, true, item.writable, listener); + final CollapsiblePanel killSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); + killSourceConditionsPane.setLayout(new JideBoxLayout(killSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); + killSourceConditionsList = new JList(killSourceConditionsModel); + killSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + killSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + killSourceConditionsPane.add(new JScrollPane(killSourceConditionsList), JideBoxLayout.FIX); + final JPanel killSourceTimedConditionsEditorPane = new JPanel(); + final JButton createKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + killSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedKillEffectCondition = (Common.TimedConditionEffect) killSourceConditionsList.getSelectedValue(); + updateKillSourceTimedConditionEditorPane(killSourceTimedConditionsEditorPane, selectedKillEffectCondition, listener); + if (selectedKillEffectCondition == null) { + deleteKillSourceCondition.setEnabled(false); + } else { + deleteKillSourceCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createKillSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + killSourceConditionsModel.addItem(condition); + killSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteKillSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedKillEffectCondition != null) { + killSourceConditionsModel.removeItem(selectedKillEffectCondition); + selectedKillEffectCondition = null; + killSourceConditionsList.clearSelection(); + listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createKillSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteKillSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + killSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + killSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(killSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + killSourceConditionsPane.add(killSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.kill_effect == null || item.kill_effect.conditions_source == null || item.kill_effect.conditions_source.isEmpty()) { + killSourceConditionsPane.collapse(); + } + killEffectPane.add(killSourceConditionsPane, JideBoxLayout.FIX); + if (item.kill_effect == null) { + killEffectPane.collapse(); + } + pane.add(killEffectPane, JideBoxLayout.FIX); + + + hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); + hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.hit_received_effect == null) { + hitReceivedEffect = new Common.HitReceivedEffect(); + } else { + hitReceivedEffect = item.hit_received_effect; + } + hitReceivedHPMin = addIntegerField(hitReceivedEffectPane, "Player HP bonus min: ", hitReceivedEffect.hp_boost_min, true, item.writable, listener); + hitReceivedHPMax = addIntegerField(hitReceivedEffectPane, "Player HP bonus max: ", hitReceivedEffect.hp_boost_max, true, item.writable, listener); + hitReceivedAPMin = addIntegerField(hitReceivedEffectPane, "Player AP bonus min: ", hitReceivedEffect.ap_boost_min, true, item.writable, listener); + hitReceivedAPMax = addIntegerField(hitReceivedEffectPane, "Player AP bonus max: ", hitReceivedEffect.ap_boost_max, true, item.writable, listener); + hitReceivedHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, item.writable, listener); + hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, item.writable, listener); + hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, item.writable, listener); + hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, item.writable, listener); + final CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the player: "); + hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(hitReceivedEffect); + hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsModel); + hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); + updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); + if (selectedHitReceivedEffectSourceCondition == null) { + deleteHitReceivedSourceCondition.setEnabled(false); + } else { + deleteHitReceivedSourceCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedSourceConditionsModel.addItem(condition); + hitReceivedSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectSourceCondition != null) { + hitReceivedSourceConditionsModel.removeItem(selectedHitReceivedEffectSourceCondition); + selectedHitReceivedEffectSourceCondition = null; + hitReceivedSourceConditionsList.clearSelection(); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_received_effect == null || item.hit_received_effect.conditions_source == null || item.hit_received_effect.conditions_source.isEmpty()) { + hitReceivedSourceConditionsPane.collapse(); + } + hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); + hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); + hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsModel); + hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); + updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); + if (selectedHitReceivedEffectTargetCondition == null) { + deleteHitReceivedTargetCondition.setEnabled(false); + } else { + deleteHitReceivedTargetCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedTargetConditionsModel.addItem(condition); + hitReceivedTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectTargetCondition != null) { + hitReceivedTargetConditionsModel.removeItem(selectedHitReceivedEffectTargetCondition); + selectedHitReceivedEffectTargetCondition = null; + hitReceivedTargetConditionsList.clearSelection(); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_received_effect == null || item.hit_received_effect.conditions_target == null || item.hit_received_effect.conditions_target.isEmpty()) { + hitReceivedTargetConditionsPane.collapse(); + } + hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); + if (item.hit_received_effect == null) { + hitReceivedEffectPane.collapse(); + } + pane.add(hitReceivedEffectPane, JideBoxLayout.FIX); + + + if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { + equipEffectPane.setVisible(false); + hitEffectPane.setVisible(false); + killEffectPane.setVisible(false); + } else if (item.category.action_type == ItemCategory.ActionType.use) { + equipEffectPane.setVisible(false); + hitEffectPane.setVisible(false); + killEffectPane.setVisible(true); + killEffectPane.setTitle(useLabel); + killEffectPane.revalidate(); + killEffectPane.repaint(); + } else if (item.category.action_type == ItemCategory.ActionType.equip) { + equipEffectPane.setVisible(true); + hitEffectPane.setVisible(true); + killEffectPane.setVisible(true); + killEffectPane.setTitle(killLabel); + killEffectPane.revalidate(); + killEffectPane.repaint(); + } + + } + + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitSourceConditionBox != null) { + removeElementListener(hitSourceConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item)target).writable; + Project proj = ((Item)target).getProject(); + + hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitSourceConditionClear, JideBoxLayout.FIX); + hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitSourceConditionApply, JideBoxLayout.FIX); + hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitSourceConditionApply); + radioEffectGroup.add(hitSourceConditionClear); + radioEffectGroup.add(hitSourceConditionImmunity); + + hitSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); + hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitSourceConditionTimed); + radioDurationGroup.add(hitSourceConditionForever); + + updateHitSourceTimedConditionWidgets(condition); + + hitSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + } + }); + hitSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + } + }); + hitSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + } + }); + + hitSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + } + }); + hitSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitSourceConditionClear.setSelected(clear); + hitSourceConditionApply.setSelected(!clear && !immunity); + hitSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitSourceConditionImmunity.setSelected(immunity); + + hitSourceConditionTimed.setSelected(!forever); + hitSourceConditionTimed.setEnabled(!clear); + hitSourceConditionDuration.setEnabled(!clear && !forever); + hitSourceConditionForever.setSelected(forever); + hitSourceConditionForever.setEnabled(!clear); + } + + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitTargetConditionBox != null) { + removeElementListener(hitTargetConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item)target).writable; + Project proj = ((Item)target).getProject(); + + hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitTargetConditionClear, JideBoxLayout.FIX); + hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitTargetConditionApply, JideBoxLayout.FIX); + hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitTargetConditionApply); + radioEffectGroup.add(hitTargetConditionClear); + radioEffectGroup.add(hitTargetConditionImmunity); + + hitTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); + hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitTargetConditionTimed); + radioDurationGroup.add(hitTargetConditionForever); + + updateHitTargetTimedConditionWidgets(condition); + + hitTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + } + }); + hitTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + } + }); + hitTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + } + }); + + hitTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + } + }); + hitTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitTargetConditionClear.setSelected(clear); + hitTargetConditionApply.setSelected(!clear && !immunity); + hitTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitTargetConditionImmunity.setSelected(immunity); + + hitTargetConditionTimed.setSelected(!forever); + hitTargetConditionTimed.setEnabled(!clear); + hitTargetConditionDuration.setEnabled(!clear && !forever); + hitTargetConditionForever.setSelected(forever); + hitTargetConditionForever.setEnabled(!clear); + } + + public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (killSourceConditionBox != null) { + removeElementListener(killSourceConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item)target).writable; + Project proj = ((Item)target).getProject(); + + killSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + killSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + killSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(killSourceConditionClear, JideBoxLayout.FIX); + killSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(killSourceConditionApply, JideBoxLayout.FIX); + killSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + killSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(killSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(killSourceConditionApply); + radioEffectGroup.add(killSourceConditionClear); + radioEffectGroup.add(killSourceConditionImmunity); + + killSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(killSourceConditionTimed, JideBoxLayout.FIX); + killSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + killSourceConditionForever = new JRadioButton("Forever"); + pane.add(killSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(killSourceConditionTimed); + radioDurationGroup.add(killSourceConditionForever); + + updateKillSourceTimedConditionWidgets(condition); + + killSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionClear, new Boolean(killSourceConditionClear.isSelected())); + } + }); + killSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionApply, new Boolean(killSourceConditionApply.isSelected())); + } + }); + killSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionImmunity, new Boolean(killSourceConditionImmunity.isSelected())); + } + }); + + killSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionTimed, new Boolean(killSourceConditionTimed.isSelected())); + } + }); + killSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionForever, new Boolean(killSourceConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateKillSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + killSourceConditionClear.setSelected(clear); + killSourceConditionApply.setSelected(!clear && !immunity); + killSourceConditionMagnitude.setEnabled(!clear && !immunity); + killSourceConditionImmunity.setSelected(immunity); + + killSourceConditionTimed.setSelected(!forever); + killSourceConditionTimed.setEnabled(!clear); + killSourceConditionDuration.setEnabled(!clear && !forever); + killSourceConditionForever.setSelected(forever); + killSourceConditionForever.setEnabled(!clear); + } + + public void updateEquipConditionEditorPane(JPanel pane, Common.ConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (equipConditionBox != null) { + removeElementListener(equipConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item)target).writable; + Project proj = ((Item)target).getProject(); + + equipConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + equipConditionWithMagnitude = new JRadioButton("Apply condition with magnitude."); + pane.add(equipConditionWithMagnitude, JideBoxLayout.FIX); + equipConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude, 1, false, writable, listener); + equipConditionImmunity = new JRadioButton("Give immunity to condition."); + pane.add(equipConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(equipConditionWithMagnitude); + radioEffectGroup.add(equipConditionImmunity); + + boolean immunity = condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR; + equipConditionImmunity.setSelected(immunity); + equipConditionWithMagnitude.setSelected(!immunity); + equipConditionMagnitude.setEnabled(!immunity); + + equipConditionWithMagnitude.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(equipConditionWithMagnitude, new Boolean(equipConditionWithMagnitude.isSelected())); + } + }); + equipConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(equipConditionImmunity, new Boolean(equipConditionImmunity.isSelected())); + } + }); + + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedSourceConditionBox != null) { + removeElementListener(hitReceivedSourceConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item)target).writable; + Project proj = ((Item)target).getProject(); + + hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); + hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); + hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedSourceConditionApply); + radioEffectGroup.add(hitReceivedSourceConditionClear); + radioEffectGroup.add(hitReceivedSourceConditionImmunity); + + hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); + hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedSourceConditionTimed); + radioDurationGroup.add(hitReceivedSourceConditionForever); + + updateHitReceivedSourceTimedConditionWidgets(condition); + + hitReceivedSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); + } + }); + hitReceivedSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); + } + }); + hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); + } + }); + + hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); + } + }); + hitReceivedSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedSourceConditionClear.setSelected(clear); + hitReceivedSourceConditionApply.setSelected(!clear && !immunity); + hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedSourceConditionImmunity.setSelected(immunity); + + hitReceivedSourceConditionTimed.setSelected(!forever); + hitReceivedSourceConditionTimed.setEnabled(!clear); + hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); + hitReceivedSourceConditionForever.setSelected(forever); + hitReceivedSourceConditionForever.setEnabled(!clear); + } + + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedTargetConditionBox != null) { + removeElementListener(hitReceivedTargetConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item)target).writable; + Project proj = ((Item)target).getProject(); + + hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); + hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); + hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedTargetConditionApply); + radioEffectGroup.add(hitReceivedTargetConditionClear); + radioEffectGroup.add(hitReceivedTargetConditionImmunity); + + hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); + hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedTargetConditionTimed); + radioDurationGroup.add(hitReceivedTargetConditionForever); + + updateHitReceivedTargetTimedConditionWidgets(condition); + + hitReceivedTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); + } + }); + hitReceivedTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); + } + }); + hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); + } + }); + + hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); + } + }); + hitReceivedTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedTargetConditionClear.setSelected(clear); + hitReceivedTargetConditionApply.setSelected(!clear && !immunity); + hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedTargetConditionImmunity.setSelected(immunity); + + hitReceivedTargetConditionTimed.setSelected(!forever); + hitReceivedTargetConditionTimed.setEnabled(!clear); + hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); + hitReceivedTargetConditionForever.setSelected(forever); + hitReceivedTargetConditionForever.setEnabled(!clear); + } + + + public static class SourceTimedConditionsListModel extends OrderedListenerListModel { + public SourceTimedConditionsListModel(Common.DeathEffect effect) { + super(effect);; + } + @Override + protected List getItems() { + return source.conditions_source; + } + + @Override + protected void setItems(List items) { + source.conditions_source = items; + } + } + + public static class TargetTimedConditionsListModel extends OrderedListenerListModel { + public TargetTimedConditionsListModel(Common.HitEffect effect) { + super(effect); + } + + @Override + protected List getItems() { + return source.conditions_target; + } + + @Override + protected void setItems(List items) { + source.conditions_target = items; + } + } + + public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel)c); + Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; + + if (effect.condition != null) { + + boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); + boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); + boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; + + if (clear) { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance+"% chances to clear actor condition "+effect.condition.getDesc()); + } else if (immunity) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText(effect.chance+"% chances to give immunity to "+effect.condition.getDesc()+(forever ? " forever" : " for "+effect.duration+" rounds")); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance+"% chances to give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude+(forever ? " forever" : " for "+effect.duration+" rounds")); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } + + public static class ConditionsListModel extends OrderedListenerListModel { + public ConditionsListModel(Item.EquipEffect equipEffect) { + super(equipEffect); + } + + @Override + protected List getItems() { + return source.conditions; + } + + @Override + protected void setItems(List conditions) { + source.conditions = conditions; + } + } + + public static class ConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel)c); + Common.ConditionEffect effect = (Common.ConditionEffect) value; + + if (effect.condition != null) { + if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText("Immune to actor condition "+effect.condition.getDesc()); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText("Give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } + + public static boolean isNull(Item.EquipEffect effect) { + if (effect.conditions != null) return false; + if (effect.critical_multiplier != null) return false; + if (effect.damage_modifier != null) return false; + if (effect.damage_boost_max != null) return false; + if (effect.damage_boost_min != null) return false; + if (effect.increase_attack_chance != null) return false; + if (effect.increase_attack_cost != null) return false; + if (effect.increase_block_chance != null) return false; + if (effect.increase_critical_skill != null) return false; + if (effect.increase_damage_resistance != null) return false; + if (effect.increase_move_cost != null) return false; + if (effect.increase_reequip_cost != null) return false; + if (effect.increase_use_item_cost != null) return false; + if (effect.max_ap_boost != null) return false; + if (effect.max_hp_boost != null) return false; + return true; + } + + + public static boolean isNull(Common.HitEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + + public static boolean isNull(Common.DeathEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + return true; + } + + public static boolean isNull(Common.HitReceivedEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.ap_boost_min_target != null) return false; + if (effect.ap_boost_max_target != null) return false; + if (effect.hp_boost_min_target != null) return false; + if (effect.hp_boost_max_target != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + + public class ItemFieldUpdater implements FieldUpdateListener { + + @Override + public void valueChanged(JComponent source, Object value) { + Item item = (Item)target; + boolean updatePrice, updateEquip, updateHit, updateKill, updateHitReceived; + updatePrice = updateEquip = updateHit = updateKill = updateHitReceived = false; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + item.id = (String) value; + ItemEditor.this.name = item.getDesc(); + item.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + item.name = (String) value; + ItemEditor.this.name = item.getDesc(); + item.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemEditor.this); + } else if (source == itemIcon) { + item.icon_id = (String) value; + item.childrenChanged(new ArrayList()); + ItemEditor.this.icon = new ImageIcon(item.getProject().getIcon((String) value)); + ATContentStudio.frame.editorChanged(ItemEditor.this); + itemIcon.setIcon(new ImageIcon(item.getProject().getImage((String) value))); + itemIcon.revalidate(); + itemIcon.repaint(); + } else if (source == descriptionField) { + item.description = descriptionField.getText(); + } else if (source == typeBox) { + item.display_type = (Item.DisplayType) value; + } else if (source == manualPriceBox) { + item.has_manual_price = (Integer) value; + if (!manualPriceBox.isSelected()) { + baseCostField.setEnabled(false); + updatePrice = true; + } else { + baseCostField.setEnabled(true); + if (baseManualPrice != null) { + baseCostField.setValue(baseManualPrice); + } + } + } else if (source == baseCostField) { + if (manualPriceBox.isSelected()) { + item.base_market_cost = (Integer) value; + baseManualPrice = item.base_market_cost; + } + } else if (source == categoryBox) { + if (item.category != null) { + item.category.removeBacklink(item); + } + item.category = (ItemCategory) value; + if (item.category != null) { + item.category_id = item.category.id; + item.category.addBacklink(item); + } else { + item.category_id = null; + } + if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { + equipEffectPane.setVisible(false); + item.equip_effect = null; + hitEffectPane.setVisible(false); + item.hit_effect = null; + killEffectPane.setVisible(false); + item.kill_effect = null; + hitReceivedEffectPane.setVisible(false); + item.hit_received_effect = null; + ItemEditor.this.revalidate(); + ItemEditor.this.repaint(); + } else if (item.category.action_type == ItemCategory.ActionType.use) { + equipEffectPane.setVisible(false); + item.equip_effect = null; + hitEffectPane.setVisible(false); + item.hit_effect = null; + killEffectPane.setVisible(true); + updateKill = true; + hitReceivedEffectPane.setVisible(false); + item.hit_received_effect = null; + killEffectPane.setTitle(useLabel); + ItemEditor.this.revalidate(); + ItemEditor.this.repaint(); + } else if (item.category.action_type == ItemCategory.ActionType.equip) { + equipEffectPane.setVisible(true); + updateEquip = true; + hitEffectPane.setVisible(true); + updateEquip = true; + killEffectPane.setVisible(true); + updateKill = true; + hitReceivedEffectPane.setVisible(true); + updateEquip = true; + killEffectPane.setTitle(killLabel); + ItemEditor.this.revalidate(); + ItemEditor.this.repaint(); + } + updatePrice = true; + } else if (source == equipDmgMin) { + equipEffect.damage_boost_min = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipDmgMax) { + equipEffect.damage_boost_max = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostHP) { + equipEffect.max_hp_boost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostAP) { + equipEffect.max_ap_boost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostAC) { + equipEffect.increase_attack_chance = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostBC) { + equipEffect.increase_block_chance = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostCS) { + equipEffect.increase_critical_skill = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipSetCM) { + equipEffect.critical_multiplier = (Double) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipSetDM) { + equipEffect.damage_modifier = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostDR) { + equipEffect.increase_damage_resistance = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncMoveCost) { + equipEffect.increase_move_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncUseCost) { + equipEffect.increase_use_item_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncReequipCost) { + equipEffect.increase_reequip_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncAttackCost) { + equipEffect.increase_attack_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipConditionsList) { + updateEquip = true; + } else if (source == equipConditionBox) { + if (selectedEquipEffectCondition.condition != null) { + selectedEquipEffectCondition.condition.removeBacklink(item); + } + selectedEquipEffectCondition.condition = (ActorCondition) value; + if (selectedEquipEffectCondition.condition != null) { + selectedEquipEffectCondition.condition_id = selectedEquipEffectCondition.condition.id; + selectedEquipEffectCondition.condition.addBacklink(item); + } else { + selectedEquipEffectCondition.condition_id = null; + } + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == equipConditionMagnitude) { + selectedEquipEffectCondition.magnitude = (Integer) value; + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == equipConditionImmunity && (Boolean) value) { + selectedEquipEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + equipConditionMagnitude.setEnabled(false); + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == equipConditionWithMagnitude && (Boolean) value) { + selectedEquipEffectCondition.magnitude = (Integer) equipConditionMagnitude.getValue(); + equipConditionMagnitude.setEnabled(true); + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == hitHPMin) { + hitEffect.hp_boost_min = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitHPMax) { + hitEffect.hp_boost_max = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitAPMin) { + hitEffect.ap_boost_min = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitAPMax) { + hitEffect.ap_boost_max = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitSourceConditionsList) { + updateHit = true; + } else if (source == hitSourceConditionBox) { + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition.removeBacklink(item); + } + selectedHitEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; + selectedHitEffectSourceCondition.condition.addBacklink(item); + } else { + selectedHitEffectSourceCondition.condition_id = null; + } + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionClear && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = null; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionApply && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionImmunity && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionMagnitude) { + selectedHitEffectSourceCondition.magnitude = (Integer) value; + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionTimed && (Boolean) value) { + selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionForever && (Boolean) value) { + selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionDuration) { + selectedHitEffectSourceCondition.duration = (Integer) value; + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionChance) { + selectedHitEffectSourceCondition.chance = (Double) value; + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitTargetConditionsList) { + updateHit = true; + } else if (source == hitTargetConditionBox) { + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition.removeBacklink(item); + } + selectedHitEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; + selectedHitEffectTargetCondition.condition.addBacklink(item); + } else { + selectedHitEffectTargetCondition.condition_id = null; + } + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionClear && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = null; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionApply && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionImmunity && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionMagnitude) { + selectedHitEffectTargetCondition.magnitude = (Integer) value; + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionTimed && (Boolean) value) { + selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionForever && (Boolean) value) { + selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionDuration) { + selectedHitEffectTargetCondition.duration = (Integer) value; + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionChance) { + selectedHitEffectTargetCondition.chance = (Double) value; + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == killHPMin) { + killEffect.hp_boost_min = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killHPMax) { + killEffect.hp_boost_max = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killAPMin) { + killEffect.ap_boost_min = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killAPMax) { + killEffect.ap_boost_max = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killSourceConditionsList) { + updateKill = true; + } else if (source == killSourceConditionBox) { + if (selectedKillEffectCondition.condition != null) { + selectedKillEffectCondition.condition.removeBacklink(item); + } + selectedKillEffectCondition.condition = (ActorCondition) value; + if (selectedKillEffectCondition.condition != null) { + selectedKillEffectCondition.condition_id = selectedKillEffectCondition.condition.id; + selectedKillEffectCondition.condition.addBacklink(item); + } else { + selectedKillEffectCondition.condition_id = null; + } + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionClear && (Boolean) value) { + selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedKillEffectCondition.duration = null; + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionApply && (Boolean) value) { + selectedKillEffectCondition.magnitude = (Integer) killSourceConditionMagnitude.getValue(); + selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); + if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { + selectedKillEffectCondition.duration = 1; + } + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionImmunity && (Boolean) value) { + selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); + if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { + selectedKillEffectCondition.duration = 1; + } + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionMagnitude) { + selectedKillEffectCondition.magnitude = (Integer) value; + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionTimed && (Boolean) value) { + selectedKillEffectCondition.duration = (Integer) killSourceConditionDuration.getValue(); + if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { + selectedKillEffectCondition.duration = 1; + } + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionForever && (Boolean) value) { + selectedKillEffectCondition.duration = ActorCondition.DURATION_FOREVER; + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionDuration) { + selectedKillEffectCondition.duration = (Integer) value; + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionChance) { + selectedKillEffectCondition.chance = (Double) value; + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == hitReceivedHPMin) { + hitReceivedEffect.hp_boost_min = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedHPMax) { + hitReceivedEffect.hp_boost_max = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMin) { + hitReceivedEffect.ap_boost_min = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMax) { + hitReceivedEffect.ap_boost_max = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedHPMinTarget) { + hitReceivedEffect.hp_boost_min_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedHPMaxTarget) { + hitReceivedEffect.hp_boost_max_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMinTarget) { + hitReceivedEffect.ap_boost_min_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMaxTarget) { + hitReceivedEffect.ap_boost_max_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionBox) { + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition.removeBacklink(item); + } + selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; + selectedHitReceivedEffectSourceCondition.condition.addBacklink(item); + } else { + selectedHitReceivedEffectSourceCondition.condition_id = null; + } + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = null; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionMagnitude) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionDuration) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) value; + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionChance) { + selectedHitReceivedEffectSourceCondition.chance = (Double) value; + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionBox) { + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition.removeBacklink(item); + } + selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; + selectedHitReceivedEffectTargetCondition.condition.addBacklink(item); + } else { + selectedHitReceivedEffectTargetCondition.condition_id = null; + } + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = null; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionMagnitude) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionDuration) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) value; + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionChance) { + selectedHitReceivedEffectTargetCondition.chance = (Double) value; + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } + + if (updateEquip) { + if (isNull(equipEffect)) { + item.equip_effect = null; + } else { + item.equip_effect = equipEffect; + } + } + if (updateHit) { + if (isNull(hitEffect)) { + item.hit_effect = null; + } else { + item.hit_effect = hitEffect; + } + } + if (updateKill) { + if (isNull(killEffect)) { + item.kill_effect = null; + } else { + item.kill_effect = killEffect; + } + } + if (updateHitReceived) { + if (isNull(hitReceivedEffect)) { + item.hit_received_effect = null; + } else { + item.hit_received_effect = hitReceivedEffect; + } + } + if (updatePrice && !manualPriceBox.isSelected()) { + baseCostField.setValue(item.computePrice()); + } + + + if (item.state != GameDataElement.State.modified) { + item.state = GameDataElement.State.modified; + ItemEditor.this.name = item.getDesc(); + item.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemEditor.this); + } + updateJsonViewText(item.toJsonString()); + + } + + } + +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 5fe32f3..7ea7871 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -1,1612 +1,1612 @@ -package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; - -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTextField; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.*; -import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.*; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; -import com.jidesoft.swing.JideBoxLayout; - -public class NPCEditor extends JSONElementEditor { - - private static final long serialVersionUID = 4001483665523721800L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - private static final String dialogue_tree_id = "Dialogue Tree"; - - private Common.TimedConditionEffect selectedHitEffectSourceCondition; - private Common.TimedConditionEffect selectedHitEffectTargetCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; - private Common.TimedConditionEffect selectedDeathEffectSourceCondition; - - private JButton npcIcon; - private JTextField idField; - private JTextField nameField; - private JTextField spawnGroupField; - private JTextField factionField; - private JSpinner experienceField; - private MyComboBox dialogueBox; - private MyComboBox droplistBox; - @SuppressWarnings("rawtypes") - private JComboBox monsterClassBox; - private IntegerBasedCheckBox uniqueBox; - @SuppressWarnings("rawtypes") - private JComboBox moveTypeBox; - - private CollapsiblePanel combatTraitPane; - private JSpinner maxHP; - private JSpinner maxAP; - private JSpinner moveCost; - private JSpinner atkDmgMin; - private JSpinner atkDmgMax; - private JSpinner atkCost; - private JSpinner atkChance; - private JSpinner critSkill; - private JSpinner critMult; - private JSpinner blockChance; - private JSpinner dmgRes; - - private Common.HitEffect hitEffect; - private CollapsiblePanel hitEffectPane; - private JSpinner hitEffectHPMin; - private JSpinner hitEffectHPMax; - private JSpinner hitEffectAPMin; - private JSpinner hitEffectAPMax; - - private SourceTimedConditionsListModel hitSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; - private MyComboBox hitSourceConditionBox; - private JSpinner hitSourceConditionChance; - private JRadioButton hitSourceConditionClear; - private JRadioButton hitSourceConditionApply; - private JRadioButton hitSourceConditionImmunity; - private JSpinner hitSourceConditionMagnitude; - private JRadioButton hitSourceConditionTimed; - private JRadioButton hitSourceConditionForever; - private JSpinner hitSourceConditionDuration; - - private TargetTimedConditionsListModel hitTargetConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitTargetConditionsList; - private MyComboBox hitTargetConditionBox; - private JSpinner hitTargetConditionChance; - private JRadioButton hitTargetConditionClear; - private JRadioButton hitTargetConditionApply; - private JRadioButton hitTargetConditionImmunity; - private JSpinner hitTargetConditionMagnitude; - private JRadioButton hitTargetConditionTimed; - private JRadioButton hitTargetConditionForever; - private JSpinner hitTargetConditionDuration; - - private Common.HitReceivedEffect hitReceivedEffect; - private CollapsiblePanel hitReceivedEffectPane; - private JSpinner hitReceivedEffectHPMin; - private JSpinner hitReceivedEffectHPMax; - private JSpinner hitReceivedEffectAPMin; - private JSpinner hitReceivedEffectAPMax; - private JSpinner hitReceivedEffectHPMinTarget; - private JSpinner hitReceivedEffectHPMaxTarget; - private JSpinner hitReceivedEffectAPMinTarget; - private JSpinner hitReceivedEffectAPMaxTarget; - - private SourceTimedConditionsListModel hitReceivedSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedSourceConditionsList; - private MyComboBox hitReceivedSourceConditionBox; - private JSpinner hitReceivedSourceConditionChance; - private JRadioButton hitReceivedSourceConditionClear; - private JRadioButton hitReceivedSourceConditionApply; - private JRadioButton hitReceivedSourceConditionImmunity; - private JSpinner hitReceivedSourceConditionMagnitude; - private JRadioButton hitReceivedSourceConditionTimed; - private JRadioButton hitReceivedSourceConditionForever; - private JSpinner hitReceivedSourceConditionDuration; - - private TargetTimedConditionsListModel hitReceivedTargetConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedTargetConditionsList; - private MyComboBox hitReceivedTargetConditionBox; - private JSpinner hitReceivedTargetConditionChance; - private JRadioButton hitReceivedTargetConditionClear; - private JRadioButton hitReceivedTargetConditionApply; - private JRadioButton hitReceivedTargetConditionImmunity; - private JSpinner hitReceivedTargetConditionMagnitude; - private JRadioButton hitReceivedTargetConditionTimed; - private JRadioButton hitReceivedTargetConditionForever; - private JSpinner hitReceivedTargetConditionDuration; - - private Common.DeathEffect deathEffect; - private CollapsiblePanel deathEffectPane; - private JSpinner deathEffectHPMin; - private JSpinner deathEffectHPMax; - private JSpinner deathEffectAPMin; - private JSpinner deathEffectAPMax; - - private SourceTimedConditionsListModel deathSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList deathSourceConditionsList; - private MyComboBox deathSourceConditionBox; - private JSpinner deathSourceConditionChance; - private JRadioButton deathSourceConditionClear; - private JRadioButton deathSourceConditionApply; - private JRadioButton deathSourceConditionImmunity; - private JSpinner deathSourceConditionMagnitude; - private JRadioButton deathSourceConditionTimed; - private JRadioButton deathSourceConditionForever; - private JSpinner deathSourceConditionDuration; - - private JPanel dialogueGraphPane; - private DialogueGraphView dialogueGraphView; - - public NPCEditor(NPC npc) { - super(npc, npc.getDesc(), npc.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - if (npc.dialogue != null) { - createDialogueGraphView(npc); - addEditorTab(dialogue_tree_id, dialogueGraphPane); - } - } - - public JPanel createDialogueGraphView(final NPC npc) { - dialogueGraphPane = new JPanel(); - dialogueGraphPane.setLayout(new BorderLayout()); - - dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); - dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - JButton reloadButton = new JButton("Refresh graph"); - buttonPane.add(reloadButton, JideBoxLayout.FIX); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - dialogueGraphPane.add(buttonPane, BorderLayout.NORTH); - - - reloadButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - reloadGraphView(npc); - } - }); - - return dialogueGraphPane; - } - - public void reloadGraphView(NPC npc) { - if (npc.dialogue != null) { - if (dialogueGraphPane != null) { - dialogueGraphPane.remove(dialogueGraphView); - dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); - dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); - dialogueGraphPane.revalidate(); - dialogueGraphPane.repaint(); - } else { - createDialogueGraphView(npc); - addEditorTab(dialogue_tree_id, dialogueGraphPane); - } - } else { - if (dialogueGraphPane != null) { - removeEditorTab(dialogue_tree_id); - dialogueGraphPane = null; - dialogueGraphView = null; - } - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void insertFormViewDataField(JPanel pane) { - final NPC npc = (NPC) target; - - final FieldUpdateListener listener = new NPCFieldUpdater(); - - npcIcon = createButtonPane(pane, npc.getProject(), npc, NPC.class, npc.getImage(), Spritesheet.Category.monster, listener); - - idField = addTextField(pane, "Internal ID: ", npc.id, npc.writable, listener); - nameField = addTranslatableTextField(pane, "Display name: ", npc.name, npc.writable, listener); - spawnGroupField = addTextField(pane, "Spawn group ID: ", npc.spawngroup_id, npc.writable, listener); - factionField = addTextField(pane, "Faction ID: ", npc.faction_id, npc.writable, listener); - experienceField = addIntegerField(pane, "Experience reward: ", npc.getMonsterExperience(), false, false, listener); - dialogueBox = addDialogueBox(pane, npc.getProject(), "Initial phrase: ", npc.dialogue, npc.writable, listener); - droplistBox = addDroplistBox(pane, npc.getProject(), "Droplist / Shop inventory: ", npc.droplist, npc.writable, listener); - monsterClassBox = addEnumValueBox(pane, "Monster class: ", NPC.MonsterClass.values(), npc.monster_class, npc.writable, listener); - uniqueBox = addIntegerBasedCheckBox(pane, "Unique", npc.unique, npc.writable, listener); - moveTypeBox = addEnumValueBox(pane, "Movement type: ", NPC.MovementType.values(), npc.movement_type, npc.writable, listener); - combatTraitPane = new CollapsiblePanel("Combat traits: "); - combatTraitPane.setLayout(new JideBoxLayout(combatTraitPane, JideBoxLayout.PAGE_AXIS, 6)); - maxHP = addIntegerField(combatTraitPane, "Max HP: ", npc.max_hp, 1, false, npc.writable, listener); - maxAP = addIntegerField(combatTraitPane, "Max AP: ", npc.max_ap, 10, false, npc.writable, listener); - moveCost = addIntegerField(combatTraitPane, "Move cost: ", npc.move_cost, 10, false, npc.writable, listener); - atkDmgMin = addIntegerField(combatTraitPane, "Attack Damage min: ", npc.attack_damage_min, false, npc.writable, listener); - atkDmgMax = addIntegerField(combatTraitPane, "Attack Damage max: ", npc.attack_damage_max, false, npc.writable, listener); - atkCost = addIntegerField(combatTraitPane, "Attack cost: ", npc.attack_cost, 10, false, npc.writable, listener); - atkChance = addIntegerField(combatTraitPane, "Attack chance: ", npc.attack_chance, false, npc.writable, listener); - critSkill = addIntegerField(combatTraitPane, "Critical skill: ", npc.critical_skill, false, npc.writable, listener); - critMult = addDoubleField(combatTraitPane, "Critical multiplier: ", npc.critical_multiplier, npc.writable, listener); - blockChance = addIntegerField(combatTraitPane, "Block chance: ", npc.block_chance, false, npc.writable, listener); - dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = npc.hit_effect; - } - hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); - hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); - hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); - hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); - - CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); - hitSourceConditionsList = new JList(hitSourceConditionsListModel); - hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); - updateHitSourceTimedConditionEditorPane(hitSourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitSourceConditionsListModel.addItem(condition); - hitSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectSourceCondition != null) { - hitSourceConditionsListModel.removeItem(selectedHitEffectSourceCondition); - selectedHitEffectSourceCondition = null; - hitSourceConditionsList.clearSelection(); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsPane.add(hitSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); - } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); - hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); - hitTargetConditionsList = new JList(hitTargetConditionsListModel); - hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); - updateHitTargetTimedConditionEditorPane(hitTargetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitTargetConditionsListModel.addItem(condition); - hitTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectTargetCondition != null) { - hitTargetConditionsListModel.removeItem(selectedHitEffectTargetCondition); - selectedHitEffectTargetCondition = null; - hitTargetConditionsList.clearSelection(); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsPane.add(hitTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); - if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { - hitTargetConditionsPane.collapse(); - } - combatTraitPane.add(hitEffectPane, JideBoxLayout.FIX); - - hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); - hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.hit_received_effect == null) { - hitReceivedEffect = new Common.HitReceivedEffect(); - } else { - hitReceivedEffect = npc.hit_received_effect; - } - hitReceivedEffectHPMin = addIntegerField(hitReceivedEffectPane, "NPC HP bonus min: ", hitReceivedEffect.hp_boost_min, true, npc.writable, listener); - hitReceivedEffectHPMax = addIntegerField(hitReceivedEffectPane, "NPC HP bonus max: ", hitReceivedEffect.hp_boost_max, true, npc.writable, listener); - hitReceivedEffectAPMin = addIntegerField(hitReceivedEffectPane, "NPC AP bonus min: ", hitReceivedEffect.ap_boost_min, true, npc.writable, listener); - hitReceivedEffectAPMax = addIntegerField(hitReceivedEffectPane, "NPC AP bonus max: ", hitReceivedEffect.ap_boost_max, true, npc.writable, listener); - hitReceivedEffectHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, npc.writable, listener); - hitReceivedEffectHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, npc.writable, listener); - hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, npc.writable, listener); - hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, npc.writable, listener); - - CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to this NPC: "); - hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); - hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsListModel); - hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); - updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedSourceConditionsListModel.addItem(condition); - hitReceivedSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectSourceCondition != null) { - hitReceivedSourceConditionsListModel.removeItem(selectedHitReceivedEffectSourceCondition); - selectedHitReceivedEffectSourceCondition = null; - hitReceivedSourceConditionsList.clearSelection(); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_source == null || npc.hit_received_effect.conditions_source.isEmpty()) { - hitReceivedSourceConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); - hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); - hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsListModel); - hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); - updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedTargetConditionsListModel.addItem(condition); - hitReceivedTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectTargetCondition != null) { - hitReceivedTargetConditionsListModel.removeItem(selectedHitReceivedEffectTargetCondition); - selectedHitReceivedEffectTargetCondition = null; - hitReceivedTargetConditionsList.clearSelection(); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); - if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_target == null || npc.hit_received_effect.conditions_target.isEmpty()) { - hitReceivedTargetConditionsPane.collapse(); - } - combatTraitPane.add(hitReceivedEffectPane, JideBoxLayout.FIX); - - deathEffectPane = new CollapsiblePanel("Effect when killed: "); - deathEffectPane.setLayout(new JideBoxLayout(deathEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.death_effect == null) { - deathEffect = new Common.DeathEffect(); - } else { - deathEffect = npc.death_effect; - } - deathEffectHPMin = addIntegerField(deathEffectPane, "Killer HP bonus min: ", deathEffect.hp_boost_min, true, npc.writable, listener); - deathEffectHPMax = addIntegerField(deathEffectPane, "Killer HP bonus max: ", deathEffect.hp_boost_max, true, npc.writable, listener); - deathEffectAPMin = addIntegerField(deathEffectPane, "Killer AP bonus min: ", deathEffect.ap_boost_min, true, npc.writable, listener); - deathEffectAPMax = addIntegerField(deathEffectPane, "Killer AP bonus max: ", deathEffect.ap_boost_max, true, npc.writable, listener); - - CollapsiblePanel deathSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the killer: "); - deathSourceConditionsPane.setLayout(new JideBoxLayout(deathSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); - deathSourceConditionsList = new JList(deathSourceConditionsListModel); - deathSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - deathSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - deathSourceConditionsPane.add(new JScrollPane(deathSourceConditionsList), JideBoxLayout.FIX); - final JPanel deathSourceTimedConditionsEditorPane = new JPanel(); - final JButton createDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deathSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedDeathEffectSourceCondition = (Common.TimedConditionEffect) deathSourceConditionsList.getSelectedValue(); - updateDeathSourceTimedConditionEditorPane(deathSourceTimedConditionsEditorPane, selectedDeathEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createDeathSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - deathSourceConditionsListModel.addItem(condition); - deathSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteDeathSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedDeathEffectSourceCondition != null) { - deathSourceConditionsListModel.removeItem(selectedDeathEffectSourceCondition); - selectedDeathEffectSourceCondition = null; - deathSourceConditionsList.clearSelection(); - listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createDeathSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteDeathSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - deathSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - deathSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(deathSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - deathSourceConditionsPane.add(deathSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (npc.death_effect == null || npc.death_effect.conditions_source == null || npc.death_effect.conditions_source.isEmpty()) { - deathSourceConditionsPane.collapse(); - } - deathEffectPane.add(deathSourceConditionsPane, JideBoxLayout.FIX); - combatTraitPane.add(deathEffectPane, JideBoxLayout.FIX); - - - pane.add(combatTraitPane, JideBoxLayout.FIX); - } - - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitSourceConditionBox != null) { - removeElementListener(hitSourceConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); - - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); - - updateHitSourceTimedConditionWidgets(condition); - - hitSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); - } - }); - hitSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); - } - }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); - } - }); - - hitSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); - } - }); - hitSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); - - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); - } - - - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitTargetConditionBox != null) { - removeElementListener(hitTargetConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitTargetConditionClear, JideBoxLayout.FIX); - hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitTargetConditionApply); - radioEffectGroup.add(hitTargetConditionClear); - radioEffectGroup.add(hitTargetConditionImmunity); - - hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitTargetConditionTimed); - radioDurationGroup.add(hitTargetConditionForever); - - updateHitTargetTimedConditionWidgets(condition); - - hitTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); - } - }); - hitTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); - } - }); - hitTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); - } - }); - - hitTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); - } - }); - hitTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitTargetConditionClear.setSelected(clear); - hitTargetConditionApply.setSelected(!clear && !immunity); - hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitTargetConditionImmunity.setSelected(immunity); - - hitTargetConditionTimed.setSelected(!forever); - hitTargetConditionTimed.setEnabled(!clear); - hitTargetConditionDuration.setEnabled(!clear && !forever); - hitTargetConditionForever.setSelected(forever); - hitTargetConditionForever.setEnabled(!clear); - } - - - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedSourceConditionBox != null) { - removeElementListener(hitReceivedSourceConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); - hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); - hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedSourceConditionApply); - radioEffectGroup.add(hitReceivedSourceConditionClear); - radioEffectGroup.add(hitReceivedSourceConditionImmunity); - - hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); - hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedSourceConditionTimed); - radioDurationGroup.add(hitReceivedSourceConditionForever); - - updateHitReceivedSourceTimedConditionWidgets(condition); - - hitReceivedSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); - } - }); - hitReceivedSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); - } - }); - hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); - } - }); - - hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); - } - }); - hitReceivedSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedSourceConditionClear.setSelected(clear); - hitReceivedSourceConditionApply.setSelected(!clear && !immunity); - hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedSourceConditionImmunity.setSelected(immunity); - - hitReceivedSourceConditionTimed.setSelected(!forever); - hitReceivedSourceConditionTimed.setEnabled(!clear); - hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); - hitReceivedSourceConditionForever.setSelected(forever); - hitReceivedSourceConditionForever.setEnabled(!clear); - } - - - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedTargetConditionBox != null) { - removeElementListener(hitReceivedTargetConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); - hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); - hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedTargetConditionApply); - radioEffectGroup.add(hitReceivedTargetConditionClear); - radioEffectGroup.add(hitReceivedTargetConditionImmunity); - - hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); - hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedTargetConditionTimed); - radioDurationGroup.add(hitReceivedTargetConditionForever); - - updateHitReceivedTargetTimedConditionWidgets(condition); - - hitReceivedTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); - } - }); - hitReceivedTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); - } - }); - hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); - } - }); - - hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); - } - }); - hitReceivedTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedTargetConditionClear.setSelected(clear); - hitReceivedTargetConditionApply.setSelected(!clear && !immunity); - hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedTargetConditionImmunity.setSelected(immunity); - - hitReceivedTargetConditionTimed.setSelected(!forever); - hitReceivedTargetConditionTimed.setEnabled(!clear); - hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); - hitReceivedTargetConditionForever.setSelected(forever); - hitReceivedTargetConditionForever.setEnabled(!clear); - } - - public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (deathSourceConditionBox != null) { - removeElementListener(deathSourceConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - deathSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - deathSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - deathSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(deathSourceConditionClear, JideBoxLayout.FIX); - deathSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(deathSourceConditionApply, JideBoxLayout.FIX); - deathSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - deathSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(deathSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(deathSourceConditionApply); - radioEffectGroup.add(deathSourceConditionClear); - radioEffectGroup.add(deathSourceConditionImmunity); - - deathSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(deathSourceConditionTimed, JideBoxLayout.FIX); - deathSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - deathSourceConditionForever = new JRadioButton("Forever"); - pane.add(deathSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(deathSourceConditionTimed); - radioDurationGroup.add(deathSourceConditionForever); - - updateDeathSourceTimedConditionWidgets(condition); - - deathSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionClear, new Boolean(deathSourceConditionClear.isSelected())); - } - }); - deathSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionApply, new Boolean(deathSourceConditionApply.isSelected())); - } - }); - deathSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionImmunity, new Boolean(deathSourceConditionImmunity.isSelected())); - } - }); - - deathSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionTimed, new Boolean(deathSourceConditionTimed.isSelected())); - } - }); - deathSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionForever, new Boolean(deathSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateDeathSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - deathSourceConditionClear.setSelected(clear); - deathSourceConditionApply.setSelected(!clear && !immunity); - deathSourceConditionMagnitude.setEnabled(!clear && !immunity); - deathSourceConditionImmunity.setSelected(immunity); - - deathSourceConditionTimed.setSelected(!forever); - deathSourceConditionTimed.setEnabled(!clear); - deathSourceConditionDuration.setEnabled(!clear && !forever); - deathSourceConditionForever.setSelected(forever); - deathSourceConditionForever.setEnabled(!clear); - } - - public static class TargetTimedConditionsListModel extends CustomListModel { - public TargetTimedConditionsListModel(Common.HitEffect effect) { - super(effect); - } - - @Override - protected List getItems() { - return source.conditions_target; - } - - @Override - protected void setItems(List items) { - source.conditions_target = items; - } - } - - public static class SourceTimedConditionsListModel extends CustomListModel { - public SourceTimedConditionsListModel(Common.DeathEffect effect) { - super(effect); - } - - @Override - protected List getItems() { - return source.conditions_source; - } - - @Override - protected void setItems(List items) { - source.conditions_source = items; - } - } - - public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; - - if (effect.condition != null) { - - boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); - boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); - boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; - - if (clear) { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to clear actor condition "+effect.condition.getDesc()); - } else if (immunity) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText(effect.chance+"% chances to give immunity to "+effect.condition.getDesc()+(forever ? " forever" : " for "+effect.duration+" rounds")); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude+(forever ? " forever" : " for "+effect.duration+" rounds")); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - - public static boolean isNull(Common.HitEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - public static boolean isNull(Common.HitReceivedEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.ap_boost_min_target != null) return false; - if (effect.ap_boost_max_target != null) return false; - if (effect.hp_boost_min_target != null) return false; - if (effect.hp_boost_max_target != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - public static boolean isNull(Common.DeathEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - return true; - } - - public class NPCFieldUpdater implements FieldUpdateListener { - - @Override - public void valueChanged(JComponent source, Object value) { - NPC npc = (NPC)target; - boolean updateHit, updateHitReceived, updateDeath; - updateHit = updateHitReceived = updateDeath = false; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - npc.id = (String) value; - NPCEditor.this.name = npc.getDesc(); - npc.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(NPCEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - npc.name = (String) value; - NPCEditor.this.name = npc.getDesc(); - npc.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(NPCEditor.this); - } else if (source == npcIcon) { - npc.icon_id = (String) value; - npc.childrenChanged(new ArrayList()); - NPCEditor.this.icon = new ImageIcon(npc.getProject().getIcon((String) value)); - ATContentStudio.frame.editorChanged(NPCEditor.this); - npcIcon.setIcon(new ImageIcon(npc.getProject().getImage((String) value))); - npcIcon.revalidate(); - npcIcon.repaint(); - } else if (source == spawnGroupField) { - npc.spawngroup_id = (String) value; - } else if (source == factionField) { - npc.faction_id = (String) value; - } else if (source == dialogueBox) { - if (npc.dialogue != null) { - npc.dialogue.removeBacklink(npc); - } - npc.dialogue = (Dialogue) value; - if (npc.dialogue != null) { - npc.dialogue_id =npc.dialogue.id; - npc.dialogue.addBacklink(npc); - } else { - npc.dialogue_id = null; - } - reloadGraphView(npc); - } else if (source == droplistBox) { - if (npc.droplist != null) { - npc.droplist.removeBacklink(npc); - } - npc.droplist = (Droplist) value; - if (npc.droplist != null) { - npc.droplist_id = npc.droplist.id; - npc.droplist.addBacklink(npc); - } else { - npc.droplist_id = null; - } - } else if (source == monsterClassBox) { - npc.monster_class = (NPC.MonsterClass) value; - } else if (source == uniqueBox) { - npc.unique = (Integer) value; - } else if (source == moveTypeBox) { - npc.movement_type = (NPC.MovementType) value; - } else if (source == maxHP) { - npc.max_hp = (Integer) value; - } else if (source == maxAP) { - npc.max_ap = (Integer) value; - } else if (source == moveCost) { - npc.move_cost = (Integer) value; - } else if (source == atkDmgMin) { - npc.attack_damage_min = (Integer) value; - } else if (source == atkDmgMax) { - npc.attack_damage_max = (Integer) value; - } else if (source == atkCost) { - npc.attack_cost = (Integer) value; - } else if (source == atkChance) { - npc.attack_chance = (Integer) value; - } else if (source == critSkill) { - npc.critical_skill = (Integer) value; - } else if (source == critMult) { - npc.critical_multiplier = (Double) value; - } else if (source == blockChance) { - npc.block_chance = (Integer) value; - } else if (source == dmgRes) { - npc.damage_resistance = (Integer) value; - } else if (source == hitEffectHPMin) { - hitEffect.hp_boost_min = (Integer) value; - updateHit = true; - } else if (source == hitEffectHPMax) { - hitEffect.hp_boost_max = (Integer) value; - updateHit = true; - } else if (source == hitEffectAPMin) { - hitEffect.ap_boost_min = (Integer) value; - updateHit = true; - } else if (source == hitEffectAPMax) { - hitEffect.ap_boost_max = (Integer) value; - updateHit = true; - } else if (source == hitSourceConditionsList) { - updateHit = true; - } else if (source == hitSourceConditionBox) { - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.removeBacklink(npc); - } - selectedHitEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.addBacklink(npc); - selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; - } else { - selectedHitEffectSourceCondition.condition_id = null; - } - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - } else if (source == hitSourceConditionClear && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionApply && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionImmunity && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionMagnitude) { - selectedHitEffectSourceCondition.magnitude = (Integer) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionTimed && (Boolean) value) { - selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionForever && (Boolean) value) { - selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionDuration) { - selectedHitEffectSourceCondition.duration = (Integer) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionChance) { - selectedHitEffectSourceCondition.chance = (Double) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - } else if (source == hitTargetConditionsList) { - updateHit = true; - } else if (source == hitTargetConditionBox) { - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition.removeBacklink(npc); - } - selectedHitEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; - selectedHitEffectTargetCondition.condition.addBacklink(npc); - } else { - selectedHitEffectTargetCondition.condition_id = null; - } - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - } else if (source == hitTargetConditionClear && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionApply && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionImmunity && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionMagnitude) { - selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionTimed && (Boolean) value) { - selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionForever && (Boolean) value) { - selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionDuration) { - selectedHitEffectTargetCondition.duration = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionChance) { - selectedHitEffectTargetCondition.chance = (Double) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - } else if (source == hitReceivedEffectHPMin) { - hitReceivedEffect.hp_boost_min = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMax) { - hitReceivedEffect.hp_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMin) { - hitReceivedEffect.ap_boost_min = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMax) { - hitReceivedEffect.ap_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMinTarget) { - hitReceivedEffect.hp_boost_min_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMaxTarget) { - hitReceivedEffect.hp_boost_max_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMinTarget) { - hitReceivedEffect.ap_boost_min_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMaxTarget) { - hitReceivedEffect.ap_boost_max_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionBox) { - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.removeBacklink(npc); - } - selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.addBacklink(npc); - selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; - } else { - selectedHitReceivedEffectSourceCondition.condition_id = null; - } - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = null; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionMagnitude) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionDuration) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionChance) { - selectedHitReceivedEffectSourceCondition.chance = (Double) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - } else if (source == hitReceivedTargetConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionBox) { - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition.removeBacklink(npc); - } - selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; - selectedHitReceivedEffectTargetCondition.condition.addBacklink(npc); - } else { - selectedHitReceivedEffectTargetCondition.condition_id = null; - } - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = null; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionMagnitude) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionDuration) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionChance) { - selectedHitReceivedEffectTargetCondition.chance = (Double) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - } else if (source == deathEffectHPMin) { - deathEffect.hp_boost_min = (Integer) value; - updateDeath = true; - } else if (source == deathEffectHPMax) { - deathEffect.hp_boost_max = (Integer) value; - updateDeath = true; - } else if (source == deathEffectAPMin) { - deathEffect.ap_boost_min = (Integer) value; - updateDeath = true; - } else if (source == deathEffectAPMax) { - deathEffect.ap_boost_max = (Integer) value; - updateDeath = true; - } else if (source == deathSourceConditionsList) { - updateDeath = true; - } else if (source == deathSourceConditionBox) { - if (selectedDeathEffectSourceCondition.condition != null) { - selectedDeathEffectSourceCondition.condition.removeBacklink(npc); - } - selectedDeathEffectSourceCondition.condition = (ActorCondition) value; - if (selectedDeathEffectSourceCondition.condition != null) { - selectedDeathEffectSourceCondition.condition.addBacklink(npc); - selectedDeathEffectSourceCondition.condition_id = selectedDeathEffectSourceCondition.condition.id; - } else { - selectedDeathEffectSourceCondition.condition_id = null; - } - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - } else if (source == deathSourceConditionClear && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedDeathEffectSourceCondition.duration = null; - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionApply && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = (Integer) deathSourceConditionMagnitude.getValue(); - selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionImmunity && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionMagnitude) { - selectedDeathEffectSourceCondition.magnitude = (Integer) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionTimed && (Boolean) value) { - selectedDeathEffectSourceCondition.duration = (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionForever && (Boolean) value) { - selectedDeathEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionDuration) { - selectedDeathEffectSourceCondition.duration = (Integer) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionChance) { - selectedDeathEffectSourceCondition.chance = (Double) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - } - - if (updateHit) { - if (isNull(hitEffect)) { - npc.hit_effect = null; - } else { - npc.hit_effect = hitEffect; - } - } - if (updateHitReceived) { - if (isNull(hitReceivedEffect)) { - npc.hit_received_effect = null; - } else { - npc.hit_received_effect = hitReceivedEffect; - } - } - if (updateDeath) { - if (isNull(deathEffect)) { - npc.death_effect = null; - } else { - npc.death_effect = deathEffect; - } - } - - experienceField.setValue(npc.getMonsterExperience()); - - if (npc.state != GameDataElement.State.modified) { - npc.state = GameDataElement.State.modified; - NPCEditor.this.name = npc.getDesc(); - npc.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(NPCEditor.this); - } - updateJsonViewText(npc.toJsonString()); - - } - - } - - -} +package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import javax.swing.ButtonGroup; +import javax.swing.DefaultListCellRenderer; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTextField; +import javax.swing.ListModel; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; +import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; +import com.jidesoft.swing.JideBoxLayout; + +public class NPCEditor extends JSONElementEditor { + + private static final long serialVersionUID = 4001483665523721800L; + + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; + private static final String dialogue_tree_id = "Dialogue Tree"; + + private Common.TimedConditionEffect selectedHitEffectSourceCondition; + private Common.TimedConditionEffect selectedHitEffectTargetCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; + private Common.TimedConditionEffect selectedDeathEffectSourceCondition; + + private JButton npcIcon; + private JTextField idField; + private JTextField nameField; + private JTextField spawnGroupField; + private JTextField factionField; + private JSpinner experienceField; + private MyComboBox dialogueBox; + private MyComboBox droplistBox; + @SuppressWarnings("rawtypes") + private JComboBox monsterClassBox; + private IntegerBasedCheckBox uniqueBox; + @SuppressWarnings("rawtypes") + private JComboBox moveTypeBox; + + private CollapsiblePanel combatTraitPane; + private JSpinner maxHP; + private JSpinner maxAP; + private JSpinner moveCost; + private JSpinner atkDmgMin; + private JSpinner atkDmgMax; + private JSpinner atkCost; + private JSpinner atkChance; + private JSpinner critSkill; + private JSpinner critMult; + private JSpinner blockChance; + private JSpinner dmgRes; + + private Common.HitEffect hitEffect; + private CollapsiblePanel hitEffectPane; + private JSpinner hitEffectHPMin; + private JSpinner hitEffectHPMax; + private JSpinner hitEffectAPMin; + private JSpinner hitEffectAPMax; + + private SourceTimedConditionsListModel hitSourceConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitSourceConditionsList; + private MyComboBox hitSourceConditionBox; + private JSpinner hitSourceConditionChance; + private JRadioButton hitSourceConditionClear; + private JRadioButton hitSourceConditionApply; + private JRadioButton hitSourceConditionImmunity; + private JSpinner hitSourceConditionMagnitude; + private JRadioButton hitSourceConditionTimed; + private JRadioButton hitSourceConditionForever; + private JSpinner hitSourceConditionDuration; + + private TargetTimedConditionsListModel hitTargetConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitTargetConditionsList; + private MyComboBox hitTargetConditionBox; + private JSpinner hitTargetConditionChance; + private JRadioButton hitTargetConditionClear; + private JRadioButton hitTargetConditionApply; + private JRadioButton hitTargetConditionImmunity; + private JSpinner hitTargetConditionMagnitude; + private JRadioButton hitTargetConditionTimed; + private JRadioButton hitTargetConditionForever; + private JSpinner hitTargetConditionDuration; + + private Common.HitReceivedEffect hitReceivedEffect; + private CollapsiblePanel hitReceivedEffectPane; + private JSpinner hitReceivedEffectHPMin; + private JSpinner hitReceivedEffectHPMax; + private JSpinner hitReceivedEffectAPMin; + private JSpinner hitReceivedEffectAPMax; + private JSpinner hitReceivedEffectHPMinTarget; + private JSpinner hitReceivedEffectHPMaxTarget; + private JSpinner hitReceivedEffectAPMinTarget; + private JSpinner hitReceivedEffectAPMaxTarget; + + private SourceTimedConditionsListModel hitReceivedSourceConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedSourceConditionsList; + private MyComboBox hitReceivedSourceConditionBox; + private JSpinner hitReceivedSourceConditionChance; + private JRadioButton hitReceivedSourceConditionClear; + private JRadioButton hitReceivedSourceConditionApply; + private JRadioButton hitReceivedSourceConditionImmunity; + private JSpinner hitReceivedSourceConditionMagnitude; + private JRadioButton hitReceivedSourceConditionTimed; + private JRadioButton hitReceivedSourceConditionForever; + private JSpinner hitReceivedSourceConditionDuration; + + private TargetTimedConditionsListModel hitReceivedTargetConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedTargetConditionsList; + private MyComboBox hitReceivedTargetConditionBox; + private JSpinner hitReceivedTargetConditionChance; + private JRadioButton hitReceivedTargetConditionClear; + private JRadioButton hitReceivedTargetConditionApply; + private JRadioButton hitReceivedTargetConditionImmunity; + private JSpinner hitReceivedTargetConditionMagnitude; + private JRadioButton hitReceivedTargetConditionTimed; + private JRadioButton hitReceivedTargetConditionForever; + private JSpinner hitReceivedTargetConditionDuration; + + private Common.DeathEffect deathEffect; + private CollapsiblePanel deathEffectPane; + private JSpinner deathEffectHPMin; + private JSpinner deathEffectHPMax; + private JSpinner deathEffectAPMin; + private JSpinner deathEffectAPMax; + + private SourceTimedConditionsListModel deathSourceConditionsListModel; + @SuppressWarnings("rawtypes") + private JList deathSourceConditionsList; + private MyComboBox deathSourceConditionBox; + private JSpinner deathSourceConditionChance; + private JRadioButton deathSourceConditionClear; + private JRadioButton deathSourceConditionApply; + private JRadioButton deathSourceConditionImmunity; + private JSpinner deathSourceConditionMagnitude; + private JRadioButton deathSourceConditionTimed; + private JRadioButton deathSourceConditionForever; + private JSpinner deathSourceConditionDuration; + + private JPanel dialogueGraphPane; + private DialogueGraphView dialogueGraphView; + + public NPCEditor(NPC npc) { + super(npc, npc.getDesc(), npc.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + if (npc.dialogue != null) { + createDialogueGraphView(npc); + addEditorTab(dialogue_tree_id, dialogueGraphPane); + } + } + + public JPanel createDialogueGraphView(final NPC npc) { + dialogueGraphPane = new JPanel(); + dialogueGraphPane.setLayout(new BorderLayout()); + + dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); + dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); + JButton reloadButton = new JButton("Refresh graph"); + buttonPane.add(reloadButton, JideBoxLayout.FIX); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + dialogueGraphPane.add(buttonPane, BorderLayout.NORTH); + + + reloadButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + reloadGraphView(npc); + } + }); + + return dialogueGraphPane; + } + + public void reloadGraphView(NPC npc) { + if (npc.dialogue != null) { + if (dialogueGraphPane != null) { + dialogueGraphPane.remove(dialogueGraphView); + dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); + dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); + dialogueGraphPane.revalidate(); + dialogueGraphPane.repaint(); + } else { + createDialogueGraphView(npc); + addEditorTab(dialogue_tree_id, dialogueGraphPane); + } + } else { + if (dialogueGraphPane != null) { + removeEditorTab(dialogue_tree_id); + dialogueGraphPane = null; + dialogueGraphView = null; + } + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public void insertFormViewDataField(JPanel pane) { + final NPC npc = (NPC) target; + + final FieldUpdateListener listener = new NPCFieldUpdater(); + + npcIcon = createButtonPane(pane, npc.getProject(), npc, NPC.class, npc.getImage(), Spritesheet.Category.monster, listener); + + idField = addTextField(pane, "Internal ID: ", npc.id, npc.writable, listener); + nameField = addTranslatableTextField(pane, "Display name: ", npc.name, npc.writable, listener); + spawnGroupField = addTextField(pane, "Spawn group ID: ", npc.spawngroup_id, npc.writable, listener); + factionField = addTextField(pane, "Faction ID: ", npc.faction_id, npc.writable, listener); + experienceField = addIntegerField(pane, "Experience reward: ", npc.getMonsterExperience(), false, false, listener); + dialogueBox = addDialogueBox(pane, npc.getProject(), "Initial phrase: ", npc.dialogue, npc.writable, listener); + droplistBox = addDroplistBox(pane, npc.getProject(), "Droplist / Shop inventory: ", npc.droplist, npc.writable, listener); + monsterClassBox = addEnumValueBox(pane, "Monster class: ", NPC.MonsterClass.values(), npc.monster_class, npc.writable, listener); + uniqueBox = addIntegerBasedCheckBox(pane, "Unique", npc.unique, npc.writable, listener); + moveTypeBox = addEnumValueBox(pane, "Movement type: ", NPC.MovementType.values(), npc.movement_type, npc.writable, listener); + combatTraitPane = new CollapsiblePanel("Combat traits: "); + combatTraitPane.setLayout(new JideBoxLayout(combatTraitPane, JideBoxLayout.PAGE_AXIS, 6)); + maxHP = addIntegerField(combatTraitPane, "Max HP: ", npc.max_hp, 1, false, npc.writable, listener); + maxAP = addIntegerField(combatTraitPane, "Max AP: ", npc.max_ap, 10, false, npc.writable, listener); + moveCost = addIntegerField(combatTraitPane, "Move cost: ", npc.move_cost, 10, false, npc.writable, listener); + atkDmgMin = addIntegerField(combatTraitPane, "Attack Damage min: ", npc.attack_damage_min, false, npc.writable, listener); + atkDmgMax = addIntegerField(combatTraitPane, "Attack Damage max: ", npc.attack_damage_max, false, npc.writable, listener); + atkCost = addIntegerField(combatTraitPane, "Attack cost: ", npc.attack_cost, 10, false, npc.writable, listener); + atkChance = addIntegerField(combatTraitPane, "Attack chance: ", npc.attack_chance, false, npc.writable, listener); + critSkill = addIntegerField(combatTraitPane, "Critical skill: ", npc.critical_skill, false, npc.writable, listener); + critMult = addDoubleField(combatTraitPane, "Critical multiplier: ", npc.critical_multiplier, npc.writable, listener); + blockChance = addIntegerField(combatTraitPane, "Block chance: ", npc.block_chance, false, npc.writable, listener); + dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); + hitEffectPane = new CollapsiblePanel("Effect on every hit: "); + hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.hit_effect == null) { + hitEffect = new Common.HitEffect(); + } else { + hitEffect = npc.hit_effect; + } + hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); + hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); + hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); + hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); + + CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); + hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); + hitSourceConditionsList = new JList(hitSourceConditionsListModel); + hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); + final JPanel hitSourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); + updateHitSourceTimedConditionEditorPane(hitSourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitSourceConditionsListModel.addItem(condition); + hitSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectSourceCondition != null) { + hitSourceConditionsListModel.removeItem(selectedHitEffectSourceCondition); + selectedHitEffectSourceCondition = null; + hitSourceConditionsList.clearSelection(); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsPane.add(hitSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { + hitSourceConditionsPane.collapse(); + } + hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); + hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); + hitTargetConditionsList = new JList(hitTargetConditionsListModel); + hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); + final JPanel hitTargetTimedConditionsEditorPane = new JPanel(); + final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); + updateHitTargetTimedConditionEditorPane(hitTargetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitTargetConditionsListModel.addItem(condition); + hitTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectTargetCondition != null) { + hitTargetConditionsListModel.removeItem(selectedHitEffectTargetCondition); + selectedHitEffectTargetCondition = null; + hitTargetConditionsList.clearSelection(); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsPane.add(hitTargetTimedConditionsEditorPane, JideBoxLayout.FIX); + hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); + if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { + hitTargetConditionsPane.collapse(); + } + combatTraitPane.add(hitEffectPane, JideBoxLayout.FIX); + + hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); + hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.hit_received_effect == null) { + hitReceivedEffect = new Common.HitReceivedEffect(); + } else { + hitReceivedEffect = npc.hit_received_effect; + } + hitReceivedEffectHPMin = addIntegerField(hitReceivedEffectPane, "NPC HP bonus min: ", hitReceivedEffect.hp_boost_min, true, npc.writable, listener); + hitReceivedEffectHPMax = addIntegerField(hitReceivedEffectPane, "NPC HP bonus max: ", hitReceivedEffect.hp_boost_max, true, npc.writable, listener); + hitReceivedEffectAPMin = addIntegerField(hitReceivedEffectPane, "NPC AP bonus min: ", hitReceivedEffect.ap_boost_min, true, npc.writable, listener); + hitReceivedEffectAPMax = addIntegerField(hitReceivedEffectPane, "NPC AP bonus max: ", hitReceivedEffect.ap_boost_max, true, npc.writable, listener); + hitReceivedEffectHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, npc.writable, listener); + hitReceivedEffectHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, npc.writable, listener); + hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, npc.writable, listener); + hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, npc.writable, listener); + + CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to this NPC: "); + hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); + hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsListModel); + hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); + updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedSourceConditionsListModel.addItem(condition); + hitReceivedSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectSourceCondition != null) { + hitReceivedSourceConditionsListModel.removeItem(selectedHitReceivedEffectSourceCondition); + selectedHitReceivedEffectSourceCondition = null; + hitReceivedSourceConditionsList.clearSelection(); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_source == null || npc.hit_received_effect.conditions_source.isEmpty()) { + hitReceivedSourceConditionsPane.collapse(); + } + hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); + hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); + hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsListModel); + hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); + updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedTargetConditionsListModel.addItem(condition); + hitReceivedTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectTargetCondition != null) { + hitReceivedTargetConditionsListModel.removeItem(selectedHitReceivedEffectTargetCondition); + selectedHitReceivedEffectTargetCondition = null; + hitReceivedTargetConditionsList.clearSelection(); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); + hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); + if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_target == null || npc.hit_received_effect.conditions_target.isEmpty()) { + hitReceivedTargetConditionsPane.collapse(); + } + combatTraitPane.add(hitReceivedEffectPane, JideBoxLayout.FIX); + + deathEffectPane = new CollapsiblePanel("Effect when killed: "); + deathEffectPane.setLayout(new JideBoxLayout(deathEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.death_effect == null) { + deathEffect = new Common.DeathEffect(); + } else { + deathEffect = npc.death_effect; + } + deathEffectHPMin = addIntegerField(deathEffectPane, "Killer HP bonus min: ", deathEffect.hp_boost_min, true, npc.writable, listener); + deathEffectHPMax = addIntegerField(deathEffectPane, "Killer HP bonus max: ", deathEffect.hp_boost_max, true, npc.writable, listener); + deathEffectAPMin = addIntegerField(deathEffectPane, "Killer AP bonus min: ", deathEffect.ap_boost_min, true, npc.writable, listener); + deathEffectAPMax = addIntegerField(deathEffectPane, "Killer AP bonus max: ", deathEffect.ap_boost_max, true, npc.writable, listener); + + CollapsiblePanel deathSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the killer: "); + deathSourceConditionsPane.setLayout(new JideBoxLayout(deathSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); + deathSourceConditionsList = new JList(deathSourceConditionsListModel); + deathSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + deathSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + deathSourceConditionsPane.add(new JScrollPane(deathSourceConditionsList), JideBoxLayout.FIX); + final JPanel deathSourceTimedConditionsEditorPane = new JPanel(); + final JButton createDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + deathSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedDeathEffectSourceCondition = (Common.TimedConditionEffect) deathSourceConditionsList.getSelectedValue(); + updateDeathSourceTimedConditionEditorPane(deathSourceTimedConditionsEditorPane, selectedDeathEffectSourceCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createDeathSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + deathSourceConditionsListModel.addItem(condition); + deathSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteDeathSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedDeathEffectSourceCondition != null) { + deathSourceConditionsListModel.removeItem(selectedDeathEffectSourceCondition); + selectedDeathEffectSourceCondition = null; + deathSourceConditionsList.clearSelection(); + listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createDeathSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteDeathSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + deathSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + deathSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(deathSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + deathSourceConditionsPane.add(deathSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (npc.death_effect == null || npc.death_effect.conditions_source == null || npc.death_effect.conditions_source.isEmpty()) { + deathSourceConditionsPane.collapse(); + } + deathEffectPane.add(deathSourceConditionsPane, JideBoxLayout.FIX); + combatTraitPane.add(deathEffectPane, JideBoxLayout.FIX); + + + pane.add(combatTraitPane, JideBoxLayout.FIX); + } + + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitSourceConditionBox != null) { + removeElementListener(hitSourceConditionBox); + } + + boolean writable = ((NPC)target).writable; + Project proj = ((NPC)target).getProject(); + + hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitSourceConditionClear, JideBoxLayout.FIX); + hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitSourceConditionApply, JideBoxLayout.FIX); + hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitSourceConditionApply); + radioEffectGroup.add(hitSourceConditionClear); + radioEffectGroup.add(hitSourceConditionImmunity); + + hitSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); + hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitSourceConditionTimed); + radioDurationGroup.add(hitSourceConditionForever); + + updateHitSourceTimedConditionWidgets(condition); + + hitSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + } + }); + hitSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + } + }); + hitSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + } + }); + + hitSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + } + }); + hitSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitSourceConditionClear.setSelected(clear); + hitSourceConditionApply.setSelected(!clear && !immunity); + hitSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitSourceConditionImmunity.setSelected(immunity); + + hitSourceConditionTimed.setSelected(!forever); + hitSourceConditionTimed.setEnabled(!clear); + hitSourceConditionDuration.setEnabled(!clear && !forever); + hitSourceConditionForever.setSelected(forever); + hitSourceConditionForever.setEnabled(!clear); + } + + + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitTargetConditionBox != null) { + removeElementListener(hitTargetConditionBox); + } + + boolean writable = ((NPC)target).writable; + Project proj = ((NPC)target).getProject(); + + hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitTargetConditionClear, JideBoxLayout.FIX); + hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitTargetConditionApply, JideBoxLayout.FIX); + hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitTargetConditionApply); + radioEffectGroup.add(hitTargetConditionClear); + radioEffectGroup.add(hitTargetConditionImmunity); + + hitTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); + hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitTargetConditionTimed); + radioDurationGroup.add(hitTargetConditionForever); + + updateHitTargetTimedConditionWidgets(condition); + + hitTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + } + }); + hitTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + } + }); + hitTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + } + }); + + hitTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + } + }); + hitTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitTargetConditionClear.setSelected(clear); + hitTargetConditionApply.setSelected(!clear && !immunity); + hitTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitTargetConditionImmunity.setSelected(immunity); + + hitTargetConditionTimed.setSelected(!forever); + hitTargetConditionTimed.setEnabled(!clear); + hitTargetConditionDuration.setEnabled(!clear && !forever); + hitTargetConditionForever.setSelected(forever); + hitTargetConditionForever.setEnabled(!clear); + } + + + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedSourceConditionBox != null) { + removeElementListener(hitReceivedSourceConditionBox); + } + + boolean writable = ((NPC)target).writable; + Project proj = ((NPC)target).getProject(); + + hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); + hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); + hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedSourceConditionApply); + radioEffectGroup.add(hitReceivedSourceConditionClear); + radioEffectGroup.add(hitReceivedSourceConditionImmunity); + + hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); + hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedSourceConditionTimed); + radioDurationGroup.add(hitReceivedSourceConditionForever); + + updateHitReceivedSourceTimedConditionWidgets(condition); + + hitReceivedSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); + } + }); + hitReceivedSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); + } + }); + hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); + } + }); + + hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); + } + }); + hitReceivedSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedSourceConditionClear.setSelected(clear); + hitReceivedSourceConditionApply.setSelected(!clear && !immunity); + hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedSourceConditionImmunity.setSelected(immunity); + + hitReceivedSourceConditionTimed.setSelected(!forever); + hitReceivedSourceConditionTimed.setEnabled(!clear); + hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); + hitReceivedSourceConditionForever.setSelected(forever); + hitReceivedSourceConditionForever.setEnabled(!clear); + } + + + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedTargetConditionBox != null) { + removeElementListener(hitReceivedTargetConditionBox); + } + + boolean writable = ((NPC)target).writable; + Project proj = ((NPC)target).getProject(); + + hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); + hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); + hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedTargetConditionApply); + radioEffectGroup.add(hitReceivedTargetConditionClear); + radioEffectGroup.add(hitReceivedTargetConditionImmunity); + + hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); + hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedTargetConditionTimed); + radioDurationGroup.add(hitReceivedTargetConditionForever); + + updateHitReceivedTargetTimedConditionWidgets(condition); + + hitReceivedTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); + } + }); + hitReceivedTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); + } + }); + hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); + } + }); + + hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); + } + }); + hitReceivedTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedTargetConditionClear.setSelected(clear); + hitReceivedTargetConditionApply.setSelected(!clear && !immunity); + hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedTargetConditionImmunity.setSelected(immunity); + + hitReceivedTargetConditionTimed.setSelected(!forever); + hitReceivedTargetConditionTimed.setEnabled(!clear); + hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); + hitReceivedTargetConditionForever.setSelected(forever); + hitReceivedTargetConditionForever.setEnabled(!clear); + } + + public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (deathSourceConditionBox != null) { + removeElementListener(deathSourceConditionBox); + } + + boolean writable = ((NPC)target).writable; + Project proj = ((NPC)target).getProject(); + + deathSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + deathSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + deathSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(deathSourceConditionClear, JideBoxLayout.FIX); + deathSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(deathSourceConditionApply, JideBoxLayout.FIX); + deathSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + deathSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(deathSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(deathSourceConditionApply); + radioEffectGroup.add(deathSourceConditionClear); + radioEffectGroup.add(deathSourceConditionImmunity); + + deathSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(deathSourceConditionTimed, JideBoxLayout.FIX); + deathSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + deathSourceConditionForever = new JRadioButton("Forever"); + pane.add(deathSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(deathSourceConditionTimed); + radioDurationGroup.add(deathSourceConditionForever); + + updateDeathSourceTimedConditionWidgets(condition); + + deathSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionClear, new Boolean(deathSourceConditionClear.isSelected())); + } + }); + deathSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionApply, new Boolean(deathSourceConditionApply.isSelected())); + } + }); + deathSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionImmunity, new Boolean(deathSourceConditionImmunity.isSelected())); + } + }); + + deathSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionTimed, new Boolean(deathSourceConditionTimed.isSelected())); + } + }); + deathSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionForever, new Boolean(deathSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateDeathSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + deathSourceConditionClear.setSelected(clear); + deathSourceConditionApply.setSelected(!clear && !immunity); + deathSourceConditionMagnitude.setEnabled(!clear && !immunity); + deathSourceConditionImmunity.setSelected(immunity); + + deathSourceConditionTimed.setSelected(!forever); + deathSourceConditionTimed.setEnabled(!clear); + deathSourceConditionDuration.setEnabled(!clear && !forever); + deathSourceConditionForever.setSelected(forever); + deathSourceConditionForever.setEnabled(!clear); + } + + public static class TargetTimedConditionsListModel extends OrderedListenerListModel { + public TargetTimedConditionsListModel(Common.HitEffect effect) { + super(effect); + } + + @Override + protected List getItems() { + return source.conditions_target; + } + + @Override + protected void setItems(List items) { + source.conditions_target = items; + } + } + + public static class SourceTimedConditionsListModel extends OrderedListenerListModel { + public SourceTimedConditionsListModel(Common.DeathEffect effect) { + super(effect); + } + + @Override + protected List getItems() { + return source.conditions_source; + } + + @Override + protected void setItems(List items) { + source.conditions_source = items; + } + } + + public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel)c); + Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; + + if (effect.condition != null) { + + boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); + boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); + boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; + + if (clear) { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance+"% chances to clear actor condition "+effect.condition.getDesc()); + } else if (immunity) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText(effect.chance+"% chances to give immunity to "+effect.condition.getDesc()+(forever ? " forever" : " for "+effect.duration+" rounds")); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance+"% chances to give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude+(forever ? " forever" : " for "+effect.duration+" rounds")); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } + + public static boolean isNull(Common.HitEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + public static boolean isNull(Common.HitReceivedEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.ap_boost_min_target != null) return false; + if (effect.ap_boost_max_target != null) return false; + if (effect.hp_boost_min_target != null) return false; + if (effect.hp_boost_max_target != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + public static boolean isNull(Common.DeathEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + return true; + } + + public class NPCFieldUpdater implements FieldUpdateListener { + + @Override + public void valueChanged(JComponent source, Object value) { + NPC npc = (NPC)target; + boolean updateHit, updateHitReceived, updateDeath; + updateHit = updateHitReceived = updateDeath = false; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + npc.id = (String) value; + NPCEditor.this.name = npc.getDesc(); + npc.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(NPCEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + npc.name = (String) value; + NPCEditor.this.name = npc.getDesc(); + npc.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(NPCEditor.this); + } else if (source == npcIcon) { + npc.icon_id = (String) value; + npc.childrenChanged(new ArrayList()); + NPCEditor.this.icon = new ImageIcon(npc.getProject().getIcon((String) value)); + ATContentStudio.frame.editorChanged(NPCEditor.this); + npcIcon.setIcon(new ImageIcon(npc.getProject().getImage((String) value))); + npcIcon.revalidate(); + npcIcon.repaint(); + } else if (source == spawnGroupField) { + npc.spawngroup_id = (String) value; + } else if (source == factionField) { + npc.faction_id = (String) value; + } else if (source == dialogueBox) { + if (npc.dialogue != null) { + npc.dialogue.removeBacklink(npc); + } + npc.dialogue = (Dialogue) value; + if (npc.dialogue != null) { + npc.dialogue_id =npc.dialogue.id; + npc.dialogue.addBacklink(npc); + } else { + npc.dialogue_id = null; + } + reloadGraphView(npc); + } else if (source == droplistBox) { + if (npc.droplist != null) { + npc.droplist.removeBacklink(npc); + } + npc.droplist = (Droplist) value; + if (npc.droplist != null) { + npc.droplist_id = npc.droplist.id; + npc.droplist.addBacklink(npc); + } else { + npc.droplist_id = null; + } + } else if (source == monsterClassBox) { + npc.monster_class = (NPC.MonsterClass) value; + } else if (source == uniqueBox) { + npc.unique = (Integer) value; + } else if (source == moveTypeBox) { + npc.movement_type = (NPC.MovementType) value; + } else if (source == maxHP) { + npc.max_hp = (Integer) value; + } else if (source == maxAP) { + npc.max_ap = (Integer) value; + } else if (source == moveCost) { + npc.move_cost = (Integer) value; + } else if (source == atkDmgMin) { + npc.attack_damage_min = (Integer) value; + } else if (source == atkDmgMax) { + npc.attack_damage_max = (Integer) value; + } else if (source == atkCost) { + npc.attack_cost = (Integer) value; + } else if (source == atkChance) { + npc.attack_chance = (Integer) value; + } else if (source == critSkill) { + npc.critical_skill = (Integer) value; + } else if (source == critMult) { + npc.critical_multiplier = (Double) value; + } else if (source == blockChance) { + npc.block_chance = (Integer) value; + } else if (source == dmgRes) { + npc.damage_resistance = (Integer) value; + } else if (source == hitEffectHPMin) { + hitEffect.hp_boost_min = (Integer) value; + updateHit = true; + } else if (source == hitEffectHPMax) { + hitEffect.hp_boost_max = (Integer) value; + updateHit = true; + } else if (source == hitEffectAPMin) { + hitEffect.ap_boost_min = (Integer) value; + updateHit = true; + } else if (source == hitEffectAPMax) { + hitEffect.ap_boost_max = (Integer) value; + updateHit = true; + } else if (source == hitSourceConditionsList) { + updateHit = true; + } else if (source == hitSourceConditionBox) { + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition.removeBacklink(npc); + } + selectedHitEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition.addBacklink(npc); + selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; + } else { + selectedHitEffectSourceCondition.condition_id = null; + } + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + } else if (source == hitSourceConditionClear && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = null; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionApply && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionImmunity && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionMagnitude) { + selectedHitEffectSourceCondition.magnitude = (Integer) value; + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionTimed && (Boolean) value) { + selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionForever && (Boolean) value) { + selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionDuration) { + selectedHitEffectSourceCondition.duration = (Integer) value; + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionChance) { + selectedHitEffectSourceCondition.chance = (Double) value; + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + } else if (source == hitTargetConditionsList) { + updateHit = true; + } else if (source == hitTargetConditionBox) { + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition.removeBacklink(npc); + } + selectedHitEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; + selectedHitEffectTargetCondition.condition.addBacklink(npc); + } else { + selectedHitEffectTargetCondition.condition_id = null; + } + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitTargetConditionClear && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = null; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionApply && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionImmunity && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionMagnitude) { + selectedHitEffectTargetCondition.magnitude = (Integer) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionTimed && (Boolean) value) { + selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionForever && (Boolean) value) { + selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionDuration) { + selectedHitEffectTargetCondition.duration = (Integer) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionChance) { + selectedHitEffectTargetCondition.chance = (Double) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitReceivedEffectHPMin) { + hitReceivedEffect.hp_boost_min = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectHPMax) { + hitReceivedEffect.hp_boost_max = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMin) { + hitReceivedEffect.ap_boost_min = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMax) { + hitReceivedEffect.ap_boost_max = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectHPMinTarget) { + hitReceivedEffect.hp_boost_min_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectHPMaxTarget) { + hitReceivedEffect.hp_boost_max_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMinTarget) { + hitReceivedEffect.ap_boost_min_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMaxTarget) { + hitReceivedEffect.ap_boost_max_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionBox) { + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition.removeBacklink(npc); + } + selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition.addBacklink(npc); + selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; + } else { + selectedHitReceivedEffectSourceCondition.condition_id = null; + } + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = null; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionMagnitude) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionDuration) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) value; + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionChance) { + selectedHitReceivedEffectSourceCondition.chance = (Double) value; + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + } else if (source == hitReceivedTargetConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionBox) { + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition.removeBacklink(npc); + } + selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; + selectedHitReceivedEffectTargetCondition.condition.addBacklink(npc); + } else { + selectedHitReceivedEffectTargetCondition.condition_id = null; + } + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = null; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionMagnitude) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionDuration) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) value; + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionChance) { + selectedHitReceivedEffectTargetCondition.chance = (Double) value; + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + } else if (source == deathEffectHPMin) { + deathEffect.hp_boost_min = (Integer) value; + updateDeath = true; + } else if (source == deathEffectHPMax) { + deathEffect.hp_boost_max = (Integer) value; + updateDeath = true; + } else if (source == deathEffectAPMin) { + deathEffect.ap_boost_min = (Integer) value; + updateDeath = true; + } else if (source == deathEffectAPMax) { + deathEffect.ap_boost_max = (Integer) value; + updateDeath = true; + } else if (source == deathSourceConditionsList) { + updateDeath = true; + } else if (source == deathSourceConditionBox) { + if (selectedDeathEffectSourceCondition.condition != null) { + selectedDeathEffectSourceCondition.condition.removeBacklink(npc); + } + selectedDeathEffectSourceCondition.condition = (ActorCondition) value; + if (selectedDeathEffectSourceCondition.condition != null) { + selectedDeathEffectSourceCondition.condition.addBacklink(npc); + selectedDeathEffectSourceCondition.condition_id = selectedDeathEffectSourceCondition.condition.id; + } else { + selectedDeathEffectSourceCondition.condition_id = null; + } + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } else if (source == deathSourceConditionClear && (Boolean) value) { + selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedDeathEffectSourceCondition.duration = null; + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionApply && (Boolean) value) { + selectedDeathEffectSourceCondition.magnitude = (Integer) deathSourceConditionMagnitude.getValue(); + selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); + if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedDeathEffectSourceCondition.duration = 1; + } + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionImmunity && (Boolean) value) { + selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); + if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedDeathEffectSourceCondition.duration = 1; + } + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionMagnitude) { + selectedDeathEffectSourceCondition.magnitude = (Integer) value; + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionTimed && (Boolean) value) { + selectedDeathEffectSourceCondition.duration = (Integer) deathSourceConditionDuration.getValue(); + if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedDeathEffectSourceCondition.duration = 1; + } + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionForever && (Boolean) value) { + selectedDeathEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionDuration) { + selectedDeathEffectSourceCondition.duration = (Integer) value; + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionChance) { + selectedDeathEffectSourceCondition.chance = (Double) value; + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } + + if (updateHit) { + if (isNull(hitEffect)) { + npc.hit_effect = null; + } else { + npc.hit_effect = hitEffect; + } + } + if (updateHitReceived) { + if (isNull(hitReceivedEffect)) { + npc.hit_received_effect = null; + } else { + npc.hit_received_effect = hitReceivedEffect; + } + } + if (updateDeath) { + if (isNull(deathEffect)) { + npc.death_effect = null; + } else { + npc.death_effect = deathEffect; + } + } + + experienceField.setValue(npc.getMonsterExperience()); + + if (npc.state != GameDataElement.State.modified) { + npc.state = GameDataElement.State.modified; + NPCEditor.this.name = npc.getDesc(); + npc.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(NPCEditor.this); + } + updateJsonViewText(npc.toJsonString()); + + } + + } + + +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java index 1b62bea..a5cc0b3 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java @@ -1,276 +1,276 @@ -package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; - -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.Common; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; -import com.gpl.rpg.atcontentstudio.ui.*; -import com.jidesoft.swing.JideBoxLayout; - -public class QuestEditor extends JSONElementEditor { - - private static final long serialVersionUID = 5701667955210615366L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - - private QuestStage selectedStage = null; - - private JTextField idField; - private JTextField nameField; - private IntegerBasedCheckBox visibleBox; - private StagesListModel stagesListModel; - private JList stagesList; - -// private JPanel stagesParamPane; - private JSpinner progressField; - private JTextArea logTextField; - private JSpinner xpRewardField; - private IntegerBasedCheckBox finishQuestBox; - - - - public QuestEditor(Quest quest) { - super(quest, quest.getDesc(), quest.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - } - - public void insertFormViewDataField(JPanel pane) { - final Quest quest = ((Quest)target); - - final FieldUpdateListener listener = new QuestFieldUpdater(); - - createButtonPane(pane, quest.getProject(), quest, Quest.class, quest.getImage(), null, listener); - - - idField = addTextField(pane, "Internal ID: ", quest.id, quest.writable, listener); - nameField = addTranslatableTextField(pane, "Quest Name: ", quest.name, quest.writable, listener); - visibleBox = addIntegerBasedCheckBox(pane, "Visible in quest log", quest.visible_in_log, quest.writable, listener); - - CollapsiblePanel stagesPane = new CollapsiblePanel("Quest stages: "); - stagesPane.setLayout(new JideBoxLayout(stagesPane, JideBoxLayout.PAGE_AXIS)); - stagesListModel = new StagesListModel(quest); - stagesList = new JList(stagesListModel); - stagesList.setCellRenderer(new StagesCellRenderer()); - stagesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - stagesPane.add(new JScrollPane(stagesList), JideBoxLayout.FIX); - final JPanel stagesEditorPane = new JPanel(); - final JButton createStage = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteStage = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - final JButton moveStageUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); - final JButton moveStageDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); - deleteStage.setEnabled(false); - moveStageUp.setEnabled(false); - moveStageDown.setEnabled(false); - stagesList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedStage = (QuestStage) stagesList.getSelectedValue(); - if (selectedStage != null) { - deleteStage.setEnabled(true); - moveStageUp.setEnabled(stagesList.getSelectedIndex() > 0); - moveStageDown.setEnabled(stagesList.getSelectedIndex() < (stagesListModel.getSize() - 1)); - } else { - deleteStage.setEnabled(false); - moveStageUp.setEnabled(false); - moveStageDown.setEnabled(false); - } - updateStageEditorPane(stagesEditorPane, selectedStage, listener); - } - }); - if (quest.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createStage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - QuestStage stage = new QuestStage(quest); - stagesListModel.addItem(stage); - stagesList.setSelectedValue(stage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteStage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.removeItem(selectedStage); - selectedStage = null; - stagesList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveStageUp.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.moveUp(selectedStage); - stagesList.setSelectedValue(selectedStage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveStageDown.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.moveDown(selectedStage); - stagesList.setSelectedValue(selectedStage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createStage, JideBoxLayout.FIX); - listButtonsPane.add(deleteStage, JideBoxLayout.FIX); - listButtonsPane.add(moveStageUp, JideBoxLayout.FIX); - listButtonsPane.add(moveStageDown, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - stagesPane.add(listButtonsPane, JideBoxLayout.FIX); - } - if (quest.stages == null || quest.stages.isEmpty()) { - stagesPane.collapse(); - } - stagesEditorPane.setLayout(new JideBoxLayout(stagesEditorPane, JideBoxLayout.PAGE_AXIS)); - stagesPane.add(stagesEditorPane, JideBoxLayout.FIX); - pane.add(stagesPane, JideBoxLayout.FIX); - - } - - public void updateStageEditorPane(JPanel pane, QuestStage selectedStage, FieldUpdateListener listener) { - pane.removeAll(); - if (selectedStage != null) { - boolean writable = ((Quest)target).writable; - progressField = addIntegerField(pane, "Progress ID: ", selectedStage.progress, false, writable, listener); - logTextField = addTranslatableTextArea(pane, "Log text: ", selectedStage.log_text, writable, listener); - xpRewardField = addIntegerField(pane, "XP Reward: ", selectedStage.exp_reward, false, writable, listener); - finishQuestBox = addIntegerBasedCheckBox(pane, "Finishes quest", selectedStage.finishes_quest, writable, listener); - addBacklinksList(pane, selectedStage, "Elements linking to this quest stage"); - - } - pane.revalidate(); - pane.repaint(); - } - - - public static class StagesListModel extends CustomListModel { - public StagesListModel(Quest quest) { - super(quest); - } - - @Override - protected List getItems() { - return source.stages; - } - - @Override - protected void setItems(List items) { - source.stages = items; - } - } - - - public static class StagesCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - label.setText(((QuestStage)value).getDesc()); - label.setIcon(new ImageIcon(((QuestStage)value).getIcon())); - } - return c; - } - } - - - public class QuestFieldUpdater implements FieldUpdateListener { - - @Override - public void valueChanged(JComponent source, Object value) { - Quest quest = (Quest) target; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - quest.id = (String) value; - QuestEditor.this.name = quest.getDesc(); - quest.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(QuestEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - quest.name = (String) value; - QuestEditor.this.name = quest.getDesc(); - quest.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(QuestEditor.this); - } else if (source == visibleBox) { - quest.visible_in_log = (Integer) value; - } else if (source == progressField) { - selectedStage.progress = (Integer) value; - stagesListModel.itemChanged(selectedStage); - } else if (source == logTextField) { - selectedStage.log_text = (String) value; - stagesListModel.itemChanged(selectedStage); - } else if (source == xpRewardField) { - selectedStage.exp_reward = (Integer) value; - stagesListModel.itemChanged(selectedStage); - } else if (source == finishQuestBox) { - selectedStage.finishes_quest = (Integer) value; - stagesListModel.itemChanged(selectedStage); - } - - - if (quest.state != GameDataElement.State.modified) { - quest.state = GameDataElement.State.modified; - QuestEditor.this.name = quest.getDesc(); - quest.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(QuestEditor.this); - } - updateJsonViewText(quest.toJsonString()); - } - - - } - - -} +package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; + +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.ListModel; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; + +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; +import com.gpl.rpg.atcontentstudio.model.gamedata.Common; +import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; +import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; +import com.gpl.rpg.atcontentstudio.ui.*; +import com.jidesoft.swing.JideBoxLayout; + +public class QuestEditor extends JSONElementEditor { + + private static final long serialVersionUID = 5701667955210615366L; + + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; + + private QuestStage selectedStage = null; + + private JTextField idField; + private JTextField nameField; + private IntegerBasedCheckBox visibleBox; + private StagesListModel stagesListModel; + private JList stagesList; + +// private JPanel stagesParamPane; + private JSpinner progressField; + private JTextArea logTextField; + private JSpinner xpRewardField; + private IntegerBasedCheckBox finishQuestBox; + + + + public QuestEditor(Quest quest) { + super(quest, quest.getDesc(), quest.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + } + + public void insertFormViewDataField(JPanel pane) { + final Quest quest = ((Quest)target); + + final FieldUpdateListener listener = new QuestFieldUpdater(); + + createButtonPane(pane, quest.getProject(), quest, Quest.class, quest.getImage(), null, listener); + + + idField = addTextField(pane, "Internal ID: ", quest.id, quest.writable, listener); + nameField = addTranslatableTextField(pane, "Quest Name: ", quest.name, quest.writable, listener); + visibleBox = addIntegerBasedCheckBox(pane, "Visible in quest log", quest.visible_in_log, quest.writable, listener); + + CollapsiblePanel stagesPane = new CollapsiblePanel("Quest stages: "); + stagesPane.setLayout(new JideBoxLayout(stagesPane, JideBoxLayout.PAGE_AXIS)); + stagesListModel = new StagesListModel(quest); + stagesList = new JList(stagesListModel); + stagesList.setCellRenderer(new StagesCellRenderer()); + stagesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + stagesPane.add(new JScrollPane(stagesList), JideBoxLayout.FIX); + final JPanel stagesEditorPane = new JPanel(); + final JButton createStage = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteStage = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + final JButton moveStageUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); + final JButton moveStageDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); + deleteStage.setEnabled(false); + moveStageUp.setEnabled(false); + moveStageDown.setEnabled(false); + stagesList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedStage = (QuestStage) stagesList.getSelectedValue(); + if (selectedStage != null) { + deleteStage.setEnabled(true); + moveStageUp.setEnabled(stagesList.getSelectedIndex() > 0); + moveStageDown.setEnabled(stagesList.getSelectedIndex() < (stagesListModel.getSize() - 1)); + } else { + deleteStage.setEnabled(false); + moveStageUp.setEnabled(false); + moveStageDown.setEnabled(false); + } + updateStageEditorPane(stagesEditorPane, selectedStage, listener); + } + }); + if (quest.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createStage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + QuestStage stage = new QuestStage(quest); + stagesListModel.addItem(stage); + stagesList.setSelectedValue(stage, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteStage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedStage != null) { + stagesListModel.removeItem(selectedStage); + selectedStage = null; + stagesList.clearSelection(); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + moveStageUp.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (selectedStage != null) { + stagesListModel.moveUp(selectedStage); + stagesList.setSelectedValue(selectedStage, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + moveStageDown.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (selectedStage != null) { + stagesListModel.moveDown(selectedStage); + stagesList.setSelectedValue(selectedStage, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + listButtonsPane.add(createStage, JideBoxLayout.FIX); + listButtonsPane.add(deleteStage, JideBoxLayout.FIX); + listButtonsPane.add(moveStageUp, JideBoxLayout.FIX); + listButtonsPane.add(moveStageDown, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + stagesPane.add(listButtonsPane, JideBoxLayout.FIX); + } + if (quest.stages == null || quest.stages.isEmpty()) { + stagesPane.collapse(); + } + stagesEditorPane.setLayout(new JideBoxLayout(stagesEditorPane, JideBoxLayout.PAGE_AXIS)); + stagesPane.add(stagesEditorPane, JideBoxLayout.FIX); + pane.add(stagesPane, JideBoxLayout.FIX); + + } + + public void updateStageEditorPane(JPanel pane, QuestStage selectedStage, FieldUpdateListener listener) { + pane.removeAll(); + if (selectedStage != null) { + boolean writable = ((Quest)target).writable; + progressField = addIntegerField(pane, "Progress ID: ", selectedStage.progress, false, writable, listener); + logTextField = addTranslatableTextArea(pane, "Log text: ", selectedStage.log_text, writable, listener); + xpRewardField = addIntegerField(pane, "XP Reward: ", selectedStage.exp_reward, false, writable, listener); + finishQuestBox = addIntegerBasedCheckBox(pane, "Finishes quest", selectedStage.finishes_quest, writable, listener); + addBacklinksList(pane, selectedStage, "Elements linking to this quest stage"); + + } + pane.revalidate(); + pane.repaint(); + } + + + public static class StagesListModel extends OrderedListenerListModel { + public StagesListModel(Quest quest) { + super(quest); + } + + @Override + protected List getItems() { + return source.stages; + } + + @Override + protected void setItems(List items) { + source.stages = items; + } + } + + + public static class StagesCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel)c); + label.setText(((QuestStage)value).getDesc()); + label.setIcon(new ImageIcon(((QuestStage)value).getIcon())); + } + return c; + } + } + + + public class QuestFieldUpdater implements FieldUpdateListener { + + @Override + public void valueChanged(JComponent source, Object value) { + Quest quest = (Quest) target; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + quest.id = (String) value; + QuestEditor.this.name = quest.getDesc(); + quest.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(QuestEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + quest.name = (String) value; + QuestEditor.this.name = quest.getDesc(); + quest.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(QuestEditor.this); + } else if (source == visibleBox) { + quest.visible_in_log = (Integer) value; + } else if (source == progressField) { + selectedStage.progress = (Integer) value; + stagesListModel.itemChanged(selectedStage); + } else if (source == logTextField) { + selectedStage.log_text = (String) value; + stagesListModel.itemChanged(selectedStage); + } else if (source == xpRewardField) { + selectedStage.exp_reward = (Integer) value; + stagesListModel.itemChanged(selectedStage); + } else if (source == finishQuestBox) { + selectedStage.finishes_quest = (Integer) value; + stagesListModel.itemChanged(selectedStage); + } + + + if (quest.state != GameDataElement.State.modified) { + quest.state = GameDataElement.State.modified; + QuestEditor.this.name = quest.getDesc(); + quest.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(QuestEditor.this); + } + updateJsonViewText(quest.toJsonString()); + } + + + } + + +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index d24adf3..73c5841 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -1147,7 +1147,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } } - public class ReplacementsListModel extends CustomListModel { + public class ReplacementsListModel extends OrderedListenerListModel { public ReplacementsListModel(ReplaceArea area) { super(area); } @@ -1242,7 +1242,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } } - public class MapObjectsListModel extends CustomListModel { + public class MapObjectsListModel extends OrderedListenerListModel { public MapObjectsListModel(MapObjectGroup group) { super(group); } @@ -1272,7 +1272,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } - public class SpawnGroupNpcListModel extends CustomListModel { + public class SpawnGroupNpcListModel extends OrderedListenerListModel { public SpawnGroupNpcListModel(SpawnArea area) { super(area); } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index 05143df..779e74d 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -4,7 +4,7 @@ import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.CustomListModel; +import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; import com.jidesoft.swing.JideBoxLayout; @@ -19,19 +19,19 @@ public class UiUtils { public JList list; } - public static > CollapsibleItemListCreation getCollapsibleItemList(FieldUpdateListener listener, - M itemsListModel, - BasicLambda selectedItemReset, - BasicLambdaWithArg setSelectedItem, - BasicLambdaWithReturn selectedItem, - BasicLambdaWithArg valueChanged, - BasicLambdaWithArg updateEditorPane, - boolean writable, - Supplier tempSupplier, - DefaultListCellRenderer cellRenderer, - String title, - BasicLambdaWithArgAndReturn getReferencedObj, - boolean withMoveButtons) { + public static > CollapsibleItemListCreation getCollapsibleItemList(FieldUpdateListener listener, + M itemsListModel, + BasicLambda selectedItemReset, + BasicLambdaWithArg setSelectedItem, + BasicLambdaWithReturn selectedItem, + BasicLambdaWithArg valueChanged, + BasicLambdaWithArg updateEditorPane, + boolean writable, + Supplier tempSupplier, + DefaultListCellRenderer cellRenderer, + String title, + BasicLambdaWithArgAndReturn getReferencedObj, + boolean withMoveButtons) { CollapsiblePanel itemsPane = new CollapsiblePanel(title); itemsPane.setLayout(new JideBoxLayout(itemsPane, JideBoxLayout.PAGE_AXIS)); final JList itemsList = new JList<>(itemsListModel); @@ -90,7 +90,7 @@ public class UiUtils { }; } - private static > void addRemoveAndAddButtons(FieldUpdateListener listener, M itemsListModel, BasicLambda selectedItemReset, BasicLambdaWithReturn selectedItem, Supplier tempSupplier, JButton createBtn, JList itemsList, JPanel listButtonsPane, JButton deleteBtn) { + private static > void addRemoveAndAddButtons(FieldUpdateListener listener, M itemsListModel, BasicLambda selectedItemReset, BasicLambdaWithReturn selectedItem, Supplier tempSupplier, JButton createBtn, JList itemsList, JPanel listButtonsPane, JButton deleteBtn) { createBtn.addActionListener(e -> { E tempItem = tempSupplier.get(); itemsListModel.addItem(tempItem); @@ -110,7 +110,7 @@ public class UiUtils { listButtonsPane.add(deleteBtn, JideBoxLayout.FIX); } - private static > void addMoveButtonListeners(FieldUpdateListener listener, M itemsListModel, BasicLambdaWithReturn selectedItem, JButton moveUpBtn, JList itemsList, JPanel listButtonsPane, JButton moveDownBtn) { + private static > void addMoveButtonListeners(FieldUpdateListener listener, M itemsListModel, BasicLambdaWithReturn selectedItem, JButton moveUpBtn, JList itemsList, JPanel listButtonsPane, JButton moveDownBtn) { moveUpBtn.addActionListener(e -> { if (selectedItem.doIt() != null) { itemsListModel.moveUp(selectedItem.doIt()); From 979a7bc43f4ee9d103ac74f14b54caf18db22f52 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 17:40:18 +0200 Subject: [PATCH 20/94] add interface ListenerCollectionModel and use it in the OrderedListenerListModel --- .../ui/ListenerCollectionModel.java | 24 ++++++++++++++ .../atcontentstudio/ui/ListenerListModel.java | 4 +++ .../ui/OrderedListenerListModel.java | 31 ++++++++++--------- 3 files changed, 45 insertions(+), 14 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java b/src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java new file mode 100644 index 0000000..bc6b3d4 --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java @@ -0,0 +1,24 @@ +package com.gpl.rpg.atcontentstudio.ui; + +import java.util.Collection; + +public interface ListenerCollectionModel extends ListenerListModel { + public Collection getElements(); + + @Override + default int getSize() { + Collection elements = getElements(); + if (elements == null) return 0; + return elements.size(); + } + + @Override + default E getElementAt(int index) { + for (E obj : getElements()) { + if (index == 0) return obj; + index --; + } + return null; + } + +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java index 7a6f5f6..9752cae 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java @@ -24,4 +24,8 @@ public interface ListenerListModel extends ListModel { default void removeListDataListener(ListDataListener l) { getListeners().remove(l); } + + default void fireListChanged() { + notifyListeners(ListDataEvent.CONTENTS_CHANGED, 0, getSize() -1); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java index e4ceeee..32f6289 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java @@ -3,10 +3,11 @@ package com.gpl.rpg.atcontentstudio.ui; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -public abstract class OrderedListenerListModel implements ListenerListModel { +public abstract class OrderedListenerListModel implements ListenerCollectionModel { protected S source; protected abstract List getItems(); @@ -16,15 +17,9 @@ public abstract class OrderedListenerListModel implements ListenerListMode this.source = source; } - public List getListeners() { - return listeners; - } - - @Override - public int getSize() { - if (getItems() == null) return 0; - return getItems().size(); + public Collection getElements(){ + return getItems(); } @Override @@ -33,6 +28,11 @@ public abstract class OrderedListenerListModel implements ListenerListMode return getItems().get(index); } + public E setElementAt(int index, E value) { + if (getItems() == null) return null; + return getItems().set(index, value); + } + public void addObject(E item) {addItem(item);} public void addItem(E item) { if (getItems() == null) { @@ -40,14 +40,14 @@ public abstract class OrderedListenerListModel implements ListenerListMode } getItems().add(item); int index = getItems().indexOf(item); - notifyListeners( ListDataEvent.INTERVAL_ADDED, index, index); + notifyListeners(ListDataEvent.INTERVAL_ADDED, index, index); } public void removeObject(E item) {removeItem(item);} public void removeItem(E item) { int index = getItems().indexOf(item); getItems().remove(item); - if (getItems().isEmpty()) { + if (getSize() == 0) { setItems(null); } notifyListeners(ListDataEvent.INTERVAL_REMOVED, index, index); @@ -64,9 +64,9 @@ public abstract class OrderedListenerListModel implements ListenerListMode private void moveUpOrDown(E item, int direction) { int index = getItems().indexOf(item); - E exchanged = getItems().get(index + direction); - getItems().set(index, exchanged); - getItems().set(index + direction, item); + E exchanged = getElementAt(index + direction); + setElementAt(index, exchanged); + setElementAt(index + direction, item); notifyListeners(ListDataEvent.CONTENTS_CHANGED, index + direction, index); } @@ -77,4 +77,7 @@ public abstract class OrderedListenerListModel implements ListenerListMode } private List listeners = new CopyOnWriteArrayList(); + public List getListeners() { + return listeners; + } } From cffbf973e15099f397d4418eb104bdd41df23e88 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 17:42:27 +0200 Subject: [PATCH 21/94] change more ListModel implementations to more specific implementations like ListenerListModel, ListenerCollectionModel or OrderedListenerListModel --- .../gpl/rpg/atcontentstudio/ui/Editor.java | 36 +++-------- .../atcontentstudio/ui/JSONImportWizard.java | 33 ++-------- .../ui/gamedataeditors/ItemEditor.java | 4 -- .../ui/gamedataeditors/NPCEditor.java | 4 -- .../ui/gamedataeditors/QuestEditor.java | 5 -- .../atcontentstudio/ui/map/TMXMapEditor.java | 63 ++++--------------- .../ui/map/WorldMapEditor.java | 54 ++++------------ .../ui/sprites/SpritesheetEditor.java | 18 ++---- .../rpg/atcontentstudio/utils/UiUtils.java | 1 - 9 files changed, 43 insertions(+), 175 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index 093dd93..b430bc7 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -15,10 +15,7 @@ import java.awt.event.MouseEvent; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.regex.Matcher; @@ -1028,7 +1025,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener { } - public static class GDEBacklinksListModel implements ListModel { + public static class GDEBacklinksListModel implements ListenerCollectionModel { GameDataElement source; @@ -1046,38 +1043,19 @@ public abstract class Editor extends JPanel implements ProjectElementListener { } }); } - - @Override - public int getSize() { - return source.getBacklinks().size(); - } @Override - public GameDataElement getElementAt(int index) { - for (GameDataElement gde : source.getBacklinks()) { - if (index == 0) return gde; - index --; - } - return null; + public Collection getElements() { + return source.getBacklinks(); } List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - - public void fireListChanged() { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, this.getSize())); - } + public List getListeners() { + return listeners; } + } @SuppressWarnings({"rawtypes", "unchecked"}) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java index f58e61a..dafc1ee 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java @@ -13,6 +13,7 @@ import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; @@ -583,46 +584,24 @@ public class JSONImportWizard extends JDialog { } @SuppressWarnings("rawtypes") - public static class GDEListModel implements ListModel { + public static class GDEListModel implements ListenerCollectionModel { List source; public GDEListModel(List source) { this.source = source; } - @Override - public int getSize() { - return source.size(); - } - - @Override - public Object getElementAt(int index) { - for (Object obj : source) { - if (index == 0) return obj; - index --; - } - return null; + public Collection getElements() { + return source; } List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); + public List getListeners() { + return listeners; } - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - - public void fireListChanged() { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, this.getSize())); - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 49a23b6..bab43f5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -5,7 +5,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.ButtonGroup; import javax.swing.DefaultListCellRenderer; @@ -20,10 +19,7 @@ import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; -import javax.swing.ListModel; import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 7ea7871..bbe4ac6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -6,7 +6,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.ButtonGroup; import javax.swing.DefaultListCellRenderer; @@ -21,10 +20,7 @@ import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; -import javax.swing.ListModel; import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java index a5cc0b3..4a90c85 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java @@ -5,7 +5,6 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.DefaultListCellRenderer; import javax.swing.ImageIcon; @@ -18,17 +17,13 @@ import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextArea; import javax.swing.JTextField; -import javax.swing.ListModel; import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.Common; import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; import com.gpl.rpg.atcontentstudio.ui.*; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index 73c5841..011ae09 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -19,10 +19,7 @@ import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.event.MouseMotionListener; import java.io.File; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.BorderFactory; @@ -1071,7 +1068,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } @SuppressWarnings("rawtypes") - public class LayerListModel implements ListModel { + public class LayerListModel implements ListenerListModel { public TMXMap map; @@ -1092,40 +1089,28 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe public void objectChanged(tiled.core.MapLayer layer) { int index = map.tmxMap.getLayerIndex(layer); - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index, index)); - } + notifyListeners(ListDataEvent.CONTENTS_CHANGED, index, index); + } public void addObject(tiled.core.MapLayer layer) { map.addLayer(layer); int index = map.tmxMap.getLayerIndex(layer); - for (ListDataListener l : listeners) { - l.intervalAdded(new ListDataEvent(this, ListDataEvent.INTERVAL_ADDED, index, index)); - } + notifyListeners(ListDataEvent.INTERVAL_ADDED, index, index); } public void removeObject(tiled.core.MapLayer layer) { int index = map.tmxMap.getLayerIndex(layer); map.removeLayer(layer); - for (ListDataListener l : listeners) { - l.intervalRemoved(new ListDataEvent(this, ListDataEvent.INTERVAL_REMOVED, index, index)); - } + notifyListeners(ListDataEvent.INTERVAL_REMOVED, index, index); } List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + public List getListeners() { + return listeners; } - - } public class LayerListRenderer extends DefaultListCellRenderer { @@ -1534,44 +1519,22 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } - public static class TMXMapSpritesheetsListModel implements ListModel { - - + public static class TMXMapSpritesheetsListModel implements ListenerCollectionModel { TMXMap map; public TMXMapSpritesheetsListModel(TMXMap map) { this.map = map; } @Override - public int getSize() { - return map.usedSpritesheets.size(); - } - - @Override - public Spritesheet getElementAt(int index) { - for (Spritesheet sheet : map.usedSpritesheets) { - if (index == 0) return sheet; - index --; - } - return null; + public Collection getElements() { + return map.usedSpritesheets; } List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - - public void fireListChanged() { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, this.getSize())); - } + public List getListeners() { + return listeners; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java index 7e1afdd..0424bcc 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java @@ -37,6 +37,7 @@ import javax.swing.event.ListDataListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; +import com.gpl.rpg.atcontentstudio.ui.*; import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; import org.fife.ui.rsyntaxtextarea.SyntaxConstants; @@ -49,10 +50,6 @@ import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.Worldmap; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.Editor; -import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.SaveItemsWizard; import com.jidesoft.swing.ComboBoxSearchable; import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideTabbedPane; @@ -694,7 +691,7 @@ public class WorldMapEditor extends Editor implements FieldUpdateListener { } - public class MapSegmentMapsListModel implements ListModel { + public class MapSegmentMapsListModel implements ListenerListModel { WorldmapSegment segment; @@ -713,27 +710,17 @@ public class WorldMapEditor extends Editor implements FieldUpdateListener { } public void listChanged() { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize() - 1)); - } + fireListChanged(); } List listeners = new ArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); + public List getListeners() { + return listeners; } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - } - public class MapSegmentLabelMapsListModel implements ListModel { - + public class MapSegmentLabelMapsListModel implements ListenerListModel { WorldmapSegment segment; WorldmapSegment.NamedArea area; @@ -755,26 +742,18 @@ public class WorldMapEditor extends Editor implements FieldUpdateListener { } public void listChanged() { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize() - 1)); - } + fireListChanged(); } List listeners = new ArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + public List getListeners() { + return listeners; } - } - public class MapSegmentLabelsListModel implements ListModel { + public class MapSegmentLabelsListModel implements ListenerListModel { WorldmapSegment segment; @@ -793,21 +772,14 @@ public class WorldMapEditor extends Editor implements FieldUpdateListener { } public void listChanged() { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, getSize() - 1)); - } + fireListChanged(); } List listeners = new ArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); + public List getListeners() { + return listeners; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java index d3f9a3f..9759e90 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java @@ -48,6 +48,7 @@ import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.Editor; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.gpl.rpg.atcontentstudio.ui.ListenerListModel; import com.gpl.rpg.atcontentstudio.utils.DesktopIntegration; import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideTabbedPane; @@ -351,7 +352,7 @@ public class SpritesheetEditor extends Editor { } - public static class SpritesheetsBacklinksListModel implements ListModel { + public static class SpritesheetsBacklinksListModel implements ListenerListModel { Spritesheet sheet; @@ -374,21 +375,10 @@ public class SpritesheetEditor extends Editor { } List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - - public void fireListChanged() { - for (ListDataListener l : listeners) { - l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, this.getSize())); - } + public List getListeners() { + return listeners; } } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index 779e74d..7fcabd7 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -2,7 +2,6 @@ package com.gpl.rpg.atcontentstudio.utils; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; From a4b431efdd202502868e101aec064a65720b74e6 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 17:52:27 +0200 Subject: [PATCH 22/94] remove some commented out code from earlier --- .../ui/gamedataeditors/DialogueEditor.java | 215 ------------------ 1 file changed, 215 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index 88e1c45..67aeecb 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -168,61 +168,6 @@ public class DialogueEditor extends JSONElementEditor { messageField = addTranslatableTextArea(pane, "Message: ", dialogue.message, dialogue.writable, listener); switchToNpcBox = addNPCBox(pane, dialogue.getProject(), "Switch active NPC to: ", dialogue.switch_to_npc, dialogue.writable, listener); - /* - CollapsiblePanel rewards = new CollapsiblePanel(titleRewards); - rewards.setLayout(new JideBoxLayout(rewards, JideBoxLayout.PAGE_AXIS)); - rewardsList = new JList(rewardsListModel); - rewardsList.setCellRenderer(cellRendererRewards); - rewardsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - rewards.add(new JScrollPane(rewardsList), JideBoxLayout.FIX); - final JPanel rewardsEditorPane = new JPanel(); - final JButton createReward = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteReward = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deleteReward.setEnabled(false); - rewardsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedReward = (Dialogue.Reward) rewardsList.getSelectedValue(); - if (selectedReward == null) { - deleteReward.setEnabled(false); - } else { - deleteReward.setEnabled(true); - } - updateRewardsEditorPane(rewardsEditorPane, selectedReward, listener); - } - }); - if (dialogue.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createReward.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Dialogue.Reward reward = new Dialogue.Reward(); - rewardsListModel.addItem(reward); - rewardsList.setSelectedValue(reward, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteReward.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedReward != null) { - rewardsListModel.removeItem(selectedReward); - selectedReward = null; - rewardsList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createReward, JideBoxLayout.FIX); - listButtonsPane.add(deleteReward, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - rewards.add(listButtonsPane, JideBoxLayout.FIX); - } - rewardsEditorPane.setLayout(new JideBoxLayout(rewardsEditorPane, JideBoxLayout.PAGE_AXIS)); - rewards.add(rewardsEditorPane, JideBoxLayout.FIX); - */ RewardsCellRenderer cellRendererRewards = new RewardsCellRenderer(); String titleRewards = "Reaching this phrase gives the following rewards: "; rewardsListModel = new RewardsListModel(dialogue); @@ -247,91 +192,6 @@ public class DialogueEditor extends JSONElementEditor { } pane.add(rewards, JideBoxLayout.FIX); - /*{ - CollapsiblePanel replies = new CollapsiblePanel(title); - replies.setLayout(new JideBoxLayout(replies, JideBoxLayout.PAGE_AXIS)); - repliesListModel = new RepliesListModel(dialogue); - repliesList = new JList(repliesListModel); - repliesList.setCellRenderer(cellRenderer); - repliesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - replies.add(new JScrollPane(repliesList), JideBoxLayout.FIX); - final JPanel repliesEditorPane = new JPanel(); - final JButton createReply = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteReply = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - final JButton moveReplyUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); - final JButton moveReplyDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); - deleteReply.setEnabled(false); - moveReplyUp.setEnabled(false); - moveReplyDown.setEnabled(false); - repliesList.addListSelectionListener(e -> { - selectedReply = (Dialogue.Reply) repliesList.getSelectedValue(); - replyValueChanged(selectedReply); - if (selectedReply != null) { - deleteReply.setEnabled(true); - moveReplyUp.setEnabled(repliesList.getSelectedIndex() > 0); - moveReplyDown.setEnabled(repliesList.getSelectedIndex() < (repliesListModel.getSize() - 1)); - } else { - deleteReply.setEnabled(false); - moveReplyUp.setEnabled(false); - moveReplyDown.setEnabled(false); - } - updateRepliesEditorPane(repliesEditorPane, selectedReply, listener); - }); - if (dialogue.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createReply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Dialogue.Reply reply = new Dialogue.Reply(); - repliesListModel.addItem(reply); - repliesList.setSelectedValue(reply, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteReply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedReply != null) { - repliesListModel.removeItem(selectedReply); - selectedReply = null; - repliesList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveReplyUp.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedReply != null) { - repliesListModel.moveUp(selectedReply); - repliesList.setSelectedValue(selectedReply, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveReplyDown.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedReply != null) { - repliesListModel.moveDown(selectedReply); - repliesList.setSelectedValue(selectedReply, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createReply, JideBoxLayout.FIX); - listButtonsPane.add(deleteReply, JideBoxLayout.FIX); - listButtonsPane.add(moveReplyUp, JideBoxLayout.FIX); - listButtonsPane.add(moveReplyDown, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - replies.add(listButtonsPane, JideBoxLayout.FIX); - } - repliesEditorPane.setLayout(new JideBoxLayout(repliesEditorPane, JideBoxLayout.PAGE_AXIS)); - replies.add(repliesEditorPane, JideBoxLayout.FIX); - }*/ RepliesCellRenderer cellRendererReplies = new RepliesCellRenderer(); String titleReplies = "Replies / Next Phrase: "; repliesListModel = new RepliesListModel(dialogue); @@ -617,81 +477,6 @@ public class DialogueEditor extends JSONElementEditor { String titleRequirements = "Requirements the player must fulfill to select this reply: "; requirementsListModel = new ReplyRequirementsListModel(reply); ReplyRequirementsCellRenderer cellRendererRequirements = new ReplyRequirementsCellRenderer(); - /* - CollapsiblePanel requirementsPane = new CollapsiblePanel(titleRequirements); - requirementsPane.setLayout(new JideBoxLayout(requirementsPane, JideBoxLayout.PAGE_AXIS)); - requirementsList = new JList(requirementsListModel); - requirementsList.setCellRenderer(cellRendererRequirements); - requirementsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - requirementsPane.add(new JScrollPane(requirementsList), JideBoxLayout.FIX); - final JPanel requirementsEditorPane = new JPanel(); - final JButton createReq = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteReq = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deleteReq.setEnabled(false); - requirementsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedRequirement = (Requirement) requirementsList.getSelectedValue(); - if (selectedRequirement != null) { - deleteReq.setEnabled(true); - } else { - deleteReq.setEnabled(false); - } - updateRequirementsEditorPane(requirementsEditorPane, selectedRequirement, listener); - } - }); - requirementsList.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - if (requirementsList.getSelectedValue() != null && ((Requirement)requirementsList.getSelectedValue()).required_obj != null) { - ATContentStudio.frame.openEditor(((Requirement)requirementsList.getSelectedValue()).required_obj); - ATContentStudio.frame.selectInTree(((Requirement)requirementsList.getSelectedValue()).required_obj); - } - } - } - }); - requirementsList.addKeyListener(new KeyAdapter() { - @Override - public void keyReleased(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - ATContentStudio.frame.openEditor(((Requirement)requirementsList.getSelectedValue()).required_obj); - ATContentStudio.frame.selectInTree(((Requirement)requirementsList.getSelectedValue()).required_obj); - } - } - }); - if (((Dialogue)target).writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createReq.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Requirement req = new Requirement(); - requirementsListModel.addItem(req); - requirementsList.setSelectedValue(req, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteReq.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedRequirement != null) { - requirementsListModel.removeItem(selectedRequirement); - selectedRequirement = null; - requirementsList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createReq, JideBoxLayout.FIX); - listButtonsPane.add(deleteReq, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - requirementsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - requirementsEditorPane.setLayout(new JideBoxLayout(requirementsEditorPane, JideBoxLayout.PAGE_AXIS)); - requirementsPane.add(requirementsEditorPane, JideBoxLayout.FIX);*/ - UiUtils.CollapsibleItemListCreation itemsPane = UiUtils.getCollapsibleItemList( listener, requirementsListModel, From bb187621b7087387e6d15f7c314c541e239313cc Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 18:19:25 +0200 Subject: [PATCH 23/94] remove a bunch of unused assignments --- hacked-libtiled/tiled/core/MapObject.java | 2 +- hacked-libtiled/tiled/core/Sprite.java | 2 +- hacked-libtiled/tiled/io/TMXMapWriter.java | 2 +- src/com/gpl/rpg/atcontentstudio/ATContentStudio.java | 2 +- src/com/gpl/rpg/atcontentstudio/Notification.java | 2 +- .../gpl/rpg/atcontentstudio/model/GameSource.java | 4 ++-- src/com/gpl/rpg/atcontentstudio/model/Project.java | 6 +++--- src/com/gpl/rpg/atcontentstudio/model/Workspace.java | 10 ++++------ .../model/bookmarks/BookmarksRoot.java | 4 ++-- .../gpl/rpg/atcontentstudio/model/maps/KeyArea.java | 6 +++--- .../rpg/atcontentstudio/model/maps/MapChange.java | 4 ++-- .../rpg/atcontentstudio/model/maps/ReplaceArea.java | 2 +- .../gpl/rpg/atcontentstudio/model/maps/TMXMap.java | 2 +- .../model/tools/resoptimizer/ResourcesCompactor.java | 3 +-- src/com/gpl/rpg/atcontentstudio/ui/Editor.java | 4 ++-- .../gpl/rpg/atcontentstudio/ui/JSONImportWizard.java | 12 +++++------- .../atcontentstudio/ui/ProjectCreationWizard.java | 6 ++---- src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java | 2 +- .../gpl/rpg/atcontentstudio/ui/WorkspaceActions.java | 2 +- .../ui/WorldmapLabelEditionWizard.java | 2 +- .../ui/gamedataeditors/DialogueEditor.java | 4 ++-- .../ui/gamedataeditors/ItemEditor.java | 6 ++---- .../rpg/atcontentstudio/ui/map/MapColorFilters.java | 2 +- .../gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java | 8 ++++---- .../ui/sprites/SpritesheetEditor.java | 2 +- .../ui/tools/writermode/WriterModeEditor.java | 10 +++++----- src/net/launchpad/tobal/poparser/POFile.java | 2 +- src/net/launchpad/tobal/poparser/POParser.java | 9 +++------ 28 files changed, 55 insertions(+), 67 deletions(-) diff --git a/hacked-libtiled/tiled/core/MapObject.java b/hacked-libtiled/tiled/core/MapObject.java index 111b825..8e75282 100644 --- a/hacked-libtiled/tiled/core/MapObject.java +++ b/hacked-libtiled/tiled/core/MapObject.java @@ -43,7 +43,7 @@ public class MapObject implements Cloneable { private Properties properties = new Properties(); private ObjectGroup objectGroup; - private Rectangle bounds = new Rectangle(); + private Rectangle bounds; private String name = "Object"; private String type = ""; private String imageSource = ""; diff --git a/hacked-libtiled/tiled/core/Sprite.java b/hacked-libtiled/tiled/core/Sprite.java index 670bc4c..266c6ec 100644 --- a/hacked-libtiled/tiled/core/Sprite.java +++ b/hacked-libtiled/tiled/core/Sprite.java @@ -57,7 +57,7 @@ public class Sprite private String name = null; private int id = -1; - private int flags = KEY_LOOP; + private int flags; private float frameRate = 1.0f; //one fps private Tile[] frames; diff --git a/hacked-libtiled/tiled/io/TMXMapWriter.java b/hacked-libtiled/tiled/io/TMXMapWriter.java index 9004af8..600a409 100644 --- a/hacked-libtiled/tiled/io/TMXMapWriter.java +++ b/hacked-libtiled/tiled/io/TMXMapWriter.java @@ -588,7 +588,7 @@ public class TMXMapWriter } // Iterate while parents are the same - int shared = 0; + int shared; int maxShared = Math.min(fromParents.size(), toParents.size()); for (shared = 0; shared < maxShared; shared++) { String fromParent = fromParents.get(shared); diff --git a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java index e53645f..8a1f295 100644 --- a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java +++ b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java @@ -62,7 +62,7 @@ public class ATContentStudio { */ public static void main(String[] args) { String fontScaling = System.getProperty(FONT_SCALE_ENV_VAR_NAME); - Float fontScale = null; + Float fontScale; if (fontScaling != null) { try { fontScale = Float.parseFloat(fontScaling); diff --git a/src/com/gpl/rpg/atcontentstudio/Notification.java b/src/com/gpl/rpg/atcontentstudio/Notification.java index fa25ebc..6cf184e 100644 --- a/src/com/gpl/rpg/atcontentstudio/Notification.java +++ b/src/com/gpl/rpg/atcontentstudio/Notification.java @@ -8,7 +8,7 @@ public class Notification { public static List notifs = new ArrayList(); private static List listeners = new CopyOnWriteArrayList(); - public static boolean showS = true, showI = true, showW = true, showE = true; + public static boolean showS, showI, showW, showE; static { boolean[] config = ConfigCache.getNotifViewConfig(); diff --git a/src/com/gpl/rpg/atcontentstudio/model/GameSource.java b/src/com/gpl/rpg/atcontentstudio/model/GameSource.java index f94751e..043d5d2 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/GameSource.java +++ b/src/com/gpl/rpg/atcontentstudio/model/GameSource.java @@ -57,7 +57,7 @@ public class GameSource implements ProjectTreeNode, Serializable { public File baseFolder; public Type type; - public transient Project parent = null; + public transient Project parent; public transient Map> referencedSourceFiles = null; @@ -105,7 +105,7 @@ public class GameSource implements ProjectTreeNode, Serializable { } public void readResourceList() { - File xmlFile = null; + File xmlFile; if (parent.sourceSetToUse == ResourceSet.gameData) { xmlFile = new File(baseFolder, DEFAULT_REL_PATH_FOR_GAME_RESOURCE); } else if (parent.sourceSetToUse == ResourceSet.debugData) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/Project.java b/src/com/gpl/rpg/atcontentstudio/model/Project.java index a6dab19..61ffbf5 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/Project.java +++ b/src/com/gpl/rpg/atcontentstudio/model/Project.java @@ -103,7 +103,7 @@ public class Project implements ProjectTreeNode, Serializable { public transient Workspace parent; - public Properties knownSpritesheetsProperties = null; + public Properties knownSpritesheetsProperties; public static enum ResourceSet { gameData, @@ -111,7 +111,7 @@ public class Project implements ProjectTreeNode, Serializable { allFiles } - public ResourceSet sourceSetToUse = ResourceSet.allFiles; + public ResourceSet sourceSetToUse; public Project(Workspace w, String name, File source, ResourceSet sourceSet) { this.parent = w; @@ -237,7 +237,7 @@ public class Project implements ProjectTreeNode, Serializable { public static Project fromFolder(Workspace w, File projRoot) { - Project p = null; + Project p; File f = new File(projRoot, Project.SETTINGS_FILE); if (!f.exists()) { Notification.addError("Unable to find "+SETTINGS_FILE+" for project "+projRoot.getName()); diff --git a/src/com/gpl/rpg/atcontentstudio/model/Workspace.java b/src/com/gpl/rpg/atcontentstudio/model/Workspace.java index 8bf298a..1697279 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/Workspace.java +++ b/src/com/gpl/rpg/atcontentstudio/model/Workspace.java @@ -72,7 +72,7 @@ public class Workspace implements ProjectTreeNode, Serializable { } public static void setActive(File workspaceRoot) { - Workspace w = null; + Workspace w; File f = new File(workspaceRoot, WS_SETTINGS_FILE); if (!workspaceRoot.exists() || !f.exists()) { w = new Workspace(workspaceRoot); @@ -311,8 +311,7 @@ public class Workspace implements ProjectTreeNode, Serializable { Notification.addError("Error while deleting closed project " + cp.name + ". Files may remain in the workspace."); } - cp = null; - saveActive(); + saveActive(); } public static void deleteProject(Project p) { @@ -327,8 +326,7 @@ public class Workspace implements ProjectTreeNode, Serializable { Notification.addError("Error while deleting project " + p.name + ". Files may remain in the workspace."); } - p = null; - saveActive(); + saveActive(); } private static boolean delete(File f) { @@ -339,7 +337,7 @@ public class Workspace implements ProjectTreeNode, Serializable { for (File c : f.listFiles()) b &= delete(c); } - return b &= f.delete(); + return b & f.delete(); } @Override diff --git a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java index 501cfff..588c1f3 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java +++ b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java @@ -30,7 +30,7 @@ public class BookmarksRoot implements BookmarkNode { SavedSlotCollection v = new SavedSlotCollection(); - public transient Project parent = null; + public transient Project parent; BookmarkFolder ac, diag, dl, it, ic, npc, q, tmx, sp, wm; @@ -171,7 +171,7 @@ public class BookmarksRoot implements BookmarkNode { public void addBookmark(GameDataElement target) { BookmarkEntry node; - BookmarkFolder folder = null; + BookmarkFolder folder; if (target instanceof ActorCondition) { folder = ac; } else if (target instanceof Dialogue) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java index c583328..c5669fd 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java @@ -9,10 +9,10 @@ import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; public class KeyArea extends MapObject { - public String dialogue_id = null; + public String dialogue_id; public Dialogue dialogue = null; - public Requirement requirement = null; - public boolean oldSchoolRequirement = true; + public Requirement requirement; + public boolean oldSchoolRequirement; public KeyArea(tiled.core.MapObject obj) { dialogue_id = obj.getProperties().getProperty("phrase"); diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java b/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java index f0e93bd..75b579d 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java @@ -9,9 +9,9 @@ import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; public class MapChange extends MapObject { - public String map_id = null; + public String map_id; public TMXMap map = null; - public String place_id = null; + public String place_id; public MapChange(tiled.core.MapObject obj) { this.map_id = obj.getProperties().getProperty("map"); diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java index eaea296..b14d41d 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java @@ -11,7 +11,7 @@ import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; public class ReplaceArea extends MapObject { - public Requirement requirement = null; + public Requirement requirement; public boolean oldSchoolRequirement = false; public List replacements = null; diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java index 38da7fc..8691bf1 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java @@ -54,7 +54,7 @@ public class TMXMap extends GameDataElement { bluetint } - public File tmxFile = null; + public File tmxFile; public tiled.core.Map tmxMap = null; public Set usedSpritesheets = null; public List groups = null; diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java b/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java index b294fdd..e69f272 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java @@ -206,8 +206,7 @@ public class ResourcesCompactor { compactMap(tmx, map.id); clone.tmxMap = null; clone.groups.clear(); - clone = null; - } + } } private void compactMap(tiled.core.Map tmx, String name) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index b430bc7..a129f3f 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -919,8 +919,8 @@ public abstract class Editor extends JPanel implements ProjectElementListener { private static final long serialVersionUID = 6819681566800482793L; - private boolean includeType = false; - private boolean writable = false; + private boolean includeType; + private boolean writable; public GDERenderer(boolean includeType, boolean writable) { super(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java index dafc1ee..a391382 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java @@ -293,8 +293,8 @@ public class JSONImportWizard extends JDialog { errors.add("Invalid JSON content: neither an array nor an object."); } if (jsonObjects != null) { - JSONElement node = null; - JSONElement existingNode = null; + JSONElement node; + JSONElement existingNode; int i = 0; for (Map jsonObject : jsonObjects) { switch ((DataType)dataTypeCombo.getSelectedItem()) { @@ -342,10 +342,8 @@ public class JSONImportWizard extends JDialog { node.jsonFile = existingNode.jsonFile; warnings.add("An item with id "+node.id+" exists in the used game source. This one will be inserted as \"altered\""); } - existingNode = null; - } - node = null; - } else { + } + } else { warnings.add("Failed to load element #"+i); } } @@ -508,7 +506,7 @@ public class JSONImportWizard extends JDialog { private static final long serialVersionUID = 6819681566800482793L; - private boolean includeType = false; + private boolean includeType; public GDERenderer(boolean includeType) { super(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java index b0958a9..dcdff60 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java @@ -234,10 +234,8 @@ public class ProjectCreationWizard extends JDialog { buttonPane.setLayout(new GridBagLayout()); GridBagConstraints c2 = new GridBagConstraints(); c2.fill = GridBagConstraints.HORIZONTAL; - c2.gridx = 1; - c2.weightx = 80; - - c2.gridx = 1; + + c2.gridx = 1; c2.weightx = 80; buttonPane.add(new JLabel(), c2); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java b/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java index 0d8148b..4b050aa 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java @@ -685,7 +685,7 @@ public class ProjectsTree extends JPanel { JLabel label = (JLabel)c; String text = ((ProjectTreeNode)value).getDesc(); if (text != null) label.setText(text); - Image img = null; + Image img; if (leaf) img = ((ProjectTreeNode)value).getLeafIcon(); else if (expanded) img = ((ProjectTreeNode)value).getOpenIcon(); else img = ((ProjectTreeNode)value).getClosedIcon(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java index 4ef50c6..7f4d10c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java @@ -171,7 +171,7 @@ public class WorkspaceActions { @Override public void run() { final List events = new ArrayList(); - List catEvents = null; + List catEvents; for (GameDataCategory category : impactedCategories.keySet()) { for (File f : impactedCategories.get(category)) { catEvents = category.attemptSave(true, f.getName()); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java index 6c97d71..ff593ab 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java @@ -32,7 +32,7 @@ public class WorldmapLabelEditionWizard extends JDialog { final WorldmapSegment segment; final WorldmapSegment.NamedArea label; - boolean createMode = false; + boolean createMode; public WorldmapLabelEditionWizard(WorldmapSegment segment) { this(segment, new WorldmapSegment.NamedArea(null, null, null), true); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index 67aeecb..11513cd 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -972,7 +972,7 @@ public class DialogueEditor extends JSONElementEditor { } else if (source == rewardValue) { //Backlink removal to quest stages when selecting another quest are handled in the addQuestStageBox() method. Too complex too handle here Quest quest = null; - QuestStage stage = null; + QuestStage stage; if (rewardValue instanceof JComboBox) { quest = ((Quest)selectedReward.reward_obj); if (quest != null && selectedReward.reward_value != null) { @@ -1048,7 +1048,7 @@ public class DialogueEditor extends JSONElementEditor { } else if (source == requirementValue) { //Backlink removal to quest stages when selecting another quest are handled in the addQuestStageBox() method. Too complex too handle here Quest quest = null; - QuestStage stage = null; + QuestStage stage; if (requirementValue instanceof JComboBox) { quest = ((Quest)selectedRequirement.required_obj); if (quest != null && selectedRequirement.required_value != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index bab43f5..66dbc11 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -1429,10 +1429,8 @@ public class ItemEditor extends JSONElementEditor { ItemEditor.this.repaint(); } else if (item.category.action_type == ItemCategory.ActionType.equip) { equipEffectPane.setVisible(true); - updateEquip = true; - hitEffectPane.setVisible(true); - updateEquip = true; - killEffectPane.setVisible(true); + hitEffectPane.setVisible(true); + killEffectPane.setVisible(true); updateKill = true; hitReceivedEffectPane.setVisible(true); updateEquip = true; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java b/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java index 19bf5de..593cb04 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java @@ -14,7 +14,7 @@ public class MapColorFilters { Composite oldComp = g2d.getComposite(); Rectangle clip = g2d.getClipBounds(); MatrixComposite newComp = null; - float f=0.0f; + float f; switch(colorFilter) { case black20: f=0.8f; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index 011ae09..69fc64c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -1173,7 +1173,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe public class ReplacementsLayersComboModel implements ComboBoxModel { ReplaceArea area; - boolean modelForSource = false; + boolean modelForSource; public List availableLayers = new ArrayList(); @@ -1542,7 +1542,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe private static final long serialVersionUID = 6819681566800482793L; - private boolean includeType = false; + private boolean includeType; public SpritesheetCellRenderer(boolean includeType) { super(); @@ -2032,7 +2032,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe if (selectedMapObject instanceof KeyArea) { KeyArea area = (KeyArea) selectedMapObject; Quest quest = null; - QuestStage stage = null; + QuestStage stage; if (requirementValue instanceof JComboBox) { quest = ((Quest)area.requirement.required_obj); if (quest != null && area.requirement.required_value != null) { @@ -2053,7 +2053,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } else if (selectedMapObject instanceof ReplaceArea) { ReplaceArea area = (ReplaceArea) selectedMapObject; Quest quest = null; - QuestStage stage = null; + QuestStage stage; if (requirementValue instanceof JComboBox) { quest = ((Quest)area.requirement.required_obj); if (quest != null && area.requirement.required_value != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java index 9759e90..2eba1c0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java @@ -386,7 +386,7 @@ public class SpritesheetEditor extends Editor { private static final long serialVersionUID = 6819681566800482793L; - private boolean includeType = false; + private boolean includeType; public BacklinkCellRenderer(boolean includeType) { super(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java index 5d663cb..9895edb 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java @@ -93,7 +93,7 @@ public class WriterModeEditor extends Editor { private Display view; final private WriterModeData data; - private WriterNode selected = null; + private WriterNode selected; private WriterNode prevSelected = null; public WriterModeEditor(WriterModeData data) { @@ -708,8 +708,8 @@ public class WriterModeEditor extends Editor { public void actionPerformed(ActionEvent e) { commitAreaText(); stopPendingEdge(); - WriterDialogue newWrNode = null; - Node newNode = null; + WriterDialogue newWrNode; + Node newNode; if (selected instanceof WriterDialogue) { EmptyReply temp = data.new EmptyReply((WriterDialogue) selected); newWrNode = data.new WriterDialogue(((WriterDialogue) selected).id_prefix); @@ -737,8 +737,8 @@ public class WriterModeEditor extends Editor { public void actionPerformed(ActionEvent e) { commitAreaText(); stopPendingEdge(); - WriterReply newWrNode = null; - Node newNode = null; + WriterReply newWrNode; + Node newNode; if (selected instanceof WriterReply) { newWrNode = data.new WriterReply(((WriterReply) selected).parent); newNode = addReplyNode(newWrNode); diff --git a/src/net/launchpad/tobal/poparser/POFile.java b/src/net/launchpad/tobal/poparser/POFile.java index 919db09..c83677c 100644 --- a/src/net/launchpad/tobal/poparser/POFile.java +++ b/src/net/launchpad/tobal/poparser/POFile.java @@ -73,7 +73,7 @@ public class POFile public boolean checkFlag(String flag, int entryIndex) { boolean status = false; - Vector strings = new Vector(); + Vector strings; strings = entries[entryIndex].getStringsByType(POEntry.StringType.FLAG); if (strings != null) { diff --git a/src/net/launchpad/tobal/poparser/POParser.java b/src/net/launchpad/tobal/poparser/POParser.java index 1fee0cc..ae03217 100644 --- a/src/net/launchpad/tobal/poparser/POParser.java +++ b/src/net/launchpad/tobal/poparser/POParser.java @@ -126,7 +126,6 @@ public class POParser { String str = rawentry.get(i); tempheader.addLine(POEntry.StringType.HEADER, str); - str = new String(); } return tempheader; } @@ -138,7 +137,7 @@ public class POParser private POEntry[] parseEntries(Vector> vectors) { - String line = new String(); + String line; boolean thereIsHeader = false; // is this header @@ -228,8 +227,7 @@ public class POParser subStrIndex = 16; } } - String str = new String(); - str = line.substring(subStrIndex); + String str = line.substring(subStrIndex); entry.addLine(strType, str); } else if(line.startsWith("msg")) @@ -253,9 +251,8 @@ public class POParser parserMode = strType; subStrIndex = 7; } - String str = new String(); // TODO: is unquoting nessessary? - str = unQuote(line.substring(subStrIndex)); + String str = unQuote(line.substring(subStrIndex)); entry.addLine(strType, str); } else From 90359bf285566cebada98c3a1f97e90652747a71 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 18:36:37 +0200 Subject: [PATCH 24/94] reformat all code --- .../rpg/atcontentstudio/ATContentStudio.java | 376 +- .../gpl/rpg/atcontentstudio/ConfigCache.java | 161 +- .../gpl/rpg/atcontentstudio/Notification.java | 164 +- .../atcontentstudio/NotificationListener.java | 7 +- .../atcontentstudio/io/JsonPrettyWriter.java | 84 +- .../rpg/atcontentstudio/io/SettingsSave.java | 132 +- .../atcontentstudio/model/ClosedProject.java | 231 +- .../model/GameDataElement.java | 411 +- .../rpg/atcontentstudio/model/GameSource.java | 557 +- .../atcontentstudio/model/Preferences.java | 18 +- .../rpg/atcontentstudio/model/Project.java | 2625 +++++---- .../model/ProjectElementListener.java | 12 +- .../model/ProjectTreeNode.java | 105 +- .../rpg/atcontentstudio/model/SaveEvent.java | 60 +- .../model/SavedSlotCollection.java | 110 +- .../rpg/atcontentstudio/model/Workspace.java | 637 ++- .../model/WorkspaceSettings.java | 400 +- .../model/bookmarks/BookmarkEntry.java | 244 +- .../model/bookmarks/BookmarkFolder.java | 269 +- .../model/bookmarks/BookmarkNode.java | 9 +- .../model/bookmarks/BookmarksRoot.java | 346 +- .../model/gamedata/ActorCondition.java | 712 +-- .../model/gamedata/Common.java | 3 +- .../model/gamedata/Dialogue.java | 880 ++- .../model/gamedata/Droplist.java | 420 +- .../model/gamedata/GameDataCategory.java | 458 +- .../model/gamedata/GameDataSet.java | 916 +-- .../atcontentstudio/model/gamedata/Item.java | 1268 ++--- .../model/gamedata/ItemCategory.java | 586 +- .../model/gamedata/JSONElement.java | 285 +- .../atcontentstudio/model/gamedata/NPC.java | 1057 ++-- .../atcontentstudio/model/gamedata/Quest.java | 335 +- .../model/gamedata/QuestStage.java | 156 +- .../model/gamedata/Requirement.java | 457 +- .../model/maps/ContainerArea.java | 71 +- .../atcontentstudio/model/maps/KeyArea.java | 208 +- .../atcontentstudio/model/maps/MapChange.java | 91 +- .../atcontentstudio/model/maps/MapObject.java | 306 +- .../model/maps/MapObjectGroup.java | 98 +- .../model/maps/ReplaceArea.java | 225 +- .../atcontentstudio/model/maps/RestArea.java | 44 +- .../model/maps/ScriptArea.java | 104 +- .../atcontentstudio/model/maps/SignArea.java | 74 +- .../atcontentstudio/model/maps/SpawnArea.java | 170 +- .../atcontentstudio/model/maps/TMXMap.java | 884 ++- .../atcontentstudio/model/maps/TMXMapSet.java | 514 +- .../atcontentstudio/model/maps/Worldmap.java | 495 +- .../model/maps/WorldmapSegment.java | 431 +- .../model/saves/SavedGame.java | 300 +- .../model/saves/SavedGamesSet.java | 318 +- .../model/sprites/SpriteSheetSet.java | 306 +- .../model/sprites/Spritesheet.java | 517 +- .../model/tools/i18n/PoPotWriter.java | 151 +- .../model/tools/i18n/PotComparator.java | 570 +- .../model/tools/i18n/PotGenerator.java | 171 +- .../resoptimizer/ResourcesCompactor.java | 671 ++- .../tools/resoptimizer/SpritesheetId.java | 48 +- .../tools/writermode/WriterModeData.java | 1273 +++-- .../tools/writermode/WriterModeDataSet.java | 466 +- .../rpg/atcontentstudio/ui/AboutEditor.java | 354 +- .../ui/BooleanBasedCheckBox.java | 20 +- .../atcontentstudio/ui/CollapsiblePanel.java | 287 +- .../rpg/atcontentstudio/ui/DefaultIcons.java | 995 +++- .../gpl/rpg/atcontentstudio/ui/Editor.java | 2193 ++++---- .../rpg/atcontentstudio/ui/EditorsArea.java | 332 +- .../ui/ExportProjectWizard.java | 409 +- .../ui/FieldUpdateListener.java | 6 +- .../ui/IdChangeImpactWizard.java | 173 +- .../ui/IntegerBasedCheckBox.java | 24 +- .../rpg/atcontentstudio/ui/JMovingIdler.java | 171 +- .../ui/JSONCreationWizard.java | 1140 ++-- .../atcontentstudio/ui/JSONImportWizard.java | 1286 +++-- .../ui/ListenerCollectionModel.java | 2 +- .../atcontentstudio/ui/ListenerListModel.java | 3 +- .../atcontentstudio/ui/NotificationsPane.java | 148 +- .../ui/OrderedListenerListModel.java | 21 +- .../rpg/atcontentstudio/ui/OverlayIcon.java | 51 +- .../ui/ProjectCreationWizard.java | 580 +- .../rpg/atcontentstudio/ui/ProjectsTree.java | 875 ++- .../atcontentstudio/ui/SaveItemsWizard.java | 476 +- .../atcontentstudio/ui/ScrollablePanel.java | 550 +- .../rpg/atcontentstudio/ui/StudioFrame.java | 461 +- .../ui/TMXMapCreationWizard.java | 543 +- .../rpg/atcontentstudio/ui/WorkerDialog.java | 87 +- .../atcontentstudio/ui/WorkspaceActions.java | 1012 ++-- .../atcontentstudio/ui/WorkspaceSelector.java | 270 +- .../ui/WorkspaceSettingsEditor.java | 471 +- .../ui/WorldmapCreationWizard.java | 285 +- .../ui/WorldmapLabelEditionWizard.java | 347 +- .../ui/WriterSketchCreationWizard.java | 257 +- .../gamedataeditors/ActorConditionEditor.java | 1047 ++-- .../ui/gamedataeditors/DialogueEditor.java | 2063 ++++--- .../ui/gamedataeditors/DroplistEditor.java | 353 +- .../gamedataeditors/ItemCategoryEditor.java | 253 +- .../ui/gamedataeditors/ItemEditor.java | 3806 +++++++------ .../ui/gamedataeditors/JSONElementEditor.java | 699 ++- .../ui/gamedataeditors/NPCEditor.java | 3127 ++++++----- .../ui/gamedataeditors/QuestEditor.java | 479 +- .../dialoguetree/DialogueGraphView.java | 906 ++- .../ui/map/MapColorFilters.java | 211 +- .../atcontentstudio/ui/map/TMXMapEditor.java | 4933 ++++++++--------- .../ui/map/WorldMapEditor.java | 2056 ++++--- .../atcontentstudio/ui/map/WorldMapView.java | 835 ++- .../ui/saves/SavedGameEditor.java | 36 +- .../ui/sprites/SpriteChooser.java | 356 +- .../ui/sprites/SpritesheetEditor.java | 811 ++- .../ui/tools/BeanShellView.java | 267 +- .../ui/tools/ElementTableView.java | 125 +- .../atcontentstudio/ui/tools/GDEVisitor.java | 378 +- .../ui/tools/ItemsTableView.java | 565 +- .../ui/tools/MatrixComposite.java | 189 +- .../ui/tools/NPCsTableView.java | 382 +- .../ui/tools/writermode/WriterModeEditor.java | 1631 +++--- .../utils/DesktopIntegration.java | 192 +- .../rpg/atcontentstudio/utils/FileUtils.java | 412 +- .../rpg/atcontentstudio/utils/HashUtils.java | 44 +- .../atcontentstudio/utils/SpriteUtils.java | 52 +- .../rpg/atcontentstudio/utils/TextUtils.java | 13 +- .../rpg/atcontentstudio/utils/UiUtils.java | 14 +- .../utils/WeblateIntegration.java | 175 +- 120 files changed, 31732 insertions(+), 31504 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java index 8a1f295..926d52d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java +++ b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java @@ -1,10 +1,16 @@ package com.gpl.rpg.atcontentstudio; -import java.awt.Color; -import java.awt.Desktop; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Toolkit; +import com.gpl.rpg.atcontentstudio.model.Workspace; +import com.gpl.rpg.atcontentstudio.ui.StudioFrame; +import com.gpl.rpg.atcontentstudio.ui.WorkerDialog; +import com.gpl.rpg.atcontentstudio.ui.WorkspaceSelector; +import prefuse.data.expression.parser.ExpressionParser; + +import javax.swing.*; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.plaf.FontUIResource; +import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.BufferedReader; @@ -14,221 +20,203 @@ import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedList; import java.util.List; -import java.util.Map; +import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; -import javax.swing.JEditorPane; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.UIDefaults; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkListener; -import javax.swing.plaf.FontUIResource; - -import prefuse.data.expression.parser.ExpressionParser; - -import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.ui.StudioFrame; -import com.gpl.rpg.atcontentstudio.ui.WorkerDialog; -import com.gpl.rpg.atcontentstudio.ui.WorkspaceSelector; - public class ATContentStudio { - public static final String APP_NAME = "Andor's Trail Content Studio"; - public static final String APP_VERSION = "v0.6.21"; + public static final String APP_NAME = "Andor's Trail Content Studio"; + public static final String APP_VERSION = "v0.6.21"; - public static final String CHECK_UPDATE_URL = "https://andorstrail.com/static/ATCS_latest"; - public static final String DOWNLOAD_URL = "https://andorstrail.com/viewtopic.php?f=6&t=4806"; + public static final String CHECK_UPDATE_URL = "https://andorstrail.com/static/ATCS_latest"; + public static final String DOWNLOAD_URL = "https://andorstrail.com/viewtopic.php?f=6&t=4806"; - public static final String FONT_SCALE_ENV_VAR_NAME = "FONT_SCALE"; + public static final String FONT_SCALE_ENV_VAR_NAME = "FONT_SCALE"; - public static boolean STARTED = false; - public static float SCALING = 1.0f; - public static StudioFrame frame = null; + public static boolean STARTED = false; + public static float SCALING = 1.0f; + public static StudioFrame frame = null; - // Need to keep a strong reference to it, to avoid garbage collection that'll - // reset these loggers. - public static final List configuredLoggers = new LinkedList(); + // Need to keep a strong reference to it, to avoid garbage collection that'll + // reset these loggers. + public static final List configuredLoggers = new LinkedList(); - /** - * @param args - */ - public static void main(String[] args) { - String fontScaling = System.getProperty(FONT_SCALE_ENV_VAR_NAME); - Float fontScale; - if (fontScaling != null) { - try { - fontScale = Float.parseFloat(fontScaling); - SCALING = fontScale; - } catch (NumberFormatException e) { - System.err.println("Failed to parse font scaling parameter. Using default."); - e.printStackTrace(); - } - } + /** + * @param args + */ + public static void main(String[] args) { + String fontScaling = System.getProperty(FONT_SCALE_ENV_VAR_NAME); + Float fontScale; + if (fontScaling != null) { + try { + fontScale = Float.parseFloat(fontScaling); + SCALING = fontScale; + } catch (NumberFormatException e) { + System.err.println("Failed to parse font scaling parameter. Using default."); + e.printStackTrace(); + } + } - ConfigCache.init(); + ConfigCache.init(); - try { - String laf = ConfigCache.getFavoriteLaFClassName(); - if (laf == null) - laf = UIManager.getSystemLookAndFeelClassName(); - UIManager.setLookAndFeel(laf); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (UnsupportedLookAndFeelException e) { - e.printStackTrace(); - } + try { + String laf = ConfigCache.getFavoriteLaFClassName(); + if (laf == null) + laf = UIManager.getSystemLookAndFeelClassName(); + UIManager.setLookAndFeel(laf); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } catch (InstantiationException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (UnsupportedLookAndFeelException e) { + e.printStackTrace(); + } - scaleUIFont(); + scaleUIFont(); - // Need to keep a strong reference to it, to avoid garbage collection that'll - // reset this setting. - Logger l = Logger.getLogger(ExpressionParser.class.getName()); - l.setLevel(Level.OFF); - configuredLoggers.add(l); + // Need to keep a strong reference to it, to avoid garbage collection that'll + // reset this setting. + Logger l = Logger.getLogger(ExpressionParser.class.getName()); + l.setLevel(Level.OFF); + configuredLoggers.add(l); - final WorkspaceSelector wsSelect = new WorkspaceSelector(); - wsSelect.pack(); - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = wsSelect.getSize(); - wsSelect.setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); - wsSelect.setVisible(true); + final WorkspaceSelector wsSelect = new WorkspaceSelector(); + wsSelect.pack(); + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = wsSelect.getSize(); + wsSelect.setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + wsSelect.setVisible(true); - wsSelect.addWindowListener(new WindowAdapter() { - @Override - public synchronized void windowClosed(WindowEvent e) { - if (wsSelect.selected != null && !STARTED) { - ATContentStudio.STARTED = true; - final File workspaceRoot = new File(wsSelect.selected); - WorkerDialog.showTaskMessage("Loading your workspace...", null, new Runnable() { - public void run() { - Workspace.setActive(workspaceRoot); - if (Workspace.activeWorkspace.settings.useInternet.getCurrentValue() - && Workspace.activeWorkspace.settings.checkUpdates.getCurrentValue()) { - new Thread() { - public void run() { - checkUpdate(); - } - }.start(); - } - frame = new StudioFrame(APP_NAME + " " + APP_VERSION); - frame.setVisible(true); - frame.setDefaultCloseOperation(StudioFrame.DO_NOTHING_ON_CLOSE); - }; - }); - for (File f : ConfigCache.getKnownWorkspaces()) { - if (workspaceRoot.equals(f)) { - if (!workspaceRoot.equals(ConfigCache.getLatestWorkspace())) { - ConfigCache.setLatestWorkspace(f); - } - return; - } - } - ConfigCache.addWorkspace(workspaceRoot); - ConfigCache.setLatestWorkspace(workspaceRoot); + wsSelect.addWindowListener(new WindowAdapter() { + @Override + public synchronized void windowClosed(WindowEvent e) { + if (wsSelect.selected != null && !STARTED) { + ATContentStudio.STARTED = true; + final File workspaceRoot = new File(wsSelect.selected); + WorkerDialog.showTaskMessage("Loading your workspace...", null, new Runnable() { + public void run() { + Workspace.setActive(workspaceRoot); + if (Workspace.activeWorkspace.settings.useInternet.getCurrentValue() + && Workspace.activeWorkspace.settings.checkUpdates.getCurrentValue()) { + new Thread() { + public void run() { + checkUpdate(); + } + }.start(); + } + frame = new StudioFrame(APP_NAME + " " + APP_VERSION); + frame.setVisible(true); + frame.setDefaultCloseOperation(StudioFrame.DO_NOTHING_ON_CLOSE); + } - } - } - }); - } + ; + }); + for (File f : ConfigCache.getKnownWorkspaces()) { + if (workspaceRoot.equals(f)) { + if (!workspaceRoot.equals(ConfigCache.getLatestWorkspace())) { + ConfigCache.setLatestWorkspace(f); + } + return; + } + } + ConfigCache.addWorkspace(workspaceRoot); + ConfigCache.setLatestWorkspace(workspaceRoot); - private static void checkUpdate() { - BufferedReader in = null; - try { - URL url = new URL(CHECK_UPDATE_URL); - in = new BufferedReader(new InputStreamReader(url.openStream())); + } + } + }); + } - String inputLine, lastLine = null; - while ((inputLine = in.readLine()) != null) { - lastLine = inputLine; - } - if (lastLine != null && !lastLine.equals(APP_VERSION)) { + private static void checkUpdate() { + BufferedReader in = null; + try { + URL url = new URL(CHECK_UPDATE_URL); + in = new BufferedReader(new InputStreamReader(url.openStream())); - // for copying style - JLabel label = new JLabel(); - Font font = label.getFont(); - Color color = label.getBackground(); + String inputLine, lastLine = null; + while ((inputLine = in.readLine()) != null) { + lastLine = inputLine; + } + if (lastLine != null && !lastLine.equals(APP_VERSION)) { - // create some css from the label's font - StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); - style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); - style.append("font-size:" + font.getSize() + "pt;"); - style.append("background-color: rgb(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() - + ");"); + // for copying style + JLabel label = new JLabel(); + Font font = label.getFont(); + Color color = label.getBackground(); - JEditorPane ep = new JEditorPane("text/html", - "" + "You are not running the latest ATCS version.
" - + "You can get the latest version (" + lastLine + ") by clicking the link below.
" - + "" + DOWNLOAD_URL + "
" + "
" - + ""); + // create some css from the label's font + StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";"); + style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); + style.append("font-size:" + font.getSize() + "pt;"); + style.append("background-color: rgb(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() + + ");"); - ep.setEditable(false); - ep.setBorder(null); + JEditorPane ep = new JEditorPane("text/html", + "" + "You are not running the latest ATCS version.
" + + "You can get the latest version (" + lastLine + ") by clicking the link below.
" + + "" + DOWNLOAD_URL + "
" + "
" + + ""); - ep.addHyperlinkListener(new HyperlinkListener() { + ep.setEditable(false); + ep.setBorder(null); - @Override - public void hyperlinkUpdate(HyperlinkEvent e) { - try { - if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { - Desktop.getDesktop().browse(e.getURL().toURI()); - } - } catch (IOException e1) { - e1.printStackTrace(); - } catch (URISyntaxException e1) { - e1.printStackTrace(); - } - } - }); + ep.addHyperlinkListener(new HyperlinkListener() { - JOptionPane.showMessageDialog(null, ep, "Update available", JOptionPane.INFORMATION_MESSAGE); - } - } catch (MalformedURLException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - if (in != null) - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + @Override + public void hyperlinkUpdate(HyperlinkEvent e) { + try { + if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { + Desktop.getDesktop().browse(e.getURL().toURI()); + } + } catch (IOException e1) { + e1.printStackTrace(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); + } + } + }); - public static void scaleUIFont() { - if (SCALING != 1.0f) { - System.out.println("Scaling fonts to " + SCALING); - UIDefaults defaults = UIManager.getLookAndFeelDefaults(); - Map newDefaults = new HashMap(); - for (Enumeration e = defaults.keys(); e.hasMoreElements();) { - Object key = e.nextElement(); - Object value = defaults.get(key); - if (value instanceof Font) { - Font font = (Font) value; - int newSize = (int) (font.getSize() * SCALING); - if (value instanceof FontUIResource) { - newDefaults.put(key, new FontUIResource(font.getName(), font.getStyle(), newSize)); - } else { - newDefaults.put(key, new Font(font.getName(), font.getStyle(), newSize)); - } - } - } - for (Object key : newDefaults.keySet()) { - defaults.put(key, newDefaults.get(key)); - } - } - } + JOptionPane.showMessageDialog(null, ep, "Update available", JOptionPane.INFORMATION_MESSAGE); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + if (in != null) + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static void scaleUIFont() { + if (SCALING != 1.0f) { + System.out.println("Scaling fonts to " + SCALING); + UIDefaults defaults = UIManager.getLookAndFeelDefaults(); + Map newDefaults = new HashMap(); + for (Enumeration e = defaults.keys(); e.hasMoreElements(); ) { + Object key = e.nextElement(); + Object value = defaults.get(key); + if (value instanceof Font) { + Font font = (Font) value; + int newSize = (int) (font.getSize() * SCALING); + if (value instanceof FontUIResource) { + newDefaults.put(key, new FontUIResource(font.getName(), font.getStyle(), newSize)); + } else { + newDefaults.put(key, new Font(font.getName(), font.getStyle(), newSize)); + } + } + } + for (Object key : newDefaults.keySet()) { + defaults.put(key, newDefaults.get(key)); + } + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ConfigCache.java b/src/com/gpl/rpg/atcontentstudio/ConfigCache.java index 42549d6..58cc3dc 100644 --- a/src/com/gpl/rpg/atcontentstudio/ConfigCache.java +++ b/src/com/gpl/rpg/atcontentstudio/ConfigCache.java @@ -1,103 +1,104 @@ package com.gpl.rpg.atcontentstudio; +import com.gpl.rpg.atcontentstudio.io.SettingsSave; + import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.List; -import com.gpl.rpg.atcontentstudio.io.SettingsSave; - public class ConfigCache implements Serializable { - private static final long serialVersionUID = 4584324644282843961L; - - private static final File CONFIG_CACHE_STORAGE; - - private static ConfigCache instance = null; + private static final long serialVersionUID = 4584324644282843961L; + + private static final File CONFIG_CACHE_STORAGE; + + private static ConfigCache instance = null; - static { - if (System.getenv("APPDATA") != null) { - CONFIG_CACHE_STORAGE = new File(System.getenv("APPDATA")+File.separator+ATContentStudio.APP_NAME+File.separator+"configCache" ); - } else { - CONFIG_CACHE_STORAGE = new File(System.getenv("HOME")+File.separator+"."+ATContentStudio.APP_NAME+File.separator+"configCache" ); - } - CONFIG_CACHE_STORAGE.getParentFile().mkdirs(); - if (CONFIG_CACHE_STORAGE.exists()) { - ConfigCache.instance = (ConfigCache) SettingsSave.loadInstance(CONFIG_CACHE_STORAGE, "Configuration cache"); - if (ConfigCache.instance == null) { - ConfigCache.instance = new ConfigCache(); - } - } else { - ConfigCache.instance = new ConfigCache(); - } - } + static { + if (System.getenv("APPDATA") != null) { + CONFIG_CACHE_STORAGE = new File(System.getenv("APPDATA") + File.separator + ATContentStudio.APP_NAME + File.separator + "configCache"); + } else { + CONFIG_CACHE_STORAGE = new File(System.getenv("HOME") + File.separator + "." + ATContentStudio.APP_NAME + File.separator + "configCache"); + } + CONFIG_CACHE_STORAGE.getParentFile().mkdirs(); + if (CONFIG_CACHE_STORAGE.exists()) { + ConfigCache.instance = (ConfigCache) SettingsSave.loadInstance(CONFIG_CACHE_STORAGE, "Configuration cache"); + if (ConfigCache.instance == null) { + ConfigCache.instance = new ConfigCache(); + } + } else { + ConfigCache.instance = new ConfigCache(); + } + } - private void save() { - SettingsSave.saveInstance(instance, ConfigCache.CONFIG_CACHE_STORAGE, "Configuration cache"); - } + private void save() { + SettingsSave.saveInstance(instance, ConfigCache.CONFIG_CACHE_STORAGE, "Configuration cache"); + } - private List knownWorkspaces = new ArrayList(); - private File latestWorkspace = null; - private String favoriteLaFClassName = null; - private boolean[] notifConfig = new boolean[]{true, true, true, true}; + private List knownWorkspaces = new ArrayList(); + private File latestWorkspace = null; + private String favoriteLaFClassName = null; + private boolean[] notifConfig = new boolean[]{true, true, true, true}; - - public static List getKnownWorkspaces() { - return instance.knownWorkspaces; - } - - public static void addWorkspace(File w) { - instance.knownWorkspaces.add(w); - instance.save(); - } - - public static void removeWorkspace(File w) { - instance.knownWorkspaces.remove(w); - instance.save(); - } - - public static File getLatestWorkspace() { - return instance.latestWorkspace; - } - public static void setLatestWorkspace(File latestWorkspace) { - instance.latestWorkspace = latestWorkspace; - instance.save(); - } + public static List getKnownWorkspaces() { + return instance.knownWorkspaces; + } - public static String getFavoriteLaFClassName() { - return instance.favoriteLaFClassName; - } - - public static void setFavoriteLaFClassName(String favoriteLaFClassName) { - instance.favoriteLaFClassName = favoriteLaFClassName; - instance.save(); - } + public static void addWorkspace(File w) { + instance.knownWorkspaces.add(w); + instance.save(); + } - public static void putNotifViewConfig(boolean[] view) { - for (int i=instance.notifConfig.length; i<0; --i) { - instance.notifConfig[i] = view[i]; - } - instance.save(); - } + public static void removeWorkspace(File w) { + instance.knownWorkspaces.remove(w); + instance.save(); + } - public static boolean[] getNotifViewConfig() { - if (instance == null || instance.notifConfig == null) { - //Not yet initialized. All flags on to help corner out init issues. - return new boolean[]{true, true, true, true}; - } - return instance.notifConfig; - } + public static File getLatestWorkspace() { + return instance.latestWorkspace; + } - public static void init() {} + public static void setLatestWorkspace(File latestWorkspace) { + instance.latestWorkspace = latestWorkspace; + instance.save(); + } - public static void clear() { - instance.knownWorkspaces.clear(); - setFavoriteLaFClassName(null); - instance.notifConfig = new boolean[]{true, true, true, true}; - instance.save(); - } + public static String getFavoriteLaFClassName() { + return instance.favoriteLaFClassName; + } + + public static void setFavoriteLaFClassName(String favoriteLaFClassName) { + instance.favoriteLaFClassName = favoriteLaFClassName; + instance.save(); + } + + public static void putNotifViewConfig(boolean[] view) { + for (int i = instance.notifConfig.length; i < 0; --i) { + instance.notifConfig[i] = view[i]; + } + instance.save(); + } + + public static boolean[] getNotifViewConfig() { + if (instance == null || instance.notifConfig == null) { + //Not yet initialized. All flags on to help corner out init issues. + return new boolean[]{true, true, true, true}; + } + return instance.notifConfig; + } + + public static void init() { + } + + public static void clear() { + instance.knownWorkspaces.clear(); + setFavoriteLaFClassName(null); + instance.notifConfig = new boolean[]{true, true, true, true}; + instance.save(); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/Notification.java b/src/com/gpl/rpg/atcontentstudio/Notification.java index 6cf184e..d3d6e33 100644 --- a/src/com/gpl/rpg/atcontentstudio/Notification.java +++ b/src/com/gpl/rpg/atcontentstudio/Notification.java @@ -6,87 +6,87 @@ import java.util.concurrent.CopyOnWriteArrayList; public class Notification { - public static List notifs = new ArrayList(); - private static List listeners = new CopyOnWriteArrayList(); - public static boolean showS, showI, showW, showE; - - static { - boolean[] config = ConfigCache.getNotifViewConfig(); - showS = config[0]; - showI = config[1]; - showW = config[2]; - showE = config[3]; - } - - public static enum Type { - SUCCESS, - INFO, - WARN, - ERROR - } - - public Type type; - public String text; - - public Notification(Type type, String text) { - this.type = type; - this.text = text; - } - - public String toString() { - return "["+type.toString()+"] "+text; - } - - public static void clear() { - int i = notifs.size(); - notifs.clear(); - for (NotificationListener l : listeners) { - l.onListCleared(i); - } - } + public static List notifs = new ArrayList(); + private static List listeners = new CopyOnWriteArrayList(); + public static boolean showS, showI, showW, showE; + + static { + boolean[] config = ConfigCache.getNotifViewConfig(); + showS = config[0]; + showI = config[1]; + showW = config[2]; + showE = config[3]; + } + + public static enum Type { + SUCCESS, + INFO, + WARN, + ERROR + } + + public Type type; + public String text; + + public Notification(Type type, String text) { + this.type = type; + this.text = text; + } + + public String toString() { + return "[" + type.toString() + "] " + text; + } + + public static void clear() { + int i = notifs.size(); + notifs.clear(); + for (NotificationListener l : listeners) { + l.onListCleared(i); + } + } + + public static void addSuccess(String text) { + if (!showS) return; + Notification n = new Notification(Notification.Type.SUCCESS, text); + notifs.add(n); + for (NotificationListener l : listeners) { + l.onNewNotification(n); + } + } + + public static void addInfo(String text) { + if (!showI) return; + Notification n = new Notification(Notification.Type.INFO, text); + notifs.add(n); + for (NotificationListener l : listeners) { + l.onNewNotification(n); + } + } + + public static void addWarn(String text) { + if (!showW) return; + Notification n = new Notification(Notification.Type.WARN, text); + notifs.add(n); + for (NotificationListener l : listeners) { + l.onNewNotification(n); + } + } + + public static void addError(String text) { + if (!showE) return; + Notification n = new Notification(Notification.Type.ERROR, text); + notifs.add(n); + for (NotificationListener l : listeners) { + l.onNewNotification(n); + } + } + + public static void addNotificationListener(NotificationListener l) { + listeners.add(l); + } + + public static void removeNotificationListener(NotificationListener l) { + listeners.remove(l); + } - public static void addSuccess(String text) { - if (!showS) return; - Notification n = new Notification(Notification.Type.SUCCESS, text); - notifs.add(n); - for (NotificationListener l : listeners) { - l.onNewNotification(n); - } - } - - public static void addInfo(String text) { - if (!showI) return; - Notification n = new Notification(Notification.Type.INFO, text); - notifs.add(n); - for (NotificationListener l : listeners) { - l.onNewNotification(n); - } - } - - public static void addWarn(String text) { - if (!showW) return; - Notification n = new Notification(Notification.Type.WARN, text); - notifs.add(n); - for (NotificationListener l : listeners) { - l.onNewNotification(n); - } - } - - public static void addError(String text) { - if (!showE) return; - Notification n = new Notification(Notification.Type.ERROR, text); - notifs.add(n); - for (NotificationListener l : listeners) { - l.onNewNotification(n); - } - } - - public static void addNotificationListener(NotificationListener l) { - listeners.add(l); - } - - public static void removeNotificationListener(NotificationListener l) { - listeners.remove(l); - } - } \ No newline at end of file diff --git a/src/com/gpl/rpg/atcontentstudio/NotificationListener.java b/src/com/gpl/rpg/atcontentstudio/NotificationListener.java index f5b265f..b015e68 100644 --- a/src/com/gpl/rpg/atcontentstudio/NotificationListener.java +++ b/src/com/gpl/rpg/atcontentstudio/NotificationListener.java @@ -2,7 +2,8 @@ package com.gpl.rpg.atcontentstudio; public interface NotificationListener { - public void onNewNotification(Notification n); - public void onListCleared(int i); - + public void onNewNotification(Notification n); + + public void onListCleared(int i); + } \ No newline at end of file diff --git a/src/com/gpl/rpg/atcontentstudio/io/JsonPrettyWriter.java b/src/com/gpl/rpg/atcontentstudio/io/JsonPrettyWriter.java index f3e5a80..65f47a2 100644 --- a/src/com/gpl/rpg/atcontentstudio/io/JsonPrettyWriter.java +++ b/src/com/gpl/rpg/atcontentstudio/io/JsonPrettyWriter.java @@ -4,50 +4,50 @@ import java.io.StringWriter; public class JsonPrettyWriter extends StringWriter { - private int indentLevel = 0; - private String indentText = " "; - - public JsonPrettyWriter() { - super(); - } - - public JsonPrettyWriter(String indent) { - super(); - this.indentText = indent; - } + private int indentLevel = 0; + private String indentText = " "; - @Override - public void write(int c) { - if (((char) c) == '[' || ((char) c) == '{') { - super.write(c); - super.write('\n'); - indentLevel++; - writeIndentation(); - } else if (((char) c) == ',') { - super.write(c); - super.write('\n'); - writeIndentation(); - } else if (((char) c) == ']' || ((char) c) == '}') { - super.write('\n'); - indentLevel--; - writeIndentation(); - super.write(c); - } else { - super.write(c); - } + public JsonPrettyWriter() { + super(); + } - } - - //Horrible hack to remove the horrible escaping of slashes in json-simple.... - @Override - public void write(String str) { - super.write(str.replaceAll("\\\\/", "/")); - } + public JsonPrettyWriter(String indent) { + super(); + this.indentText = indent; + } - private void writeIndentation() { - for (int i = 0; i < indentLevel; i++) { - super.write(indentText); - } - } + @Override + public void write(int c) { + if (((char) c) == '[' || ((char) c) == '{') { + super.write(c); + super.write('\n'); + indentLevel++; + writeIndentation(); + } else if (((char) c) == ',') { + super.write(c); + super.write('\n'); + writeIndentation(); + } else if (((char) c) == ']' || ((char) c) == '}') { + super.write('\n'); + indentLevel--; + writeIndentation(); + super.write(c); + } else { + super.write(c); + } + + } + + //Horrible hack to remove the horrible escaping of slashes in json-simple.... + @Override + public void write(String str) { + super.write(str.replaceAll("\\\\/", "/")); + } + + private void writeIndentation() { + for (int i = 0; i < indentLevel; i++) { + super.write(indentText); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/io/SettingsSave.java b/src/com/gpl/rpg/atcontentstudio/io/SettingsSave.java index 21bc3bc..c5eccb8 100644 --- a/src/com/gpl/rpg/atcontentstudio/io/SettingsSave.java +++ b/src/com/gpl/rpg/atcontentstudio/io/SettingsSave.java @@ -1,76 +1,70 @@ package com.gpl.rpg.atcontentstudio.io; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - import com.gpl.rpg.atcontentstudio.Notification; +import java.io.*; + public class SettingsSave { - public static void saveInstance(Object obj, File f, String type) { - try { - FileOutputStream fos = new FileOutputStream(f); - try { - ObjectOutputStream oos = new ObjectOutputStream(fos); - oos.writeObject(obj); - oos.flush(); - oos.close(); - Notification.addSuccess(type+" successfully saved."); - } catch (IOException e) { - e.printStackTrace(); - Notification.addError(type+" saving error: "+e.getMessage()); - } finally { - try { - fos.close(); - } catch (IOException e) { - e.printStackTrace(); - Notification.addError(type+" saving error: "+e.getMessage()); - } - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - Notification.addError(type+" saving error: "+e.getMessage()); - } - } - - public static Object loadInstance(File f, String type) { - FileInputStream fis; - Object result = null; - try { - fis = new FileInputStream(f); - ObjectInputStream ois; - try { - ois = new ObjectInputStream(fis); - try { - result = ois.readObject(); - Notification.addSuccess(type+" successfully loaded."); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - Notification.addError(type+" loading error: "+e.getMessage()); - } finally { - ois.close(); - } - } catch (IOException e) { - e.printStackTrace(); - Notification.addError(type+" loading error: "+e.getMessage()); - } finally { - try { - fis.close(); - } catch (IOException e) { - e.printStackTrace(); - Notification.addError(type+" loading error: "+e.getMessage()); - } - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - Notification.addError(type+" loading error: "+e.getMessage()); - } - return result; - } - + public static void saveInstance(Object obj, File f, String type) { + try { + FileOutputStream fos = new FileOutputStream(f); + try { + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(obj); + oos.flush(); + oos.close(); + Notification.addSuccess(type + " successfully saved."); + } catch (IOException e) { + e.printStackTrace(); + Notification.addError(type + " saving error: " + e.getMessage()); + } finally { + try { + fos.close(); + } catch (IOException e) { + e.printStackTrace(); + Notification.addError(type + " saving error: " + e.getMessage()); + } + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + Notification.addError(type + " saving error: " + e.getMessage()); + } + } + + public static Object loadInstance(File f, String type) { + FileInputStream fis; + Object result = null; + try { + fis = new FileInputStream(f); + ObjectInputStream ois; + try { + ois = new ObjectInputStream(fis); + try { + result = ois.readObject(); + Notification.addSuccess(type + " successfully loaded."); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + Notification.addError(type + " loading error: " + e.getMessage()); + } finally { + ois.close(); + } + } catch (IOException e) { + e.printStackTrace(); + Notification.addError(type + " loading error: " + e.getMessage()); + } finally { + try { + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + Notification.addError(type + " loading error: " + e.getMessage()); + } + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + Notification.addError(type + " loading error: " + e.getMessage()); + } + return result; + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/model/ClosedProject.java b/src/com/gpl/rpg/atcontentstudio/model/ClosedProject.java index db92f88..0ce838b 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/ClosedProject.java +++ b/src/com/gpl/rpg/atcontentstudio/model/ClosedProject.java @@ -1,124 +1,135 @@ package com.gpl.rpg.atcontentstudio.model; -import java.awt.Image; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + public class ClosedProject implements ProjectTreeNode { - String name; - Workspace parent; - - public ClosedProject(Workspace w, String name) { - this.parent = w; - this.name = name; - } + String name; + Workspace parent; - @Override - public TreeNode getChildAt(int childIndex) { - return null; - } - @Override - public int getChildCount() { - return 0; - } - @Override - public TreeNode getParent() { - return parent; - } - @Override - public int getIndex(TreeNode node) { - return 0; - } - @Override - public boolean getAllowsChildren() { - return false; - } - @Override - public boolean isLeaf() { - return true; - } - @Override - public Enumeration children() { - return null; - } - - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - path.add(0,this); - parent.childrenRemoved(path); - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } + public ClosedProject(Workspace w, String name) { + this.parent = w; + this.name = name; + } - @Override - public String getDesc() { - return name+" [closed]"; - } - - @Override - public Project getProject() { - return null; - } + @Override + public TreeNode getChildAt(int childIndex) { + return null; + } + + @Override + public int getChildCount() { + return 0; + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public int getIndex(TreeNode node) { + return 0; + } + + @Override + public boolean getAllowsChildren() { + return false; + } + + @Override + public boolean isLeaf() { + return true; + } + + @Override + public Enumeration children() { + return null; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } + + @Override + public String getDesc() { + return name + " [closed]"; + } + + @Override + public Project getProject() { + return null; + } - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - //TODO Create a cool Project icon. - return DefaultIcons.getStdClosedIcon(); - } - @Override - public Image getLeafIcon() { - //TODO Create a cool Project icon. - return DefaultIcons.getStdClosedIcon(); - } - @Override - public Image getOpenIcon() { - //TODO Create a cool Project icon. - return DefaultIcons.getStdOpenIcon(); - } - - @Override - public GameDataSet getDataSet() { - return null; - } + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + //TODO Create a cool Project icon. + return DefaultIcons.getStdClosedIcon(); + } + + @Override + public Image getLeafIcon() { + //TODO Create a cool Project icon. + return DefaultIcons.getStdClosedIcon(); + } + + @Override + public Image getOpenIcon() { + //TODO Create a cool Project icon. + return DefaultIcons.getStdOpenIcon(); + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return null; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean needsSaving() { + return false; + } - @Override - public Type getDataType() { - return null; - } - - @Override - public boolean isEmpty() { - return true; - } - - @Override - public boolean needsSaving() { - return false; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java index bd5a4a6..46bc743 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java @@ -1,216 +1,229 @@ package com.gpl.rpg.atcontentstudio.model; -import java.awt.Image; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.model.bookmarks.BookmarkEntry; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.Serializable; +import java.util.List; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; + public abstract class GameDataElement implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = 2028934451226743389L; - - public static enum State { - init, // We know the object exists, and have its key/ID. - parsed, // We know the object's properties, but related objects are referenced by ID only. - linked, // We know the object fully, and all links to related objects point to objects in the parsed state at least. - created, // This is an object we are creating - modified, // Whether altered or created, this item has been modified since creation from scratch or from JSON. - saved // Whether altered or created, this item has been saved since last modification. - } - - public State state = State.init; - - //Available from state init. - public ProjectTreeNode parent; - - public boolean writable = false; - - public BookmarkEntry bookmark = null; - - //List of objects whose transition to "linked" state made them point to this instance. - private Map backlinks = new ConcurrentHashMap(); + private static final long serialVersionUID = 2028934451226743389L; - public String id = null; + public static enum State { + init, // We know the object exists, and have its key/ID. + parsed, // We know the object's properties, but related objects are referenced by ID only. + linked, // We know the object fully, and all links to related objects point to objects in the parsed state at least. + created, // This is an object we are creating + modified, // Whether altered or created, this item has been modified since creation from scratch or from JSON. + saved // Whether altered or created, this item has been saved since last modification. + } - protected boolean linkCheck(){ - if (checkNotRelatedToParseOrLink()) { - //This type of state is unrelated to parsing/linking. - return false; - } - else if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return false; - } - return true; + public State state = State.init; - } + //Available from state init. + public ProjectTreeNode parent; - protected boolean checkNotRelatedToParseOrLink() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return true; - } - return false; - } - @Override - public Enumeration children() { - return null; - } - @Override - public boolean getAllowsChildren() { - return false; - } - @Override - public TreeNode getChildAt(int arg0) { - return null; - } - @Override - public int getChildCount() { - return 0; - } - @Override - public int getIndex(TreeNode arg0) { - return 0; - } - @Override - public TreeNode getParent() { - return parent; - } - @Override - public boolean isLeaf() { - return true; - } - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } + public boolean writable = false; - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } + public BookmarkEntry bookmark = null; - @Override - public void childrenRemoved(List path) { - path.add(0,this); - parent.childrenRemoved(path); - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } - @Override - public abstract String getDesc(); - - public static String getStaticDesc() { - return "GameDataElements"; - } - - public abstract void parse(); - public abstract void link(); - - - - @Override - public Project getProject() { - return parent == null ? null : parent.getProject(); - } - - - public Image getIcon() { - return null; - } - @Override - public Image getClosedIcon() {return null;} - @Override - public Image getOpenIcon() {return null;} - @Override - public Image getLeafIcon() { - return getIcon(); - } - - - public abstract GameDataElement clone(); - - public abstract void elementChanged(GameDataElement oldOne, GameDataElement newOne); + //List of objects whose transition to "linked" state made them point to this instance. + private Map backlinks = new ConcurrentHashMap(); - - @Override - public GameSource.Type getDataType() { - if (parent == null) { - System.out.println("blerf."); - } - return parent.getDataType(); - } - - - public List backlinkListeners = new ArrayList(); - - public void addBacklinkListener(BacklinksListener l) { - backlinkListeners.add(l); - } + public String id = null; - public void removeBacklinkListener(BacklinksListener l) { - backlinkListeners.remove(l); - } - - public void addBacklink(GameDataElement gde) { - if (!backlinks.containsKey(gde)) { - backlinks.put(gde, 1); - for (BacklinksListener l : backlinkListeners) { - l.backlinkAdded(gde); - } - } else { - backlinks.put(gde, backlinks.get(gde) + 1); - } - } + protected boolean linkCheck() { + if (checkNotRelatedToParseOrLink()) { + //This type of state is unrelated to parsing/linking. + return false; + } else if (this.state == State.init) { + //Not parsed yet. + this.parse(); + } else if (this.state == State.linked) { + //Already linked. + return false; + } + return true; - public void removeBacklink(GameDataElement gde) { - if (backlinks.get(gde) == null) return; - backlinks.put(gde, backlinks.get(gde) - 1); - if (backlinks.get(gde) == 0) { - backlinks.remove(gde); - for (BacklinksListener l : backlinkListeners) { - l.backlinkRemoved(gde); - } - } - } + } + + protected boolean checkNotRelatedToParseOrLink() { + if (this.state == State.created || this.state == State.modified || this.state == State.saved) { + //This type of state is unrelated to parsing/linking. + return true; + } + return false; + } + + @Override + public Enumeration children() { + return null; + } + + @Override + public boolean getAllowsChildren() { + return false; + } + + @Override + public TreeNode getChildAt(int arg0) { + return null; + } + + @Override + public int getChildCount() { + return 0; + } + + @Override + public int getIndex(TreeNode arg0) { + return 0; + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public boolean isLeaf() { + return true; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } + + @Override + public abstract String getDesc(); + + public static String getStaticDesc() { + return "GameDataElements"; + } + + public abstract void parse(); + + public abstract void link(); + + + @Override + public Project getProject() { + return parent == null ? null : parent.getProject(); + } + + + public Image getIcon() { + return null; + } + + @Override + public Image getClosedIcon() { + return null; + } + + @Override + public Image getOpenIcon() { + return null; + } + + @Override + public Image getLeafIcon() { + return getIcon(); + } + + + public abstract GameDataElement clone(); + + public abstract void elementChanged(GameDataElement oldOne, GameDataElement newOne); + + + @Override + public GameSource.Type getDataType() { + if (parent == null) { + System.out.println("blerf."); + } + return parent.getDataType(); + } + + + public List backlinkListeners = new ArrayList(); + + public void addBacklinkListener(BacklinksListener l) { + backlinkListeners.add(l); + } + + public void removeBacklinkListener(BacklinksListener l) { + backlinkListeners.remove(l); + } + + public void addBacklink(GameDataElement gde) { + if (!backlinks.containsKey(gde)) { + backlinks.put(gde, 1); + for (BacklinksListener l : backlinkListeners) { + l.backlinkAdded(gde); + } + } else { + backlinks.put(gde, backlinks.get(gde) + 1); + } + } + + public void removeBacklink(GameDataElement gde) { + if (backlinks.get(gde) == null) return; + backlinks.put(gde, backlinks.get(gde) - 1); + if (backlinks.get(gde) == 0) { + backlinks.remove(gde); + for (BacklinksListener l : backlinkListeners) { + l.backlinkRemoved(gde); + } + } + } + + public Set getBacklinks() { + return backlinks.keySet(); + } + + public static interface BacklinksListener { + public void backlinkAdded(GameDataElement gde); + + public void backlinkRemoved(GameDataElement gde); + } + + @Override + public boolean isEmpty() { + return false; + } + + public boolean needsSaving() { + return this.state == State.modified || this.state == State.created; + } + + public abstract String getProjectFilename(); + + public abstract void save(); + + public abstract List attemptSave(); - public Set getBacklinks() { - return backlinks.keySet(); - } - - public static interface BacklinksListener { - public void backlinkAdded(GameDataElement gde); - public void backlinkRemoved(GameDataElement gde); - } - - @Override - public boolean isEmpty() { - return false; - } - - public boolean needsSaving() { - return this.state == State.modified || this.state == State.created; - } - - public abstract String getProjectFilename(); - - public abstract void save(); - - public abstract List attemptSave(); - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/GameSource.java b/src/com/gpl/rpg/atcontentstudio/model/GameSource.java index 043d5d2..0c0a95b 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/GameSource.java +++ b/src/com/gpl/rpg/atcontentstudio/model/GameSource.java @@ -1,28 +1,5 @@ package com.gpl.rpg.atcontentstudio.model; -import java.awt.Image; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.tree.TreeNode; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - import com.gpl.rpg.atcontentstudio.model.Project.ResourceSet; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet; @@ -32,263 +9,297 @@ import com.gpl.rpg.atcontentstudio.model.sprites.SpriteSheetSet; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.swing.tree.TreeNode; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.awt.*; +import java.io.*; +import java.util.List; +import java.util.*; public class GameSource implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = -1512979360971918158L; - - public static final String DEFAULT_REL_PATH_FOR_GAME_RESOURCE = "res"+File.separator+"values"+File.separator+"loadresources.xml"; - public static final String DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE = "res"+File.separator+"values"+File.separator+"loadresources_debug.xml"; - - public transient GameDataSet gameData; - public transient TMXMapSet gameMaps; - public transient SpriteSheetSet gameSprites; - public transient Worldmap worldmap; - public transient WriterModeDataSet writerModeDataSet; - private transient SavedSlotCollection v; - - public static enum Type { - source, - referenced, - altered, - created - } - - public File baseFolder; - public Type type; - - public transient Project parent; - - public transient Map> referencedSourceFiles = null; - - public GameSource(File folder, Project parent) { - this.parent = parent; - this.baseFolder = folder; - this.type = Type.source; - initData(); - } - - public GameSource(Project parent, Type type) { - this.parent = parent; - this.baseFolder = new File(parent.baseFolder, type.toString()); - this.type = type; - initData(); - } - - public void refreshTransients(Project p) { - parent = p; - initData(); - } + private static final long serialVersionUID = -1512979360971918158L; - public void initData() { - if (type == Type.source) { - if (parent.sourceSetToUse == ResourceSet.gameData || parent.sourceSetToUse == ResourceSet.debugData) { - referencedSourceFiles = new LinkedHashMap>(); - readResourceList(); - } - } - if (type == Type.created) { - this.writerModeDataSet = new WriterModeDataSet(this); - } - this.gameData = new GameDataSet(this); - this.gameMaps = new TMXMapSet(this); - this.gameSprites = new SpriteSheetSet(this); - this.worldmap = new Worldmap(this); - v = new SavedSlotCollection(); - v.add(gameData); - v.add(gameMaps); - v.add(gameSprites); - v.add(worldmap); - if (type == Type.created) { - v.add(writerModeDataSet); - } - } - - public void readResourceList() { - File xmlFile; - if (parent.sourceSetToUse == ResourceSet.gameData) { - xmlFile = new File(baseFolder, DEFAULT_REL_PATH_FOR_GAME_RESOURCE); - } else if (parent.sourceSetToUse == ResourceSet.debugData) { - xmlFile = new File(baseFolder, DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE); - } else { - return; - } - - if (!xmlFile.exists()) return; - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - Document doc; - try { - factory.setIgnoringComments(true); - factory.setIgnoringElementContentWhitespace(true); - factory.setExpandEntityReferences(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource insrc = new InputSource(new FileInputStream(xmlFile)); + public static final String DEFAULT_REL_PATH_FOR_GAME_RESOURCE = "res" + File.separator + "values" + File.separator + "loadresources.xml"; + public static final String DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE = "res" + File.separator + "values" + File.separator + "loadresources_debug.xml"; + + public transient GameDataSet gameData; + public transient TMXMapSet gameMaps; + public transient SpriteSheetSet gameSprites; + public transient Worldmap worldmap; + public transient WriterModeDataSet writerModeDataSet; + private transient SavedSlotCollection v; + + public static enum Type { + source, + referenced, + altered, + created + } + + public File baseFolder; + public Type type; + + public transient Project parent; + + public transient Map> referencedSourceFiles = null; + + public GameSource(File folder, Project parent) { + this.parent = parent; + this.baseFolder = folder; + this.type = Type.source; + initData(); + } + + public GameSource(Project parent, Type type) { + this.parent = parent; + this.baseFolder = new File(parent.baseFolder, type.toString()); + this.type = type; + initData(); + } + + public void refreshTransients(Project p) { + parent = p; + initData(); + } + + public void initData() { + if (type == Type.source) { + if (parent.sourceSetToUse == ResourceSet.gameData || parent.sourceSetToUse == ResourceSet.debugData) { + referencedSourceFiles = new LinkedHashMap>(); + readResourceList(); + } + } + if (type == Type.created) { + this.writerModeDataSet = new WriterModeDataSet(this); + } + this.gameData = new GameDataSet(this); + this.gameMaps = new TMXMapSet(this); + this.gameSprites = new SpriteSheetSet(this); + this.worldmap = new Worldmap(this); + v = new SavedSlotCollection(); + v.add(gameData); + v.add(gameMaps); + v.add(gameSprites); + v.add(worldmap); + if (type == Type.created) { + v.add(writerModeDataSet); + } + } + + public void readResourceList() { + File xmlFile; + if (parent.sourceSetToUse == ResourceSet.gameData) { + xmlFile = new File(baseFolder, DEFAULT_REL_PATH_FOR_GAME_RESOURCE); + } else if (parent.sourceSetToUse == ResourceSet.debugData) { + xmlFile = new File(baseFolder, DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE); + } else { + return; + } + + if (!xmlFile.exists()) return; + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + Document doc; + try { + factory.setIgnoringComments(true); + factory.setIgnoringElementContentWhitespace(true); + factory.setExpandEntityReferences(false); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource insrc = new InputSource(new FileInputStream(xmlFile)); // insrc.setSystemId("http://worldmap/"); - insrc.setEncoding("UTF-8"); - doc = builder.parse(insrc); - - Element root = (Element) doc.getElementsByTagName("resources").item(0); - if (root != null) { - NodeList arraysList = root.getElementsByTagName("array"); - if (arraysList != null) { - for (int i = 0; i < arraysList.getLength(); i++) { - Element arrayNode = (Element) arraysList.item(i); - String name = arrayNode.getAttribute("name"); - List arrayContents = new ArrayList(); - NodeList arrayItems = arrayNode.getElementsByTagName("item"); - if (arrayItems != null) { - for (int j = 0; j < arrayItems.getLength(); j++) { - arrayContents.add(((Element)arrayItems.item(j)).getTextContent()); - } - referencedSourceFiles.put(name, arrayContents); - } - } - } - } - } catch (SAXException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public Enumeration children() { - return v.getNonEmptyElements(); - } - @Override - public boolean getAllowsChildren() { - return true; - } - @Override - public TreeNode getChildAt(int arg0) { - return v.getNonEmptyElementAt(arg0); - } - @Override - public int getChildCount() { - return v.getNonEmptySize(); - } - @Override - public int getIndex(TreeNode arg0) { - return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); - } - @Override - public TreeNode getParent() { - return parent; - } - @Override - public boolean isLeaf() { - return false; - } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.v.getNonEmptySize() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (ProjectTreeNode node : v.getNonEmptyIterable()) { - node.notifyCreated(); - } - } - @Override - public String getDesc() { - switch(type) { - case altered: return (needsSaving() ? "*" : "")+"Altered data"; - case created: return (needsSaving() ? "*" : "")+"Created data"; - case referenced: return (needsSaving() ? "*" : "")+"Referenced data"; - case source: return (needsSaving() ? "*" : "")+"AT Source"; //The fact that it is from "source" is already mentionned by its parent. - default: return (needsSaving() ? "*" : "")+"Game data"; - } - } - - - @Override - public Project getProject() { - return parent == null ? null : parent.getProject(); - } + insrc.setEncoding("UTF-8"); + doc = builder.parse(insrc); - public Image getIcon(String iconId) { - String[] data = iconId.split(":"); - for (Spritesheet sheet : gameSprites.spritesheets) { - if (sheet.id.equals(data[0])) { - return sheet.getIcon(Integer.parseInt(data[1])); - } - } - return null; - } - - public Image getImage(String iconId) { - String[] data = iconId.split(":"); - for (Spritesheet sheet : gameSprites.spritesheets) { - if (sheet.id.equals(data[0])) { - return sheet.getImage(Integer.parseInt(data[1])); - } - } - return null; - } - + Element root = (Element) doc.getElementsByTagName("resources").item(0); + if (root != null) { + NodeList arraysList = root.getElementsByTagName("array"); + if (arraysList != null) { + for (int i = 0; i < arraysList.getLength(); i++) { + Element arrayNode = (Element) arraysList.item(i); + String name = arrayNode.getAttribute("name"); + List arrayContents = new ArrayList(); + NodeList arrayItems = arrayNode.getElementsByTagName("item"); + if (arrayItems != null) { + for (int j = 0; j < arrayItems.getLength(); j++) { + arrayContents.add(((Element) arrayItems.item(j)).getTextContent()); + } + referencedSourceFiles.put(name, arrayContents); + } + } + } + } + } catch (SAXException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - return DefaultIcons.getATClosedIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getATClosedIcon(); - } - @Override - public Image getOpenIcon() { - return DefaultIcons.getATOpenIcon(); - } - @Override - public GameDataSet getDataSet() { - return null; - } - + @Override + public Enumeration children() { + return v.getNonEmptyElements(); + } - @Override - public Type getDataType() { - return type; - } - - @Override - public boolean isEmpty() { - return v.isEmpty(); - } + @Override + public boolean getAllowsChildren() { + return true; + } - public WorldmapSegment getWorldmapSegment(String id) { - return worldmap.getWorldmapSegment(id); - } - - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : v.getNonEmptyIterable()) { - if (node.needsSaving()) return true; - } - return false; - } + @Override + public TreeNode getChildAt(int arg0) { + return v.getNonEmptyElementAt(arg0); + } + + @Override + public int getChildCount() { + return v.getNonEmptySize(); + } + + @Override + public int getIndex(TreeNode arg0) { + return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.v.getNonEmptySize() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (ProjectTreeNode node : v.getNonEmptyIterable()) { + node.notifyCreated(); + } + } + + @Override + public String getDesc() { + switch (type) { + case altered: + return (needsSaving() ? "*" : "") + "Altered data"; + case created: + return (needsSaving() ? "*" : "") + "Created data"; + case referenced: + return (needsSaving() ? "*" : "") + "Referenced data"; + case source: + return (needsSaving() ? "*" : "") + "AT Source"; //The fact that it is from "source" is already mentionned by its parent. + default: + return (needsSaving() ? "*" : "") + "Game data"; + } + } + + + @Override + public Project getProject() { + return parent == null ? null : parent.getProject(); + } + + public Image getIcon(String iconId) { + String[] data = iconId.split(":"); + for (Spritesheet sheet : gameSprites.spritesheets) { + if (sheet.id.equals(data[0])) { + return sheet.getIcon(Integer.parseInt(data[1])); + } + } + return null; + } + + public Image getImage(String iconId) { + String[] data = iconId.split(":"); + for (Spritesheet sheet : gameSprites.spritesheets) { + if (sheet.id.equals(data[0])) { + return sheet.getImage(Integer.parseInt(data[1])); + } + } + return null; + } + + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + return DefaultIcons.getATClosedIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getATClosedIcon(); + } + + @Override + public Image getOpenIcon() { + return DefaultIcons.getATOpenIcon(); + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + + @Override + public Type getDataType() { + return type; + } + + @Override + public boolean isEmpty() { + return v.isEmpty(); + } + + public WorldmapSegment getWorldmapSegment(String id) { + return worldmap.getWorldmapSegment(id); + } + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : v.getNonEmptyIterable()) { + if (node.needsSaving()) return true; + } + return false; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/Preferences.java b/src/com/gpl/rpg/atcontentstudio/model/Preferences.java index 36fa399..e43c2c0 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/Preferences.java +++ b/src/com/gpl/rpg/atcontentstudio/model/Preferences.java @@ -1,19 +1,19 @@ package com.gpl.rpg.atcontentstudio.model; -import java.awt.Dimension; +import java.awt.*; import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class Preferences implements Serializable { - private static final long serialVersionUID = 2455802658424031276L; - - public Dimension windowSize = null; - public Map splittersPositions = new HashMap(); - - public Preferences() { + private static final long serialVersionUID = 2455802658424031276L; + + public Dimension windowSize = null; + public Map splittersPositions = new HashMap(); + + public Preferences() { + + } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/Project.java b/src/com/gpl/rpg/atcontentstudio/model/Project.java index 61ffbf5..baea51c 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/Project.java +++ b/src/com/gpl/rpg/atcontentstudio/model/Project.java @@ -1,69 +1,12 @@ package com.gpl.rpg.atcontentstudio.model; -import java.awt.Image; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Serializable; -import java.io.StringReader; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.swing.tree.TreeNode; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; - -import org.json.simple.JSONArray; -import org.w3c.dom.Comment; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import com.gpl.rpg.atcontentstudio.io.SettingsSave; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.bookmarks.BookmarksRoot; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet; import com.gpl.rpg.atcontentstudio.model.maps.Worldmap; @@ -74,1333 +17,1355 @@ import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.WorkerDialog; import com.gpl.rpg.atcontentstudio.utils.FileUtils; +import org.json.simple.JSONArray; +import org.w3c.dom.Comment; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.swing.tree.TreeNode; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import java.awt.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.*; public class Project implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = 4807454973303366758L; - private static final String drawablePath = TMXMapSet.DEFAULT_REL_PATH_TO_DRAWABLE.replace("\\", "/"); + private static final long serialVersionUID = 4807454973303366758L; + private static final String drawablePath = TMXMapSet.DEFAULT_REL_PATH_TO_DRAWABLE.replace("\\", "/"); - - //Every instance field that is not transient will be saved in this file. - public static final String SETTINGS_FILE = ".project"; - - public String name; - public File baseFolder; - public boolean open; - - public GameSource baseContent; //A.k.a library - - public GameSource referencedContent; //Pointers to base content - public transient GameSource alteredContent; //Copied from base content (does not overwrite yet) - public transient GameSource createdContent; //Stand-alone. - public transient BookmarksRoot bookmarks; - - - public SavedGamesSet saves; //For simulations. - - public transient SavedSlotCollection v; + //Every instance field that is not transient will be saved in this file. + public static final String SETTINGS_FILE = ".project"; - public transient Workspace parent; - - public Properties knownSpritesheetsProperties; - - public static enum ResourceSet { - gameData, - debugData, - allFiles - } - - public ResourceSet sourceSetToUse; + public String name; + + public File baseFolder; + public boolean open; + + public GameSource baseContent; //A.k.a library + + public GameSource referencedContent; //Pointers to base content + public transient GameSource alteredContent; //Copied from base content (does not overwrite yet) + public transient GameSource createdContent; //Stand-alone. + public transient BookmarksRoot bookmarks; + + + public SavedGamesSet saves; //For simulations. + + public transient SavedSlotCollection v; + + public transient Workspace parent; + + public Properties knownSpritesheetsProperties; + + public static enum ResourceSet { + gameData, + debugData, + allFiles + } + + public ResourceSet sourceSetToUse; + + public Project(Workspace w, String name, File source, ResourceSet sourceSet) { + this.parent = w; + this.name = name; + this.sourceSetToUse = sourceSet; + + //CREATE PROJECT + baseFolder = new File(w.baseFolder, name + File.separator); + try { + baseFolder.mkdir(); + } catch (SecurityException e) { + Notification.addError("Eror creating project root folder: " + e.getMessage()); + e.printStackTrace(); + } + open = true; + v = new SavedSlotCollection(); + + knownSpritesheetsProperties = new Properties(); + try { + knownSpritesheetsProperties.load(Project.class.getResourceAsStream("/spritesheets.properties")); + } catch (IOException e) { + Notification.addWarn("Unable to load default spritesheets properties."); + e.printStackTrace(); + } + + + baseContent = new GameSource(source, this); - public Project(Workspace w, String name, File source, ResourceSet sourceSet) { - this.parent = w; - this.name = name; - this.sourceSetToUse = sourceSet; - - //CREATE PROJECT - baseFolder = new File(w.baseFolder, name+File.separator); - try { - baseFolder.mkdir(); - } catch (SecurityException e) { - Notification.addError("Eror creating project root folder: "+e.getMessage()); - e.printStackTrace(); - } - open = true; - v = new SavedSlotCollection(); - - knownSpritesheetsProperties = new Properties(); - try { - knownSpritesheetsProperties.load(Project.class.getResourceAsStream("/spritesheets.properties")); - } catch (IOException e) { - Notification.addWarn("Unable to load default spritesheets properties."); - e.printStackTrace(); - } - - - baseContent = new GameSource(source, this); - // referencedContent = new GameSource(this, GameSource.Type.referenced); - alteredContent = new GameSource(this, GameSource.Type.altered); - createdContent = new GameSource(this, GameSource.Type.created); - bookmarks = new BookmarksRoot(this); - - saves = new SavedGamesSet(this); + alteredContent = new GameSource(this, GameSource.Type.altered); + createdContent = new GameSource(this, GameSource.Type.created); + bookmarks = new BookmarksRoot(this); - v.add(createdContent); - v.add(alteredContent); + saves = new SavedGamesSet(this); + + v.add(createdContent); + v.add(alteredContent); // v.add(referencedContent); - v.add(baseContent); - v.add(saves); - v.add(bookmarks); + v.add(baseContent); + v.add(saves); + v.add(bookmarks); - linkAll(); - - save(); - } - - - @Override - public TreeNode getChildAt(int childIndex) { - return v.getNonEmptyElementAt(childIndex); - } + linkAll(); - @Override - public int getChildCount() { - return v.getNonEmptySize(); - } - - @Override - public TreeNode getParent() { - return parent; - } - - @Override - public int getIndex(TreeNode node) { - return v.getNonEmptyIndexOf((ProjectTreeNode) node); - } - - @Override - public boolean getAllowsChildren() { - return open; - } - - @Override - public boolean isLeaf() { - return !open; - } - - @Override - public Enumeration children() { - return v.getNonEmptyElements(); - } - - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } - - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } - - @Override - public void childrenRemoved(List path) { - path.add(0,this); - parent.childrenRemoved(path); - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (ProjectTreeNode node : v.getNonEmptyIterable()) { - node.notifyCreated(); - } - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+name; - } + save(); + } - public void close() { - this.open = false; - childrenRemoved(new ArrayList()); - } + @Override + public TreeNode getChildAt(int childIndex) { + return v.getNonEmptyElementAt(childIndex); + } - public void open() { - open = true; - } + @Override + public int getChildCount() { + return v.getNonEmptySize(); + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public int getIndex(TreeNode node) { + return v.getNonEmptyIndexOf((ProjectTreeNode) node); + } + + @Override + public boolean getAllowsChildren() { + return open; + } + + @Override + public boolean isLeaf() { + return !open; + } + + @Override + public Enumeration children() { + return v.getNonEmptyElements(); + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (ProjectTreeNode node : v.getNonEmptyIterable()) { + node.notifyCreated(); + } + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + name; + } - public static Project fromFolder(Workspace w, File projRoot) { - Project p; - File f = new File(projRoot, Project.SETTINGS_FILE); - if (!f.exists()) { - Notification.addError("Unable to find "+SETTINGS_FILE+" for project "+projRoot.getName()); - return null; - } else { - p = (Project) SettingsSave.loadInstance(f, "Project"); - } - p.refreshTransients(w); - return p; - } - - public void refreshTransients(Workspace w) { - this.parent = w; + public void close() { + this.open = false; + childrenRemoved(new ArrayList()); + } - projectElementListeners = new HashMap, List>(); + public void open() { + open = true; + } + + + public static Project fromFolder(Workspace w, File projRoot) { + Project p; + File f = new File(projRoot, Project.SETTINGS_FILE); + if (!f.exists()) { + Notification.addError("Unable to find " + SETTINGS_FILE + " for project " + projRoot.getName()); + return null; + } else { + p = (Project) SettingsSave.loadInstance(f, "Project"); + } + p.refreshTransients(w); + return p; + } + + public void refreshTransients(Workspace w) { + this.parent = w; + + projectElementListeners = new HashMap, List>(); + + try { + knownSpritesheetsProperties = new Properties(); + knownSpritesheetsProperties.load(Project.class.getResourceAsStream("/spritesheets.properties")); + } catch (IOException e) { + Notification.addWarn("Unable to load default spritesheets properties."); + e.printStackTrace(); + } + + if (sourceSetToUse == null) { + sourceSetToUse = ResourceSet.allFiles; + } - try { - knownSpritesheetsProperties = new Properties(); - knownSpritesheetsProperties.load(Project.class.getResourceAsStream("/spritesheets.properties")); - } catch (IOException e) { - Notification.addWarn("Unable to load default spritesheets properties."); - e.printStackTrace(); - } - - if (sourceSetToUse == null) { - sourceSetToUse = ResourceSet.allFiles; - } - // long l = new Date().getTime(); - baseContent.refreshTransients(this); + baseContent.refreshTransients(this); // l = new Date().getTime() - l; // System.out.println("All initialized in "+l+"ms."); // referencedContent.refreshTransients(this); - alteredContent = new GameSource(this, GameSource.Type.altered); - createdContent = new GameSource(this, GameSource.Type.created); - bookmarks = new BookmarksRoot(this); - - saves.refreshTransients(); + alteredContent = new GameSource(this, GameSource.Type.altered); + createdContent = new GameSource(this, GameSource.Type.created); + bookmarks = new BookmarksRoot(this); - v = new SavedSlotCollection(); - v.add(createdContent); - v.add(alteredContent); + saves.refreshTransients(); + + v = new SavedSlotCollection(); + v.add(createdContent); + v.add(alteredContent); // v.add(referencedContent); - v.add(baseContent); - v.add(saves); - v.add(bookmarks); - - - linkAll(); - - } - - public void linkAll() { - for (ProjectTreeNode node : baseContent.gameData.v.getNonEmptyIterable()) { - if (node instanceof GameDataCategory) { - for (GameDataElement e : ((GameDataCategory) node)) { - e.link(); - } - } - } - for (ProjectTreeNode node : baseContent.gameMaps.tmxMaps) { - ((TMXMap)node).link(); - } - for (ProjectTreeNode node : alteredContent.gameData.v.getNonEmptyIterable()) { - if (node instanceof GameDataCategory) { - for (GameDataElement e : ((GameDataCategory) node)) { - e.link(); - } - } - } - for (ProjectTreeNode node : alteredContent.gameMaps.tmxMaps) { - ((TMXMap)node).link(); - } - for (ProjectTreeNode node : createdContent.gameData.v.getNonEmptyIterable()) { - if (node instanceof GameDataCategory) { - for (GameDataElement e : ((GameDataCategory) node)) { - e.link(); - } - } - } - for (ProjectTreeNode node : createdContent.gameMaps.tmxMaps) { - ((TMXMap)node).link(); - } - - for (WorldmapSegment node : createdContent.worldmap) { - node.link(); - } - for (WorldmapSegment node : alteredContent.worldmap) { - node.link(); - } - for (WorldmapSegment node : baseContent.worldmap) { - node.link(); - } - } - - public void save() { - SettingsSave.saveInstance(this, new File(baseFolder, Project.SETTINGS_FILE), "Project "+this.name); - } - - - public JSONElement getGameDataElement(Class gdeClass, String id) { - if (gdeClass == ActorCondition.class) { - return getActorCondition(id); - } - if (gdeClass == Dialogue.class) { - return getDialogue(id); - } - if (gdeClass == Droplist.class) { - return getDroplist(id); - } - if (gdeClass == ItemCategory.class) { - return getItemCategory(id); - } - if (gdeClass == Item.class) { - return getItem(id); - } - if (gdeClass == NPC.class) { - return getNPC(id); - } - if (gdeClass == Quest.class) { - return getQuest(id); - } - return null; - } - - public int getNodeCount(Class gdeClass) { - if (gdeClass == ActorCondition.class) { - return getActorConditionCount(); - } - if (gdeClass == Dialogue.class) { - return getDialogueCount(); - } - if (gdeClass == Droplist.class) { - return getDroplistCount(); - } - if (gdeClass == ItemCategory.class) { - return getItemCategoryCount(); - } - if (gdeClass == Item.class) { - return getItemCount(); - } - if (gdeClass == NPC.class) { - return getNPCCount(); - } - if (gdeClass == Quest.class) { - return getQuestCount(); - } - return 0; - } - - public int getNodeIndex(GameDataElement node) { - Class gdeClass = node.getClass(); - if (gdeClass == ActorCondition.class) { - return getActorConditionIndex((ActorCondition) node); - } - if (gdeClass == Dialogue.class) { - return getDialogueIndex((Dialogue) node); - } - if (gdeClass == Droplist.class) { - return getDroplistIndex((Droplist) node); - } - if (gdeClass == ItemCategory.class) { - return getItemCategoryIndex((ItemCategory) node); - } - if (gdeClass == Item.class) { - return getItemIndex((Item) node); - } - if (gdeClass == NPC.class) { - return getNPCIndex((NPC) node); - } - if (gdeClass == Quest.class) { - return getQuestIndex((Quest) node); - } - return 0; - } - - public ActorCondition getActorCondition(String id) { - ActorCondition gde = createdContent.gameData.getActorCondition(id); - if (gde == null) gde = alteredContent.gameData.getActorCondition(id); - if (gde == null) gde = baseContent.gameData.getActorCondition(id); - return gde; - } - - public int getActorConditionCount() { - return createdContent.gameData.actorConditions.size() + baseContent.gameData.actorConditions.size(); - } - - public ActorCondition getActorCondition(int index) { - if (index < createdContent.gameData.actorConditions.size()) { - return createdContent.gameData.actorConditions.get(index); - } else if (index < getActorConditionCount()){ - return getActorCondition(baseContent.gameData.actorConditions.get(index - createdContent.gameData.actorConditions.size()).id); - } - return null; - } - - public int getActorConditionIndex(ActorCondition ac) { - if (ac.getDataType() == GameSource.Type.created) { - return createdContent.gameData.actorConditions.getIndex(ac); - } else { - return createdContent.gameData.actorConditions.size() + baseContent.gameData.actorConditions.indexOf(baseContent.gameData.getActorCondition(ac.id)); - } - } - - - public Dialogue getDialogue(String id) { - Dialogue gde = createdContent.gameData.getDialogue(id); - if (gde == null) gde = alteredContent.gameData.getDialogue(id); - if (gde == null) gde = baseContent.gameData.getDialogue(id); - return gde; - } - - public int getDialogueCount() { - return createdContent.gameData.dialogues.size() + baseContent.gameData.dialogues.size(); - } - - public Dialogue getDialogue(int index) { - if (index < createdContent.gameData.dialogues.size()) { - return createdContent.gameData.dialogues.get(index); - } else if (index < getDialogueCount()){ - return getDialogue(baseContent.gameData.dialogues.get(index - createdContent.gameData.dialogues.size()).id); - } - return null; - } - - public int getDialogueIndex(Dialogue dialogue) { - if (dialogue.getDataType() == GameSource.Type.created) { - return createdContent.gameData.dialogues.getIndex(dialogue); - } else { - return createdContent.gameData.dialogues.size() + baseContent.gameData.dialogues.indexOf(baseContent.gameData.getDialogue(dialogue.id)); - } - } - - - public Droplist getDroplist(String id) { - Droplist gde = createdContent.gameData.getDroplist(id); - if (gde == null) gde = alteredContent.gameData.getDroplist(id); - if (gde == null) gde = baseContent.gameData.getDroplist(id); - return gde; - } - - public int getDroplistCount() { - return createdContent.gameData.droplists.size() + baseContent.gameData.droplists.size(); - } - - public Droplist getDroplist(int index) { - if (index < createdContent.gameData.droplists.size()) { - return createdContent.gameData.droplists.get(index); - } else if (index < getDroplistCount()){ - return getDroplist(baseContent.gameData.droplists.get(index - createdContent.gameData.droplists.size()).id); - } - return null; - } - - public int getDroplistIndex(Droplist droplist) { - if (droplist.getDataType() == GameSource.Type.created) { - return createdContent.gameData.droplists.getIndex(droplist); - } else { - return createdContent.gameData.droplists.size() + baseContent.gameData.droplists.indexOf(baseContent.gameData.getDroplist(droplist.id)); - } - } - - - public Item getItem(String id) { - Item gde = createdContent.gameData.getItem(id); - if (gde == null) gde = alteredContent.gameData.getItem(id); - if (gde == null) gde = baseContent.gameData.getItem(id); - return gde; - } - - public int getItemCount() { - return createdContent.gameData.items.size() + baseContent.gameData.items.size(); - } - - public Item getItem(int index) { - if (index < createdContent.gameData.items.size()) { - return createdContent.gameData.items.get(index); - } else if (index < getItemCount()){ - return getItem(baseContent.gameData.items.get(index - createdContent.gameData.items.size()).id); - } - return null; - } - - public int getItemCountIncludingAltered() { - return createdContent.gameData.items.size() + alteredContent.gameData.items.size() + baseContent.gameData.items.size(); - } - - public Item getItemIncludingAltered(int index) { - if (index < createdContent.gameData.items.size()) { - return createdContent.gameData.items.get(index); - } else if (index < createdContent.gameData.items.size() + alteredContent.gameData.items.size()){ - return alteredContent.gameData.items.get(index - createdContent.gameData.items.size()); - } else if (index < getItemCountIncludingAltered()) { - return baseContent.gameData.items.get(index - (createdContent.gameData.items.size() + alteredContent.gameData.items.size())); - } - return null; - } - - public int getItemIndex(Item item) { - if (item.getDataType() == GameSource.Type.created) { - return createdContent.gameData.items.getIndex(item); - } else { - return createdContent.gameData.items.size() + baseContent.gameData.items.indexOf(baseContent.gameData.getItem(item.id)); - } - } - - - public ItemCategory getItemCategory(String id) { - ItemCategory gde = createdContent.gameData.getItemCategory(id); - if (gde == null) gde = alteredContent.gameData.getItemCategory(id); - if (gde == null) gde = baseContent.gameData.getItemCategory(id); - return gde; - } - - public int getItemCategoryCount() { - return createdContent.gameData.itemCategories.size() + baseContent.gameData.itemCategories.size(); - } - - public ItemCategory getItemCategory(int index) { - if (index < createdContent.gameData.itemCategories.size()) { - return createdContent.gameData.itemCategories.get(index); - } else if (index < getItemCategoryCount()){ - return getItemCategory(baseContent.gameData.itemCategories.get(index - createdContent.gameData.itemCategories.size()).id); - } - return null; - } - - public int getItemCategoryIndex(ItemCategory iCat) { - if (iCat.getDataType() == GameSource.Type.created) { - return createdContent.gameData.itemCategories.getIndex(iCat); - } else { - return createdContent.gameData.itemCategories.size() + baseContent.gameData.itemCategories.indexOf(baseContent.gameData.getItemCategory(iCat.id)); - } - } - - - public NPC getNPC(String id) { - NPC gde = createdContent.gameData.getNPC(id); - if (gde == null) gde = alteredContent.gameData.getNPC(id); - if (gde == null) gde = baseContent.gameData.getNPC(id); - return gde; - } - - public NPC getNPCIgnoreCase(String id) { - NPC gde = createdContent.gameData.getNPCIgnoreCase(id); - if (gde == null) gde = alteredContent.gameData.getNPCIgnoreCase(id); - if (gde == null) gde = baseContent.gameData.getNPCIgnoreCase(id); - return gde; - } - - public int getNPCCount() { - return createdContent.gameData.npcs.size() + baseContent.gameData.npcs.size(); - } - - public NPC getNPC(int index) { - if (index < createdContent.gameData.npcs.size()) { - return createdContent.gameData.npcs.get(index); - } else if (index < getNPCCount()){ - return getNPC(baseContent.gameData.npcs.get(index - createdContent.gameData.npcs.size()).id); - } - return null; - } - - public int getNPCCountIncludingAltered() { - return createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size() + baseContent.gameData.npcs.size(); - } - - public NPC getNPCIncludingAltered(int index) { - if (index < createdContent.gameData.npcs.size()) { - return createdContent.gameData.npcs.get(index); - } else if (index < createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size()){ - return alteredContent.gameData.npcs.get(index - createdContent.gameData.npcs.size()); - } else if (index < getNPCCountIncludingAltered()) { - return baseContent.gameData.npcs.get(index - (createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size())); - } - return null; - } - - public int getNPCIndex(NPC npc) { - if (npc.getDataType() == GameSource.Type.created) { - return createdContent.gameData.npcs.getIndex(npc); - } else { - return createdContent.gameData.npcs.size() + baseContent.gameData.npcs.indexOf(baseContent.gameData.getNPC(npc.id)); - } - } - - - public Quest getQuest(String id) { - Quest gde = createdContent.gameData.getQuest(id); - if (gde == null) gde = alteredContent.gameData.getQuest(id); - if (gde == null) gde = baseContent.gameData.getQuest(id); - return gde; - } - - public int getQuestCount() { - return createdContent.gameData.quests.size() + baseContent.gameData.quests.size(); - } - - public Quest getQuest(int index) { - if (index < createdContent.gameData.quests.size()) { - return createdContent.gameData.quests.get(index); - } else if (index < getQuestCount()){ - return getQuest(baseContent.gameData.quests.get(index - createdContent.gameData.quests.size()).id); - } - return null; - } - - public int getQuestIndex(Quest quest) { - if (quest.getDataType() == GameSource.Type.created) { - return createdContent.gameData.quests.getIndex(quest); - } else { - return createdContent.gameData.quests.size() + baseContent.gameData.quests.indexOf(baseContent.gameData.getQuest(quest.id)); - } - } - - public WorldmapSegment getWorldmapSegment(String id) { - WorldmapSegment gde = createdContent.getWorldmapSegment(id); - if (gde == null) gde = alteredContent.getWorldmapSegment(id); - if (gde == null) gde = baseContent.getWorldmapSegment(id); - return gde; - } - - public int getWorldmapSegmentCount() { - return createdContent.worldmap.size() + baseContent.worldmap.size(); - } - - public WorldmapSegment getWorldmapSegment(int index) { - if (index < createdContent.worldmap.size()) { - return createdContent.worldmap.get(index); - } else if (index < getWorldmapSegmentCount()){ - return getWorldmapSegment(baseContent.worldmap.get(index - createdContent.worldmap.size()).id); - } - return null; - } - - public int getWorldmapSegmentIndex(WorldmapSegment segment) { - if (segment.getDataType() == GameSource.Type.created) { - return createdContent.worldmap.getIndex(segment); - } else { - return createdContent.worldmap.size() + baseContent.worldmap.indexOf(baseContent.getWorldmapSegment(segment.id)); - } - } - - public Image getIcon(String iconId) { - return baseContent.getIcon(iconId); - } - - public Image getImage(String iconId) { - return baseContent.getImage(iconId); - } - - public Spritesheet getSpritesheet(String id) { - Spritesheet sheet = createdContent.gameSprites.getSpritesheet(id); - if (sheet == null) sheet = alteredContent.gameSprites.getSpritesheet(id); - if (sheet == null) sheet = baseContent.gameSprites.getSpritesheet(id); - return sheet; - } - - public int getSpritesheetCount() { - return createdContent.gameSprites.spritesheets.size() + baseContent.gameSprites.spritesheets.size(); - } - - public Spritesheet getSpritesheet(int index) { - if (index < createdContent.gameSprites.spritesheets.size()) { - return createdContent.gameSprites.spritesheets.get(index); - } else if (index < getSpritesheetCount()){ - return getSpritesheet(baseContent.gameSprites.spritesheets.get(index - createdContent.gameSprites.spritesheets.size()).id); - } - return null; - } - - public int getSpritesheetIndex(Spritesheet spritesheet) { - if (spritesheet.getDataType() == GameSource.Type.created) { - return createdContent.gameSprites.spritesheets.indexOf(spritesheet); - } else { - return createdContent.gameSprites.spritesheets.size() + baseContent.gameSprites.spritesheets.indexOf(baseContent.gameSprites.getSpritesheet(spritesheet.id)); - } - } - - public TMXMap getMap(String id) { - TMXMap map = createdContent.gameMaps.getMap(id); - if (map == null) map = alteredContent.gameMaps.getMap(id); - if (map == null) map = baseContent.gameMaps.getMap(id); - return map; - } - - public int getMapCount() { - return createdContent.gameMaps.getChildCount() + baseContent.gameMaps.getChildCount(); - } - - public TMXMap getMap(int index) { - if (index < createdContent.gameMaps.getChildCount()) { - return createdContent.gameMaps.get(index); - } else if (index < getMapCount()){ - return getMap(baseContent.gameMaps.get(index - createdContent.gameMaps.getChildCount()).id); - } - return null; - } - - public int getMapIndex(TMXMap map) { - if (map.getDataType() == GameSource.Type.created) { - return createdContent.gameMaps.tmxMaps.indexOf(map); - } else { - return createdContent.gameMaps.tmxMaps.size() + baseContent.gameMaps.tmxMaps.indexOf(baseContent.gameMaps.getMap(map.id)); - } - } - - public int getWriterSketchCount() { - return createdContent.writerModeDataSet.getChildCount(); - } - - public WriterModeData getWriterSketch(String id) { - return createdContent.writerModeDataSet.getWriterSketch(id); - } - - public WriterModeData getWriterSketch(int index) { - if (index < createdContent.writerModeDataSet.getChildCount()) { - return createdContent.writerModeDataSet.get(index); - } - return null; - } - - @Override - public Project getProject() { - return this; - } - - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - //TODO Create a cool Project icon. - return DefaultIcons.getStdClosedIcon(); - } - @Override - public Image getLeafIcon() { - //TODO Create a cool Project icon. - return DefaultIcons.getStdClosedIcon(); - } - @Override - public Image getOpenIcon() { - //TODO Create a cool Project icon. - return DefaultIcons.getStdOpenIcon(); - } - - public void makeWritable(JSONElement node) { - GameSource.Type type = node.getDataType(); - if (type == null) { - Notification.addError("Unable to make "+node.getDesc()+" writable. No owning GameDataSet found."); - } else { - if (type == GameSource.Type.source) { - JSONElement clone = (JSONElement) node.clone(); - if (node instanceof Quest) { - for (QuestStage oldStage : ((Quest) node).stages) { - QuestStage newStage = ((Quest) clone).getStage(oldStage.progress); - for (GameDataElement backlink : oldStage.getBacklinks()) { - backlink.elementChanged(oldStage, newStage); - } - oldStage.getBacklinks().clear(); - } - } - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, clone); - } - node.getBacklinks().clear(); - clone.writable = true; - clone.state = GameDataElement.State.created; - alteredContent.gameData.addElement(clone); - } else { - Notification.addError("Unable to make "+node.getDesc()+" writable. It does not originate from game source material."); - } - } - } - + v.add(baseContent); + v.add(saves); + v.add(bookmarks); - public void makeWritable(TMXMap node) { - GameSource.Type type = node.getDataType(); - if (type == null) { - Notification.addError("Unable to make "+node.getDesc()+" writable. No owning GameDataSet found."); - } else { - if (type == GameSource.Type.source) { - TMXMap clone = node.clone(); - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, clone); - } - node.getBacklinks().clear(); - clone.writable = true; - clone.state = GameDataElement.State.created; - alteredContent.gameMaps.addMap(clone); - } else { - Notification.addError("Unable to make "+node.getDesc()+" writable. It does not originate from game source material."); - } - } - } + linkAll(); - public void makeWritable(WorldmapSegment node) { - GameSource.Type type = node.getDataType(); - if (type == null) { - Notification.addError("Unable to make "+node.getDesc()+" writable. No owning GameDataSet found."); - } else { - if (type == GameSource.Type.source) { - WorldmapSegment clone = node.clone(); - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, clone); - } - clone.state = GameDataElement.State.init; - clone.parse(); - node.getBacklinks().clear(); - clone.writable = true; - clone.state = GameDataElement.State.created; - alteredContent.worldmap.addSegment(clone); - } else { - Notification.addError("Unable to make "+node.getDesc()+" writable. It does not originate from game source material."); - } - } - } - - /** - * - * @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered. - */ - public void createElement(JSONElement node) { - node.writable = true; - if (getGameDataElement(node.getClass(), node.id) != null) { - GameDataElement existingNode = getGameDataElement(node.getClass(), node.id); - for (GameDataElement backlink : existingNode.getBacklinks()) { - backlink.elementChanged(existingNode, node); - } - existingNode.getBacklinks().clear(); - node.writable = true; - alteredContent.gameData.addElement(node); - node.link(); - node.state = GameDataElement.State.created; - } else { - createdContent.gameData.addElement(node); - node.link(); - node.state = GameDataElement.State.created; - } - fireElementAdded(node, getNodeIndex(node)); - } - - /** - * - * @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered. - */ - public void createElements(List nodes) { - for (JSONElement node : nodes) { - //Already added. - if (node.getProject() != null) continue; - node.writable = true; - if (getGameDataElement(node.getClass(), node.id) != null) { - GameDataElement existingNode = getGameDataElement(node.getClass(), node.id); - for (GameDataElement backlink : existingNode.getBacklinks()) { - backlink.elementChanged(existingNode, node); - } - existingNode.getBacklinks().clear(); - node.writable = true; - alteredContent.gameData.addElement(node); - } else { - createdContent.gameData.addElement(node); - } - } - for (JSONElement node : nodes) { - node.link(); - node.state = GameDataElement.State.created; - fireElementAdded(node, getNodeIndex(node)); - } - } - - /** - * - * @param node. Before calling this method, make sure that no other map with the same id exist in either created or altered. - */ - public void createElement(TMXMap node) { - node.writable = true; - if (getMap(node.id) != null) { - GameDataElement existingNode = getMap(node.id); - for (GameDataElement backlink : existingNode.getBacklinks()) { - backlink.elementChanged(existingNode, node); - } - existingNode.getBacklinks().clear(); - node.writable = true; - node.tmxFile = new File(alteredContent.baseFolder, node.tmxFile.getName()); - node.parent = alteredContent.gameMaps; - alteredContent.gameMaps.addMap(node); - node.link(); - node.state = GameDataElement.State.created; - } else { - node.tmxFile = new File(createdContent.baseFolder, node.tmxFile.getName()); - node.parent = createdContent.gameMaps; - createdContent.gameMaps.addMap(node); - node.link(); - node.state = GameDataElement.State.created; - } - fireElementAdded(node, getNodeIndex(node)); - } - + } - public void moveToCreated(JSONElement target) { - target.childrenRemoved(new ArrayList()); - ((GameDataCategory)target.getParent()).remove(target); - target.state = GameDataElement.State.created; - createdContent.gameData.addElement(target); - } - - public void moveToAltered(JSONElement target) { - target.childrenRemoved(new ArrayList()); - ((GameDataCategory)target.getParent()).remove(target); - target.state = GameDataElement.State.created; - ((JSONElement) target).jsonFile = new File(baseContent.gameData.getGameDataElement(((JSONElement)target).getClass(), target.id).jsonFile.getAbsolutePath()); - alteredContent.gameData.addElement((JSONElement) target); - } - - public void createWorldmapSegment(WorldmapSegment node) { - node.writable = true; - if (getWorldmapSegment(node.id) != null) { - WorldmapSegment existingNode = getWorldmapSegment(node.id); - for (GameDataElement backlink : existingNode.getBacklinks()) { - backlink.elementChanged(existingNode, node); - } - existingNode.getBacklinks().clear(); - node.writable = true; - node.state = GameDataElement.State.created; - alteredContent.worldmap.addSegment(node); - node.link(); - } else { - createdContent.worldmap.addSegment(node); - node.state = GameDataElement.State.created; - node.link(); - } - fireElementAdded(node, getNodeIndex(node)); - } + public void linkAll() { + for (ProjectTreeNode node : baseContent.gameData.v.getNonEmptyIterable()) { + if (node instanceof GameDataCategory) { + for (GameDataElement e : ((GameDataCategory) node)) { + e.link(); + } + } + } + for (ProjectTreeNode node : baseContent.gameMaps.tmxMaps) { + ((TMXMap) node).link(); + } + for (ProjectTreeNode node : alteredContent.gameData.v.getNonEmptyIterable()) { + if (node instanceof GameDataCategory) { + for (GameDataElement e : ((GameDataCategory) node)) { + e.link(); + } + } + } + for (ProjectTreeNode node : alteredContent.gameMaps.tmxMaps) { + ((TMXMap) node).link(); + } + for (ProjectTreeNode node : createdContent.gameData.v.getNonEmptyIterable()) { + if (node instanceof GameDataCategory) { + for (GameDataElement e : ((GameDataCategory) node)) { + e.link(); + } + } + } + for (ProjectTreeNode node : createdContent.gameMaps.tmxMaps) { + ((TMXMap) node).link(); + } + + for (WorldmapSegment node : createdContent.worldmap) { + node.link(); + } + for (WorldmapSegment node : alteredContent.worldmap) { + node.link(); + } + for (WorldmapSegment node : baseContent.worldmap) { + node.link(); + } + } + + public void save() { + SettingsSave.saveInstance(this, new File(baseFolder, Project.SETTINGS_FILE), "Project " + this.name); + } + public JSONElement getGameDataElement(Class gdeClass, String id) { + if (gdeClass == ActorCondition.class) { + return getActorCondition(id); + } + if (gdeClass == Dialogue.class) { + return getDialogue(id); + } + if (gdeClass == Droplist.class) { + return getDroplist(id); + } + if (gdeClass == ItemCategory.class) { + return getItemCategory(id); + } + if (gdeClass == Item.class) { + return getItem(id); + } + if (gdeClass == NPC.class) { + return getNPC(id); + } + if (gdeClass == Quest.class) { + return getQuest(id); + } + return null; + } - public void createWriterSketch(WriterModeData node) { - node.writable = true; - createdContent.writerModeDataSet.add(node); - node.link(); - fireElementAdded(node, getNodeIndex(node)); - } - - public void bookmark(GameDataElement gde) { - bookmarks.addBookmark(gde); - } - - - @Override - public GameDataSet getDataSet() { - return null; - } + public int getNodeCount(Class gdeClass) { + if (gdeClass == ActorCondition.class) { + return getActorConditionCount(); + } + if (gdeClass == Dialogue.class) { + return getDialogueCount(); + } + if (gdeClass == Droplist.class) { + return getDroplistCount(); + } + if (gdeClass == ItemCategory.class) { + return getItemCategoryCount(); + } + if (gdeClass == Item.class) { + return getItemCount(); + } + if (gdeClass == NPC.class) { + return getNPCCount(); + } + if (gdeClass == Quest.class) { + return getQuestCount(); + } + return 0; + } - @Override - public Type getDataType() { - return null; - } - - - public String getSpritesheetsProperty(String string) { - return knownSpritesheetsProperties.getProperty(string); - } + public int getNodeIndex(GameDataElement node) { + Class gdeClass = node.getClass(); + if (gdeClass == ActorCondition.class) { + return getActorConditionIndex((ActorCondition) node); + } + if (gdeClass == Dialogue.class) { + return getDialogueIndex((Dialogue) node); + } + if (gdeClass == Droplist.class) { + return getDroplistIndex((Droplist) node); + } + if (gdeClass == ItemCategory.class) { + return getItemCategoryIndex((ItemCategory) node); + } + if (gdeClass == Item.class) { + return getItemIndex((Item) node); + } + if (gdeClass == NPC.class) { + return getNPCIndex((NPC) node); + } + if (gdeClass == Quest.class) { + return getQuestIndex((Quest) node); + } + return 0; + } - public void setSpritesheetsProperty(String key, String value) { - knownSpritesheetsProperties.setProperty(key, value); - } + public ActorCondition getActorCondition(String id) { + ActorCondition gde = createdContent.gameData.getActorCondition(id); + if (gde == null) gde = alteredContent.gameData.getActorCondition(id); + if (gde == null) gde = baseContent.gameData.getActorCondition(id); + return gde; + } + + public int getActorConditionCount() { + return createdContent.gameData.actorConditions.size() + baseContent.gameData.actorConditions.size(); + } + + public ActorCondition getActorCondition(int index) { + if (index < createdContent.gameData.actorConditions.size()) { + return createdContent.gameData.actorConditions.get(index); + } else if (index < getActorConditionCount()) { + return getActorCondition(baseContent.gameData.actorConditions.get(index - createdContent.gameData.actorConditions.size()).id); + } + return null; + } + + public int getActorConditionIndex(ActorCondition ac) { + if (ac.getDataType() == GameSource.Type.created) { + return createdContent.gameData.actorConditions.getIndex(ac); + } else { + return createdContent.gameData.actorConditions.size() + baseContent.gameData.actorConditions.indexOf(baseContent.gameData.getActorCondition(ac.id)); + } + } - @Override - public boolean isEmpty() { - return v.isEmpty(); - } + public Dialogue getDialogue(String id) { + Dialogue gde = createdContent.gameData.getDialogue(id); + if (gde == null) gde = alteredContent.gameData.getDialogue(id); + if (gde == null) gde = baseContent.gameData.getDialogue(id); + return gde; + } + + public int getDialogueCount() { + return createdContent.gameData.dialogues.size() + baseContent.gameData.dialogues.size(); + } + + public Dialogue getDialogue(int index) { + if (index < createdContent.gameData.dialogues.size()) { + return createdContent.gameData.dialogues.get(index); + } else if (index < getDialogueCount()) { + return getDialogue(baseContent.gameData.dialogues.get(index - createdContent.gameData.dialogues.size()).id); + } + return null; + } + + public int getDialogueIndex(Dialogue dialogue) { + if (dialogue.getDataType() == GameSource.Type.created) { + return createdContent.gameData.dialogues.getIndex(dialogue); + } else { + return createdContent.gameData.dialogues.size() + baseContent.gameData.dialogues.indexOf(baseContent.gameData.getDialogue(dialogue.id)); + } + } - public void addSave(File selectedFile) { - saves.addSave(selectedFile); - } + public Droplist getDroplist(String id) { + Droplist gde = createdContent.gameData.getDroplist(id); + if (gde == null) gde = alteredContent.gameData.getDroplist(id); + if (gde == null) gde = baseContent.gameData.getDroplist(id); + return gde; + } + + public int getDroplistCount() { + return createdContent.gameData.droplists.size() + baseContent.gameData.droplists.size(); + } + + public Droplist getDroplist(int index) { + if (index < createdContent.gameData.droplists.size()) { + return createdContent.gameData.droplists.get(index); + } else if (index < getDroplistCount()) { + return getDroplist(baseContent.gameData.droplists.get(index - createdContent.gameData.droplists.size()).id); + } + return null; + } + + public int getDroplistIndex(Droplist droplist) { + if (droplist.getDataType() == GameSource.Type.created) { + return createdContent.gameData.droplists.getIndex(droplist); + } else { + return createdContent.gameData.droplists.size() + baseContent.gameData.droplists.indexOf(baseContent.gameData.getDroplist(droplist.id)); + } + } - public List getSpawnGroup(String spawngroup_id) { - List result = new ArrayList(); - int i = getNPCCount(); - boolean alreadyAdded = false; - int index = -1; - while (--i >= 0) { - NPC npc = getNPC(i); - if (spawngroup_id.equalsIgnoreCase(npc.spawngroup_id)) { - for (NPC present : result) { - if (present.id.equals(npc.id)) { - alreadyAdded = true; - index = result.indexOf(present); - break; - } - } - if (alreadyAdded) { - result.set(index, npc); - } else { - result.add(npc); - } - } - alreadyAdded = false; - } - if (result.isEmpty()) { - //Fallback case. A single NPC does not declare a spawn group, but is referred by its ID in maps' spawn areas. - NPC npc = getNPCIgnoreCase(spawngroup_id); - if (npc != null) result.add(npc); - } - return result; - } - - transient Map, List> projectElementListeners = new HashMap, List>(); - - public void addElementListener(Class interestingType, ProjectElementListener listener) { - if (projectElementListeners.get(interestingType) == null) { - projectElementListeners.put(interestingType, new ArrayList()); - } - projectElementListeners.get(interestingType).add(listener); - } - - public void removeElementListener(Class interestingType, ProjectElementListener listener) { - if (projectElementListeners.get(interestingType) != null) projectElementListeners.get(interestingType).remove(listener); - } - - public void fireElementAdded(GameDataElement element, int index) { - if (projectElementListeners.get(element.getClass()) != null) { - for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { - l.elementAdded(element, index); - } - } - } + public Item getItem(String id) { + Item gde = createdContent.gameData.getItem(id); + if (gde == null) gde = alteredContent.gameData.getItem(id); + if (gde == null) gde = baseContent.gameData.getItem(id); + return gde; + } - public void fireElementRemoved(GameDataElement element, int index) { - if (projectElementListeners.get(element.getClass()) != null) { - for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { - l.elementRemoved(element, index); - } - } - } - - public void exportProjectAsZipPackage(final File target) { - WorkerDialog.showTaskMessage("Exporting project "+name+"...", ATContentStudio.frame, true, new Runnable() { - @Override - public void run() { - Notification.addInfo("Exporting project \""+name+"\" as "+target.getAbsolutePath()); - - File tmpDir; - try { - tmpDir = exportProjectToTmpDir(); - FileUtils.writeToZip(tmpDir, target); - FileUtils.deleteDir(tmpDir); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + public int getItemCount() { + return createdContent.gameData.items.size() + baseContent.gameData.items.size(); + } - Notification.addSuccess("Project \""+name+"\" exported as "+target.getAbsolutePath()); - } + public Item getItem(int index) { + if (index < createdContent.gameData.items.size()) { + return createdContent.gameData.items.get(index); + } else if (index < getItemCount()) { + return getItem(baseContent.gameData.items.get(index - createdContent.gameData.items.size()).id); + } + return null; + } - - }); - } - - public void exportProjectOverGameSource(final File target) { - WorkerDialog.showTaskMessage("Exporting project "+name+"...", ATContentStudio.frame, true, new Runnable() { - @Override - public void run() { - Notification.addInfo("Exporting project \""+name+"\" into "+target.getAbsolutePath()); - - File tmpDir; - try { - tmpDir = exportProjectToTmpDir(); - FileUtils.copyOver(tmpDir, target); - FileUtils.deleteDir(tmpDir); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + public int getItemCountIncludingAltered() { + return createdContent.gameData.items.size() + alteredContent.gameData.items.size() + baseContent.gameData.items.size(); + } - Notification.addSuccess("Project \""+name+"\" exported into "+target.getAbsolutePath()); - } + public Item getItemIncludingAltered(int index) { + if (index < createdContent.gameData.items.size()) { + return createdContent.gameData.items.get(index); + } else if (index < createdContent.gameData.items.size() + alteredContent.gameData.items.size()) { + return alteredContent.gameData.items.get(index - createdContent.gameData.items.size()); + } else if (index < getItemCountIncludingAltered()) { + return baseContent.gameData.items.get(index - (createdContent.gameData.items.size() + alteredContent.gameData.items.size())); + } + return null; + } - - }); - } - - public File exportProjectToTmpDir() throws IOException { - File tmpDir = new File(baseFolder, "tmp"); - FileUtils.deleteDir(tmpDir); - tmpDir.mkdir(); - File tmpJsonDataDir = new File(tmpDir, GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); - tmpJsonDataDir.mkdirs(); + public int getItemIndex(Item item) { + if (item.getDataType() == GameSource.Type.created) { + return createdContent.gameData.items.getIndex(item); + } else { + return createdContent.gameData.items.size() + baseContent.gameData.items.indexOf(baseContent.gameData.getItem(item.id)); + } + } + + + public ItemCategory getItemCategory(String id) { + ItemCategory gde = createdContent.gameData.getItemCategory(id); + if (gde == null) gde = alteredContent.gameData.getItemCategory(id); + if (gde == null) gde = baseContent.gameData.getItemCategory(id); + return gde; + } + + public int getItemCategoryCount() { + return createdContent.gameData.itemCategories.size() + baseContent.gameData.itemCategories.size(); + } + + public ItemCategory getItemCategory(int index) { + if (index < createdContent.gameData.itemCategories.size()) { + return createdContent.gameData.itemCategories.get(index); + } else if (index < getItemCategoryCount()) { + return getItemCategory(baseContent.gameData.itemCategories.get(index - createdContent.gameData.itemCategories.size()).id); + } + return null; + } + + public int getItemCategoryIndex(ItemCategory iCat) { + if (iCat.getDataType() == GameSource.Type.created) { + return createdContent.gameData.itemCategories.getIndex(iCat); + } else { + return createdContent.gameData.itemCategories.size() + baseContent.gameData.itemCategories.indexOf(baseContent.gameData.getItemCategory(iCat.id)); + } + } + + + public NPC getNPC(String id) { + NPC gde = createdContent.gameData.getNPC(id); + if (gde == null) gde = alteredContent.gameData.getNPC(id); + if (gde == null) gde = baseContent.gameData.getNPC(id); + return gde; + } + + public NPC getNPCIgnoreCase(String id) { + NPC gde = createdContent.gameData.getNPCIgnoreCase(id); + if (gde == null) gde = alteredContent.gameData.getNPCIgnoreCase(id); + if (gde == null) gde = baseContent.gameData.getNPCIgnoreCase(id); + return gde; + } + + public int getNPCCount() { + return createdContent.gameData.npcs.size() + baseContent.gameData.npcs.size(); + } + + public NPC getNPC(int index) { + if (index < createdContent.gameData.npcs.size()) { + return createdContent.gameData.npcs.get(index); + } else if (index < getNPCCount()) { + return getNPC(baseContent.gameData.npcs.get(index - createdContent.gameData.npcs.size()).id); + } + return null; + } + + public int getNPCCountIncludingAltered() { + return createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size() + baseContent.gameData.npcs.size(); + } + + public NPC getNPCIncludingAltered(int index) { + if (index < createdContent.gameData.npcs.size()) { + return createdContent.gameData.npcs.get(index); + } else if (index < createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size()) { + return alteredContent.gameData.npcs.get(index - createdContent.gameData.npcs.size()); + } else if (index < getNPCCountIncludingAltered()) { + return baseContent.gameData.npcs.get(index - (createdContent.gameData.npcs.size() + alteredContent.gameData.npcs.size())); + } + return null; + } + + public int getNPCIndex(NPC npc) { + if (npc.getDataType() == GameSource.Type.created) { + return createdContent.gameData.npcs.getIndex(npc); + } else { + return createdContent.gameData.npcs.size() + baseContent.gameData.npcs.indexOf(baseContent.gameData.getNPC(npc.id)); + } + } + + + public Quest getQuest(String id) { + Quest gde = createdContent.gameData.getQuest(id); + if (gde == null) gde = alteredContent.gameData.getQuest(id); + if (gde == null) gde = baseContent.gameData.getQuest(id); + return gde; + } + + public int getQuestCount() { + return createdContent.gameData.quests.size() + baseContent.gameData.quests.size(); + } + + public Quest getQuest(int index) { + if (index < createdContent.gameData.quests.size()) { + return createdContent.gameData.quests.get(index); + } else if (index < getQuestCount()) { + return getQuest(baseContent.gameData.quests.get(index - createdContent.gameData.quests.size()).id); + } + return null; + } + + public int getQuestIndex(Quest quest) { + if (quest.getDataType() == GameSource.Type.created) { + return createdContent.gameData.quests.getIndex(quest); + } else { + return createdContent.gameData.quests.size() + baseContent.gameData.quests.indexOf(baseContent.gameData.getQuest(quest.id)); + } + } + + public WorldmapSegment getWorldmapSegment(String id) { + WorldmapSegment gde = createdContent.getWorldmapSegment(id); + if (gde == null) gde = alteredContent.getWorldmapSegment(id); + if (gde == null) gde = baseContent.getWorldmapSegment(id); + return gde; + } + + public int getWorldmapSegmentCount() { + return createdContent.worldmap.size() + baseContent.worldmap.size(); + } + + public WorldmapSegment getWorldmapSegment(int index) { + if (index < createdContent.worldmap.size()) { + return createdContent.worldmap.get(index); + } else if (index < getWorldmapSegmentCount()) { + return getWorldmapSegment(baseContent.worldmap.get(index - createdContent.worldmap.size()).id); + } + return null; + } + + public int getWorldmapSegmentIndex(WorldmapSegment segment) { + if (segment.getDataType() == GameSource.Type.created) { + return createdContent.worldmap.getIndex(segment); + } else { + return createdContent.worldmap.size() + baseContent.worldmap.indexOf(baseContent.getWorldmapSegment(segment.id)); + } + } + + public Image getIcon(String iconId) { + return baseContent.getIcon(iconId); + } + + public Image getImage(String iconId) { + return baseContent.getImage(iconId); + } + + public Spritesheet getSpritesheet(String id) { + Spritesheet sheet = createdContent.gameSprites.getSpritesheet(id); + if (sheet == null) sheet = alteredContent.gameSprites.getSpritesheet(id); + if (sheet == null) sheet = baseContent.gameSprites.getSpritesheet(id); + return sheet; + } + + public int getSpritesheetCount() { + return createdContent.gameSprites.spritesheets.size() + baseContent.gameSprites.spritesheets.size(); + } + + public Spritesheet getSpritesheet(int index) { + if (index < createdContent.gameSprites.spritesheets.size()) { + return createdContent.gameSprites.spritesheets.get(index); + } else if (index < getSpritesheetCount()) { + return getSpritesheet(baseContent.gameSprites.spritesheets.get(index - createdContent.gameSprites.spritesheets.size()).id); + } + return null; + } + + public int getSpritesheetIndex(Spritesheet spritesheet) { + if (spritesheet.getDataType() == GameSource.Type.created) { + return createdContent.gameSprites.spritesheets.indexOf(spritesheet); + } else { + return createdContent.gameSprites.spritesheets.size() + baseContent.gameSprites.spritesheets.indexOf(baseContent.gameSprites.getSpritesheet(spritesheet.id)); + } + } + + public TMXMap getMap(String id) { + TMXMap map = createdContent.gameMaps.getMap(id); + if (map == null) map = alteredContent.gameMaps.getMap(id); + if (map == null) map = baseContent.gameMaps.getMap(id); + return map; + } + + public int getMapCount() { + return createdContent.gameMaps.getChildCount() + baseContent.gameMaps.getChildCount(); + } + + public TMXMap getMap(int index) { + if (index < createdContent.gameMaps.getChildCount()) { + return createdContent.gameMaps.get(index); + } else if (index < getMapCount()) { + return getMap(baseContent.gameMaps.get(index - createdContent.gameMaps.getChildCount()).id); + } + return null; + } + + public int getMapIndex(TMXMap map) { + if (map.getDataType() == GameSource.Type.created) { + return createdContent.gameMaps.tmxMaps.indexOf(map); + } else { + return createdContent.gameMaps.tmxMaps.size() + baseContent.gameMaps.tmxMaps.indexOf(baseContent.gameMaps.getMap(map.id)); + } + } + + public int getWriterSketchCount() { + return createdContent.writerModeDataSet.getChildCount(); + } + + public WriterModeData getWriterSketch(String id) { + return createdContent.writerModeDataSet.getWriterSketch(id); + } + + public WriterModeData getWriterSketch(int index) { + if (index < createdContent.writerModeDataSet.getChildCount()) { + return createdContent.writerModeDataSet.get(index); + } + return null; + } + + @Override + public Project getProject() { + return this; + } + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + //TODO Create a cool Project icon. + return DefaultIcons.getStdClosedIcon(); + } + + @Override + public Image getLeafIcon() { + //TODO Create a cool Project icon. + return DefaultIcons.getStdClosedIcon(); + } + + @Override + public Image getOpenIcon() { + //TODO Create a cool Project icon. + return DefaultIcons.getStdOpenIcon(); + } + + public void makeWritable(JSONElement node) { + GameSource.Type type = node.getDataType(); + if (type == null) { + Notification.addError("Unable to make " + node.getDesc() + " writable. No owning GameDataSet found."); + } else { + if (type == GameSource.Type.source) { + JSONElement clone = (JSONElement) node.clone(); + if (node instanceof Quest) { + for (QuestStage oldStage : ((Quest) node).stages) { + QuestStage newStage = ((Quest) clone).getStage(oldStage.progress); + for (GameDataElement backlink : oldStage.getBacklinks()) { + backlink.elementChanged(oldStage, newStage); + } + oldStage.getBacklinks().clear(); + } + } + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, clone); + } + node.getBacklinks().clear(); + clone.writable = true; + clone.state = GameDataElement.State.created; + alteredContent.gameData.addElement(clone); + } else { + Notification.addError("Unable to make " + node.getDesc() + " writable. It does not originate from game source material."); + } + } + } + + + public void makeWritable(TMXMap node) { + GameSource.Type type = node.getDataType(); + if (type == null) { + Notification.addError("Unable to make " + node.getDesc() + " writable. No owning GameDataSet found."); + } else { + if (type == GameSource.Type.source) { + TMXMap clone = node.clone(); + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, clone); + } + node.getBacklinks().clear(); + clone.writable = true; + clone.state = GameDataElement.State.created; + alteredContent.gameMaps.addMap(clone); + } else { + Notification.addError("Unable to make " + node.getDesc() + " writable. It does not originate from game source material."); + } + } + } + + public void makeWritable(WorldmapSegment node) { + GameSource.Type type = node.getDataType(); + if (type == null) { + Notification.addError("Unable to make " + node.getDesc() + " writable. No owning GameDataSet found."); + } else { + if (type == GameSource.Type.source) { + WorldmapSegment clone = node.clone(); + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, clone); + } + clone.state = GameDataElement.State.init; + clone.parse(); + node.getBacklinks().clear(); + clone.writable = true; + clone.state = GameDataElement.State.created; + alteredContent.worldmap.addSegment(clone); + } else { + Notification.addError("Unable to make " + node.getDesc() + " writable. It does not originate from game source material."); + } + } + } + + /** + * @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered. + */ + public void createElement(JSONElement node) { + node.writable = true; + if (getGameDataElement(node.getClass(), node.id) != null) { + GameDataElement existingNode = getGameDataElement(node.getClass(), node.id); + for (GameDataElement backlink : existingNode.getBacklinks()) { + backlink.elementChanged(existingNode, node); + } + existingNode.getBacklinks().clear(); + node.writable = true; + alteredContent.gameData.addElement(node); + node.link(); + node.state = GameDataElement.State.created; + } else { + createdContent.gameData.addElement(node); + node.link(); + node.state = GameDataElement.State.created; + } + fireElementAdded(node, getNodeIndex(node)); + } + + /** + * @param node. Before calling this method, make sure that no other node with the same class and id exist in either created or altered. + */ + public void createElements(List nodes) { + for (JSONElement node : nodes) { + //Already added. + if (node.getProject() != null) continue; + node.writable = true; + if (getGameDataElement(node.getClass(), node.id) != null) { + GameDataElement existingNode = getGameDataElement(node.getClass(), node.id); + for (GameDataElement backlink : existingNode.getBacklinks()) { + backlink.elementChanged(existingNode, node); + } + existingNode.getBacklinks().clear(); + node.writable = true; + alteredContent.gameData.addElement(node); + } else { + createdContent.gameData.addElement(node); + } + } + for (JSONElement node : nodes) { + node.link(); + node.state = GameDataElement.State.created; + fireElementAdded(node, getNodeIndex(node)); + } + } + + /** + * @param node. Before calling this method, make sure that no other map with the same id exist in either created or altered. + */ + public void createElement(TMXMap node) { + node.writable = true; + if (getMap(node.id) != null) { + GameDataElement existingNode = getMap(node.id); + for (GameDataElement backlink : existingNode.getBacklinks()) { + backlink.elementChanged(existingNode, node); + } + existingNode.getBacklinks().clear(); + node.writable = true; + node.tmxFile = new File(alteredContent.baseFolder, node.tmxFile.getName()); + node.parent = alteredContent.gameMaps; + alteredContent.gameMaps.addMap(node); + node.link(); + node.state = GameDataElement.State.created; + } else { + node.tmxFile = new File(createdContent.baseFolder, node.tmxFile.getName()); + node.parent = createdContent.gameMaps; + createdContent.gameMaps.addMap(node); + node.link(); + node.state = GameDataElement.State.created; + } + fireElementAdded(node, getNodeIndex(node)); + } + + + public void moveToCreated(JSONElement target) { + target.childrenRemoved(new ArrayList()); + ((GameDataCategory) target.getParent()).remove(target); + target.state = GameDataElement.State.created; + createdContent.gameData.addElement(target); + } + + public void moveToAltered(JSONElement target) { + target.childrenRemoved(new ArrayList()); + ((GameDataCategory) target.getParent()).remove(target); + target.state = GameDataElement.State.created; + ((JSONElement) target).jsonFile = new File(baseContent.gameData.getGameDataElement(((JSONElement) target).getClass(), target.id).jsonFile.getAbsolutePath()); + alteredContent.gameData.addElement((JSONElement) target); + } + + public void createWorldmapSegment(WorldmapSegment node) { + node.writable = true; + if (getWorldmapSegment(node.id) != null) { + WorldmapSegment existingNode = getWorldmapSegment(node.id); + for (GameDataElement backlink : existingNode.getBacklinks()) { + backlink.elementChanged(existingNode, node); + } + existingNode.getBacklinks().clear(); + node.writable = true; + node.state = GameDataElement.State.created; + alteredContent.worldmap.addSegment(node); + node.link(); + } else { + createdContent.worldmap.addSegment(node); + node.state = GameDataElement.State.created; + node.link(); + } + fireElementAdded(node, getNodeIndex(node)); + } + + + public void createWriterSketch(WriterModeData node) { + node.writable = true; + createdContent.writerModeDataSet.add(node); + node.link(); + fireElementAdded(node, getNodeIndex(node)); + } + + public void bookmark(GameDataElement gde) { + bookmarks.addBookmark(gde); + } + + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return null; + } + + + public String getSpritesheetsProperty(String string) { + return knownSpritesheetsProperties.getProperty(string); + } + + public void setSpritesheetsProperty(String key, String value) { + knownSpritesheetsProperties.setProperty(key, value); + } + + + @Override + public boolean isEmpty() { + return v.isEmpty(); + } + + + public void addSave(File selectedFile) { + saves.addSave(selectedFile); + } + + + public List getSpawnGroup(String spawngroup_id) { + List result = new ArrayList(); + int i = getNPCCount(); + boolean alreadyAdded = false; + int index = -1; + while (--i >= 0) { + NPC npc = getNPC(i); + if (spawngroup_id.equalsIgnoreCase(npc.spawngroup_id)) { + for (NPC present : result) { + if (present.id.equals(npc.id)) { + alreadyAdded = true; + index = result.indexOf(present); + break; + } + } + if (alreadyAdded) { + result.set(index, npc); + } else { + result.add(npc); + } + } + alreadyAdded = false; + } + if (result.isEmpty()) { + //Fallback case. A single NPC does not declare a spawn group, but is referred by its ID in maps' spawn areas. + NPC npc = getNPCIgnoreCase(spawngroup_id); + if (npc != null) result.add(npc); + } + return result; + } + + transient Map, List> projectElementListeners = new HashMap, List>(); + + public void addElementListener(Class interestingType, ProjectElementListener listener) { + if (projectElementListeners.get(interestingType) == null) { + projectElementListeners.put(interestingType, new ArrayList()); + } + projectElementListeners.get(interestingType).add(listener); + } + + public void removeElementListener(Class interestingType, ProjectElementListener listener) { + if (projectElementListeners.get(interestingType) != null) + projectElementListeners.get(interestingType).remove(listener); + } + + public void fireElementAdded(GameDataElement element, int index) { + if (projectElementListeners.get(element.getClass()) != null) { + for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { + l.elementAdded(element, index); + } + } + } + + public void fireElementRemoved(GameDataElement element, int index) { + if (projectElementListeners.get(element.getClass()) != null) { + for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { + l.elementRemoved(element, index); + } + } + } + + public void exportProjectAsZipPackage(final File target) { + WorkerDialog.showTaskMessage("Exporting project " + name + "...", ATContentStudio.frame, true, new Runnable() { + @Override + public void run() { + Notification.addInfo("Exporting project \"" + name + "\" as " + target.getAbsolutePath()); + + File tmpDir; + try { + tmpDir = exportProjectToTmpDir(); + FileUtils.writeToZip(tmpDir, target); + FileUtils.deleteDir(tmpDir); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Notification.addSuccess("Project \"" + name + "\" exported as " + target.getAbsolutePath()); + } + + + }); + } + + public void exportProjectOverGameSource(final File target) { + WorkerDialog.showTaskMessage("Exporting project " + name + "...", ATContentStudio.frame, true, new Runnable() { + @Override + public void run() { + Notification.addInfo("Exporting project \"" + name + "\" into " + target.getAbsolutePath()); + + File tmpDir; + try { + tmpDir = exportProjectToTmpDir(); + FileUtils.copyOver(tmpDir, target); + FileUtils.deleteDir(tmpDir); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Notification.addSuccess("Project \"" + name + "\" exported into " + target.getAbsolutePath()); + } + + + }); + } + + public File exportProjectToTmpDir() throws IOException { + File tmpDir = new File(baseFolder, "tmp"); + FileUtils.deleteDir(tmpDir); + tmpDir.mkdir(); + File tmpJsonDataDir = new File(tmpDir, GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); + tmpJsonDataDir.mkdirs(); // for (File createdJsonFile : createdContent.gameData.baseFolder.listFiles()) { // FileUtils.copyFile(createdJsonFile, new File(tmpJsonDataDir, createdJsonFile.getName())); // } - Map, List> writtenFilesPerDataType = new LinkedHashMap, List>(); - List writtenFiles; - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.actorConditions, alteredContent.gameData.actorConditions, baseContent.gameData.actorConditions, ActorCondition.class, tmpJsonDataDir); - writtenFilesPerDataType.put(ActorCondition.class, writtenFiles); - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.dialogues, alteredContent.gameData.dialogues, baseContent.gameData.dialogues, Dialogue.class, tmpJsonDataDir); - writtenFilesPerDataType.put(Dialogue.class, writtenFiles); - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.droplists, alteredContent.gameData.droplists, baseContent.gameData.droplists, Droplist.class, tmpJsonDataDir); - writtenFilesPerDataType.put(Droplist.class, writtenFiles); - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.itemCategories, alteredContent.gameData.itemCategories, baseContent.gameData.itemCategories, ItemCategory.class, tmpJsonDataDir); - writtenFilesPerDataType.put(ItemCategory.class, writtenFiles); - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.items, alteredContent.gameData.items, baseContent.gameData.items, Item.class, tmpJsonDataDir); - writtenFilesPerDataType.put(Item.class, writtenFiles); - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.npcs, alteredContent.gameData.npcs, baseContent.gameData.npcs, NPC.class, tmpJsonDataDir); - writtenFilesPerDataType.put(NPC.class, writtenFiles); - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.quests, alteredContent.gameData.quests, baseContent.gameData.quests, Quest.class, tmpJsonDataDir); - writtenFilesPerDataType.put(Quest.class, writtenFiles); + Map, List> writtenFilesPerDataType = new LinkedHashMap, List>(); + List writtenFiles; + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.actorConditions, alteredContent.gameData.actorConditions, baseContent.gameData.actorConditions, ActorCondition.class, tmpJsonDataDir); + writtenFilesPerDataType.put(ActorCondition.class, writtenFiles); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.dialogues, alteredContent.gameData.dialogues, baseContent.gameData.dialogues, Dialogue.class, tmpJsonDataDir); + writtenFilesPerDataType.put(Dialogue.class, writtenFiles); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.droplists, alteredContent.gameData.droplists, baseContent.gameData.droplists, Droplist.class, tmpJsonDataDir); + writtenFilesPerDataType.put(Droplist.class, writtenFiles); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.itemCategories, alteredContent.gameData.itemCategories, baseContent.gameData.itemCategories, ItemCategory.class, tmpJsonDataDir); + writtenFilesPerDataType.put(ItemCategory.class, writtenFiles); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.items, alteredContent.gameData.items, baseContent.gameData.items, Item.class, tmpJsonDataDir); + writtenFilesPerDataType.put(Item.class, writtenFiles); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.npcs, alteredContent.gameData.npcs, baseContent.gameData.npcs, NPC.class, tmpJsonDataDir); + writtenFilesPerDataType.put(NPC.class, writtenFiles); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.quests, alteredContent.gameData.quests, baseContent.gameData.quests, Quest.class, tmpJsonDataDir); + writtenFilesPerDataType.put(Quest.class, writtenFiles); - File tmpMapDir = new File(tmpDir, TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE); - tmpMapDir.mkdirs(); - writtenFiles = new LinkedList(); - for (File createdMapFile : createdContent.gameMaps.mapFolder.listFiles()) { - if (createdMapFile.getName().equalsIgnoreCase("worldmap.xml")) continue; - copyTmxConverted(createdMapFile.toPath(), Paths.get(tmpMapDir.getAbsolutePath(), createdMapFile.getName())); - writtenFiles.add(createdMapFile.getName()); - } - for (File alteredMapFile : alteredContent.gameMaps.mapFolder.listFiles()) { - if (alteredMapFile.getName().equalsIgnoreCase("worldmap.xml")) continue; - copyTmxConverted(alteredMapFile.toPath(), Paths.get(tmpMapDir.getAbsolutePath(), alteredMapFile.getName())); - writtenFiles.add(alteredMapFile.getName()); - } - writtenFilesPerDataType.put(TMXMap.class, writtenFiles); - - if (sourceSetToUse == ResourceSet.gameData) { - writeResourceListXml(writtenFilesPerDataType, GameSource.DEFAULT_REL_PATH_FOR_GAME_RESOURCE, baseContent.baseFolder, tmpDir); - } else if (sourceSetToUse == ResourceSet.debugData) { - writeResourceListXml(writtenFilesPerDataType, GameSource.DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE, baseContent.baseFolder, tmpDir); - } - - - if (!createdContent.worldmap.isEmpty() || !alteredContent.worldmap.isEmpty()) { - try { - Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - doc.setXmlVersion("1.0"); - Element root = doc.createElement("worldmap"); - doc.appendChild(root); + File tmpMapDir = new File(tmpDir, TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE); + tmpMapDir.mkdirs(); + writtenFiles = new LinkedList(); + for (File createdMapFile : createdContent.gameMaps.mapFolder.listFiles()) { + if (createdMapFile.getName().equalsIgnoreCase("worldmap.xml")) continue; + copyTmxConverted(createdMapFile.toPath(), Paths.get(tmpMapDir.getAbsolutePath(), createdMapFile.getName())); + writtenFiles.add(createdMapFile.getName()); + } + for (File alteredMapFile : alteredContent.gameMaps.mapFolder.listFiles()) { + if (alteredMapFile.getName().equalsIgnoreCase("worldmap.xml")) continue; + copyTmxConverted(alteredMapFile.toPath(), Paths.get(tmpMapDir.getAbsolutePath(), alteredMapFile.getName())); + writtenFiles.add(alteredMapFile.getName()); + } + writtenFilesPerDataType.put(TMXMap.class, writtenFiles); - for (int i = 0; i < getWorldmapSegmentCount(); i++) { - root.appendChild(getWorldmapSegment(i).toXmlElement(doc)); - } - - Worldmap.saveDocToFile(doc, new File(tmpMapDir, "worldmap.xml")); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - return tmpDir; - } - - private void copyTmxConverted(Path from, Path to) throws IOException { - String xml = new String(Files.readAllBytes(from), StandardCharsets.UTF_8); - xml = xml.replace("../../altered/spritesheets/", drawablePath); - xml = xml.replace("../../created/spritesheets/", drawablePath); - xml = xml.replace("../spritesheets/", drawablePath); - xml = xml.replace("../spritesheets/", drawablePath); - Files.write(to, xml.getBytes(StandardCharsets.UTF_8)); - } + if (sourceSetToUse == ResourceSet.gameData) { + writeResourceListXml(writtenFilesPerDataType, GameSource.DEFAULT_REL_PATH_FOR_GAME_RESOURCE, baseContent.baseFolder, tmpDir); + } else if (sourceSetToUse == ResourceSet.debugData) { + writeResourceListXml(writtenFilesPerDataType, GameSource.DEFAULT_REL_PATH_FOR_DEBUG_RESOURCE, baseContent.baseFolder, tmpDir); + } - @SuppressWarnings("rawtypes") - public List writeDataDeltaForDataType(GameDataCategory created, GameDataCategory altered, GameDataCategory source, Class gdeClass, File targetFolder) { - List filenamesToWrite = new LinkedList(); - Map> dataToWritePerFilename = new LinkedHashMap>(); - for (JSONElement gde : altered) { - if (!filenamesToWrite.contains(gde.jsonFile.getName())) { - filenamesToWrite.add(gde.jsonFile.getName()); - } - } - for (JSONElement gde : created) { - if (!filenamesToWrite.contains(gde.jsonFile.getName())) { - filenamesToWrite.add(gde.jsonFile.getName()); - } - } - for (String fName : filenamesToWrite) { - for (JSONElement gde : source) { - if (gde.jsonFile.getName().equals(fName)) { - if (dataToWritePerFilename.get(fName) == null) { - dataToWritePerFilename.put(fName, new ArrayList()); - } - //Automatically fetches altered element over source element. - dataToWritePerFilename.get(fName).add(getGameDataElement(gdeClass, gde.id).toJson()); - } - } - for (JSONElement gde : created) { - if (gde.jsonFile.getName().equals(fName)) { - if (dataToWritePerFilename.get(fName) == null) { - dataToWritePerFilename.put(fName, new ArrayList()); - } - //Add the created elements. - dataToWritePerFilename.get(fName).add(getGameDataElement(gdeClass, gde.id).toJson()); - } - } - } - for (String fName : dataToWritePerFilename.keySet()) { - File jsonFile = new File(targetFolder, fName); - StringWriter writer = new JsonPrettyWriter(); - try { - JSONArray.writeJSONString(dataToWritePerFilename.get(fName), writer); - } catch (IOException e) { - //Impossible with a StringWriter - } - String textToWrite = writer.toString(); - try { - FileWriter w = new FileWriter(jsonFile); - w.write(textToWrite); - w.close(); + if (!createdContent.worldmap.isEmpty() || !alteredContent.worldmap.isEmpty()) { + try { + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + doc.setXmlVersion("1.0"); + Element root = doc.createElement("worldmap"); + doc.appendChild(root); + + for (int i = 0; i < getWorldmapSegmentCount(); i++) { + root.appendChild(getWorldmapSegment(i).toXmlElement(doc)); + } + + Worldmap.saveDocToFile(doc, new File(tmpMapDir, "worldmap.xml")); + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + return tmpDir; + } + + private void copyTmxConverted(Path from, Path to) throws IOException { + String xml = new String(Files.readAllBytes(from), StandardCharsets.UTF_8); + xml = xml.replace("../../altered/spritesheets/", drawablePath); + xml = xml.replace("../../created/spritesheets/", drawablePath); + xml = xml.replace("../spritesheets/", drawablePath); + xml = xml.replace("../spritesheets/", drawablePath); + Files.write(to, xml.getBytes(StandardCharsets.UTF_8)); + } + + + @SuppressWarnings("rawtypes") + public List writeDataDeltaForDataType(GameDataCategory created, GameDataCategory altered, GameDataCategory source, Class gdeClass, File targetFolder) { + List filenamesToWrite = new LinkedList(); + Map> dataToWritePerFilename = new LinkedHashMap>(); + for (JSONElement gde : altered) { + if (!filenamesToWrite.contains(gde.jsonFile.getName())) { + filenamesToWrite.add(gde.jsonFile.getName()); + } + } + for (JSONElement gde : created) { + if (!filenamesToWrite.contains(gde.jsonFile.getName())) { + filenamesToWrite.add(gde.jsonFile.getName()); + } + } + for (String fName : filenamesToWrite) { + for (JSONElement gde : source) { + if (gde.jsonFile.getName().equals(fName)) { + if (dataToWritePerFilename.get(fName) == null) { + dataToWritePerFilename.put(fName, new ArrayList()); + } + //Automatically fetches altered element over source element. + dataToWritePerFilename.get(fName).add(getGameDataElement(gdeClass, gde.id).toJson()); + } + } + for (JSONElement gde : created) { + if (gde.jsonFile.getName().equals(fName)) { + if (dataToWritePerFilename.get(fName) == null) { + dataToWritePerFilename.put(fName, new ArrayList()); + } + //Add the created elements. + dataToWritePerFilename.get(fName).add(getGameDataElement(gdeClass, gde.id).toJson()); + } + } + } + for (String fName : dataToWritePerFilename.keySet()) { + File jsonFile = new File(targetFolder, fName); + StringWriter writer = new JsonPrettyWriter(); + try { + JSONArray.writeJSONString(dataToWritePerFilename.get(fName), writer); + } catch (IOException e) { + //Impossible with a StringWriter + } + String textToWrite = writer.toString(); + try { + FileWriter w = new FileWriter(jsonFile); + w.write(textToWrite); + w.close(); // Notification.addSuccess("Json file "+jsonFile.getAbsolutePath()+" saved."); - } catch (IOException e) { - Notification.addError("Error while writing json file "+jsonFile.getAbsolutePath()+" : "+e.getMessage()); - e.printStackTrace(); - } - } - return filenamesToWrite; - } - - - private void writeResourceListXml(Map, List> writtenFilesPerDataType, String xmlFileRelPath, File baseFolder, File tmpDir) { - File xmlFile = new File(baseFolder, xmlFileRelPath); - File outputFile = new File(tmpDir, xmlFileRelPath); - - Map> classNamesByArrayNames = new HashMap>(); - classNamesByArrayNames.put("loadresource_itemcategories", ItemCategory.class); - classNamesByArrayNames.put("loadresource_actorconditions", ActorCondition.class); - classNamesByArrayNames.put("loadresource_items", Item.class); - classNamesByArrayNames.put("loadresource_droplists", Droplist.class); - classNamesByArrayNames.put("loadresource_quests", Quest.class); - classNamesByArrayNames.put("loadresource_conversationlists", Dialogue.class); - classNamesByArrayNames.put("loadresource_monsters", NPC.class); - classNamesByArrayNames.put("loadresource_maps", TMXMap.class); - - String jsonResPrefix = "@raw/"; - String tmxResPrefix = "@xml/"; - String jsonFileSuffix = ".json"; - String tmxFileSuffix = ".tmx"; - - if (!xmlFile.exists()) return; - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - Document doc; - try { - factory.setIgnoringElementContentWhitespace(true); - factory.setExpandEntityReferences(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - - InputSource insrc = new InputSource(new FileInputStream(xmlFile)); - insrc.setEncoding("UTF-8"); - doc = builder.parse(insrc); - - Element arrayNode; - String name, resPrefix, fileSuffix, resName, resToFile, fileToRes; - Class clazz; - List writtenFiles; - - Element root = (Element) doc.getElementsByTagName("resources").item(0); - if (root != null) { - NodeList arraysList = root.getElementsByTagName("array"); - if (arraysList != null) { - for (int i = 0; i < arraysList.getLength(); i++) { - arrayNode = (Element) arraysList.item(i); - name = arrayNode.getAttribute("name"); - clazz = classNamesByArrayNames.get(name); - if (clazz == null) continue; - writtenFiles = writtenFilesPerDataType.get(clazz); - if (writtenFiles == null) continue; - if (clazz == TMXMap.class) { - resPrefix = tmxResPrefix; - fileSuffix = tmxFileSuffix; - } else { - resPrefix = jsonResPrefix; - fileSuffix = jsonFileSuffix; - } - NodeList arrayItems = arrayNode.getElementsByTagName("item"); - if (arrayItems != null) { - for (int j = 0; j < arrayItems.getLength(); j++) { - resName = ((Element)arrayItems.item(j)).getTextContent(); - if (resName == null) continue; - resToFile = resName.replaceFirst("\\A"+resPrefix, "")+fileSuffix; - writtenFiles.remove(resToFile); - } - } - if (!writtenFiles.isEmpty()) { - Comment com = doc.createComment("Added by ATCS "+ATContentStudio.APP_VERSION+" for project "+getProject().name); - arrayNode.appendChild(com); - Collections.sort(writtenFiles); - for (String missingRes : writtenFiles) { - Element item = doc.createElement("item"); - fileToRes = resPrefix+missingRes.replaceFirst(fileSuffix+"\\z", ""); - item.setTextContent(fileToRes); - arrayNode.appendChild(item); - } - } - } - } - } - - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - if (!outputFile.getParentFile().exists()) { - outputFile.getParentFile().mkdirs(); - } - StringWriter temp = new StringWriter(); - Result output = new StreamResult(temp); - Source input = new DOMSource(doc); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - transformer.transform(input, output); - - String tempString = temp.toString(); - doc = builder.parse(new ByteArrayInputStream(tempString.getBytes("UTF-8"))); - input = new DOMSource(doc); - transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader( - "\r\n" + - "\r\n" + - " \r\n" + - " \r\n" + - "\r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - "\r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - " \r\n" + - ""))); - output = new StreamResult(new FileOutputStream(outputFile)); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - transformer.transform(input, output); - - - } catch (SAXException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } catch (TransformerException e) { - e.printStackTrace(); - } - } - - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : v.getNonEmptyIterable()) { - if (node.needsSaving()) return true; - } - return false; - } - - + } catch (IOException e) { + Notification.addError("Error while writing json file " + jsonFile.getAbsolutePath() + " : " + e.getMessage()); + e.printStackTrace(); + } + } + return filenamesToWrite; + } + + + private void writeResourceListXml(Map, List> writtenFilesPerDataType, String xmlFileRelPath, File baseFolder, File tmpDir) { + File xmlFile = new File(baseFolder, xmlFileRelPath); + File outputFile = new File(tmpDir, xmlFileRelPath); + + Map> classNamesByArrayNames = new HashMap>(); + classNamesByArrayNames.put("loadresource_itemcategories", ItemCategory.class); + classNamesByArrayNames.put("loadresource_actorconditions", ActorCondition.class); + classNamesByArrayNames.put("loadresource_items", Item.class); + classNamesByArrayNames.put("loadresource_droplists", Droplist.class); + classNamesByArrayNames.put("loadresource_quests", Quest.class); + classNamesByArrayNames.put("loadresource_conversationlists", Dialogue.class); + classNamesByArrayNames.put("loadresource_monsters", NPC.class); + classNamesByArrayNames.put("loadresource_maps", TMXMap.class); + + String jsonResPrefix = "@raw/"; + String tmxResPrefix = "@xml/"; + String jsonFileSuffix = ".json"; + String tmxFileSuffix = ".tmx"; + + if (!xmlFile.exists()) return; + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + Document doc; + try { + factory.setIgnoringElementContentWhitespace(true); + factory.setExpandEntityReferences(false); + DocumentBuilder builder = factory.newDocumentBuilder(); + + InputSource insrc = new InputSource(new FileInputStream(xmlFile)); + insrc.setEncoding("UTF-8"); + doc = builder.parse(insrc); + + Element arrayNode; + String name, resPrefix, fileSuffix, resName, resToFile, fileToRes; + Class clazz; + List writtenFiles; + + Element root = (Element) doc.getElementsByTagName("resources").item(0); + if (root != null) { + NodeList arraysList = root.getElementsByTagName("array"); + if (arraysList != null) { + for (int i = 0; i < arraysList.getLength(); i++) { + arrayNode = (Element) arraysList.item(i); + name = arrayNode.getAttribute("name"); + clazz = classNamesByArrayNames.get(name); + if (clazz == null) continue; + writtenFiles = writtenFilesPerDataType.get(clazz); + if (writtenFiles == null) continue; + if (clazz == TMXMap.class) { + resPrefix = tmxResPrefix; + fileSuffix = tmxFileSuffix; + } else { + resPrefix = jsonResPrefix; + fileSuffix = jsonFileSuffix; + } + NodeList arrayItems = arrayNode.getElementsByTagName("item"); + if (arrayItems != null) { + for (int j = 0; j < arrayItems.getLength(); j++) { + resName = ((Element) arrayItems.item(j)).getTextContent(); + if (resName == null) continue; + resToFile = resName.replaceFirst("\\A" + resPrefix, "") + fileSuffix; + writtenFiles.remove(resToFile); + } + } + if (!writtenFiles.isEmpty()) { + Comment com = doc.createComment("Added by ATCS " + ATContentStudio.APP_VERSION + " for project " + getProject().name); + arrayNode.appendChild(com); + Collections.sort(writtenFiles); + for (String missingRes : writtenFiles) { + Element item = doc.createElement("item"); + fileToRes = resPrefix + missingRes.replaceFirst(fileSuffix + "\\z", ""); + item.setTextContent(fileToRes); + arrayNode.appendChild(item); + } + } + } + } + } + + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + if (!outputFile.getParentFile().exists()) { + outputFile.getParentFile().mkdirs(); + } + StringWriter temp = new StringWriter(); + Result output = new StreamResult(temp); + Source input = new DOMSource(doc); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.transform(input, output); + + String tempString = temp.toString(); + doc = builder.parse(new ByteArrayInputStream(tempString.getBytes("UTF-8"))); + input = new DOMSource(doc); + transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader( + "\r\n" + + "\r\n" + + " \r\n" + + " \r\n" + + "\r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + "\r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + " \r\n" + + ""))); + output = new StreamResult(new FileOutputStream(outputFile)); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); + transformer.transform(input, output); + + + } catch (SAXException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } catch (TransformerException e) { + e.printStackTrace(); + } + } + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : v.getNonEmptyIterable()) { + if (node.needsSaving()) return true; + } + return false; + } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/ProjectElementListener.java b/src/com/gpl/rpg/atcontentstudio/model/ProjectElementListener.java index af0daad..9f04781 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/ProjectElementListener.java +++ b/src/com/gpl/rpg/atcontentstudio/model/ProjectElementListener.java @@ -2,10 +2,10 @@ package com.gpl.rpg.atcontentstudio.model; public interface ProjectElementListener { - public void elementAdded(GameDataElement added, int index); - - public void elementRemoved(GameDataElement removed, int index); - - public Class getDataType(); - + public void elementAdded(GameDataElement added, int index); + + public void elementRemoved(GameDataElement removed, int index); + + public Class getDataType(); + } diff --git a/src/com/gpl/rpg/atcontentstudio/model/ProjectTreeNode.java b/src/com/gpl/rpg/atcontentstudio/model/ProjectTreeNode.java index ae58d2c..31bbf1f 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/ProjectTreeNode.java +++ b/src/com/gpl/rpg/atcontentstudio/model/ProjectTreeNode.java @@ -1,59 +1,64 @@ package com.gpl.rpg.atcontentstudio.model; -import java.awt.Image; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.util.List; + public interface ProjectTreeNode extends TreeNode { - - public void childrenAdded(List path); - public void childrenChanged(List path); - public void childrenRemoved(List path); - public void notifyCreated(); - - public String getDesc(); - /** - * Unnecessary for anything not below a Project. Can return null. - * @return the parent Project or null. - */ - public Project getProject(); - + public void childrenAdded(List path); - /** - * Unnecessary for anything not below a GameDataSet. Can return null. - * @return the parent GameDataSet or null. - */ - public GameDataSet getDataSet(); - - public Image getIcon(); - /** - * - * @return The icon depicting this node when it is an open folder. Can be null for leaves. - */ - public Image getOpenIcon(); - /** - * - * @return The icon depicting this node when it is a closed folder. Can be null for leaves. - */ - public Image getClosedIcon(); - /** - * - * @return The icon depicting this node when it is a leaf. Should return the closed one for empty folders. - */ - public Image getLeafIcon(); - - /** - * Unnecessary for anything not below a GameSource. Can return null. - * @return the parent GameSource or null. - */ - public GameSource.Type getDataType(); - - public boolean isEmpty(); - - public boolean needsSaving(); + public void childrenChanged(List path); + + public void childrenRemoved(List path); + + public void notifyCreated(); + + public String getDesc(); + + /** + * Unnecessary for anything not below a Project. Can return null. + * + * @return the parent Project or null. + */ + public Project getProject(); + + + /** + * Unnecessary for anything not below a GameDataSet. Can return null. + * + * @return the parent GameDataSet or null. + */ + public GameDataSet getDataSet(); + + public Image getIcon(); + + /** + * @return The icon depicting this node when it is an open folder. Can be null for leaves. + */ + public Image getOpenIcon(); + + /** + * @return The icon depicting this node when it is a closed folder. Can be null for leaves. + */ + public Image getClosedIcon(); + + /** + * @return The icon depicting this node when it is a leaf. Should return the closed one for empty folders. + */ + public Image getLeafIcon(); + + /** + * Unnecessary for anything not below a GameSource. Can return null. + * + * @return the parent GameSource or null. + */ + public GameSource.Type getDataType(); + + public boolean isEmpty(); + + public boolean needsSaving(); } diff --git a/src/com/gpl/rpg/atcontentstudio/model/SaveEvent.java b/src/com/gpl/rpg/atcontentstudio/model/SaveEvent.java index 48a51fe..7c7b6dd 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/SaveEvent.java +++ b/src/com/gpl/rpg/atcontentstudio/model/SaveEvent.java @@ -1,35 +1,35 @@ package com.gpl.rpg.atcontentstudio.model; public class SaveEvent { - - public enum Type { - moveToAltered, - moveToCreated, - alsoSave - } - - public Type type; - public GameDataElement target; - - public boolean error = false; - public String errorText; - - public SaveEvent(SaveEvent.Type type, GameDataElement target) { - this.type = type; - this.target = target; - } - - public SaveEvent(SaveEvent.Type type, GameDataElement target, boolean error, String errorText) { - this.type = type; - this.target = target; - this.error = error; - this.errorText = errorText; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SaveEvent)) return false; - else return (((SaveEvent)obj).type == this.type) && (((SaveEvent)obj).target == this.target); - } + + public enum Type { + moveToAltered, + moveToCreated, + alsoSave + } + + public Type type; + public GameDataElement target; + + public boolean error = false; + public String errorText; + + public SaveEvent(SaveEvent.Type type, GameDataElement target) { + this.type = type; + this.target = target; + } + + public SaveEvent(SaveEvent.Type type, GameDataElement target, boolean error, String errorText) { + this.type = type; + this.target = target; + this.error = error; + this.errorText = errorText; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof SaveEvent)) return false; + else return (((SaveEvent) obj).type == this.type) && (((SaveEvent) obj).target == this.target); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/SavedSlotCollection.java b/src/com/gpl/rpg/atcontentstudio/model/SavedSlotCollection.java index c3859be..10cb11c 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/SavedSlotCollection.java +++ b/src/com/gpl/rpg/atcontentstudio/model/SavedSlotCollection.java @@ -5,67 +5,67 @@ import java.util.Vector; public class SavedSlotCollection { - Vector contents = new Vector(); - - public void add(ProjectTreeNode node) { - contents.add(node); - } - - public int getNonEmptySize() { + Vector contents = new Vector(); + + public void add(ProjectTreeNode node) { + contents.add(node); + } + + public int getNonEmptySize() { // return contents.size(); - int size = 0; - for (ProjectTreeNode node : contents) { - if (!node.isEmpty()) size++; - } - return size; - } - - public Enumeration getNonEmptyElements() { + int size = 0; + for (ProjectTreeNode node : contents) { + if (!node.isEmpty()) size++; + } + return size; + } + + public Enumeration getNonEmptyElements() { // return contents.elements(); - Vector v = new Vector(); - for (ProjectTreeNode node : contents) { - if (!node.isEmpty()) v.add(node); - } - return v.elements(); - } - - public ProjectTreeNode getNonEmptyElementAt(int index) { + Vector v = new Vector(); + for (ProjectTreeNode node : contents) { + if (!node.isEmpty()) v.add(node); + } + return v.elements(); + } + + public ProjectTreeNode getNonEmptyElementAt(int index) { // return contents.get(index); - int i = 0; - while (i < contents.size()) { - if (!contents.get(i).isEmpty()) index--; - if (index == -1) return contents.get(i); - i++; - } - return null; - } + int i = 0; + while (i < contents.size()) { + if (!contents.get(i).isEmpty()) index--; + if (index == -1) return contents.get(i); + i++; + } + return null; + } - - public int getNonEmptyIndexOf(ProjectTreeNode node) { + + public int getNonEmptyIndexOf(ProjectTreeNode node) { // return contents.indexOf(node); - int index = contents.indexOf(node); - int trueIndex = index; - for (int i = 0; i < trueIndex; i++) { - if (contents.get(i).isEmpty()) index--; - } - return index; - } - + int index = contents.indexOf(node); + int trueIndex = index; + for (int i = 0; i < trueIndex; i++) { + if (contents.get(i).isEmpty()) index--; + } + return index; + } - public Vector getNonEmptyIterable() { + + public Vector getNonEmptyIterable() { // return contents; - Vector v = new Vector(); - for (ProjectTreeNode node : contents) { - if (!node.isEmpty()) v.add(node); - } - return v; - } - - public boolean isEmpty() { + Vector v = new Vector(); + for (ProjectTreeNode node : contents) { + if (!node.isEmpty()) v.add(node); + } + return v; + } + + public boolean isEmpty() { // return contents.isEmpty(); - for (ProjectTreeNode node : contents) { - if (!node.isEmpty()) return false; - } - return true; - } + for (ProjectTreeNode node : contents) { + if (!node.isEmpty()) return false; + } + return true; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/Workspace.java b/src/com/gpl/rpg/atcontentstudio/model/Workspace.java index 1697279..a1d485f 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/Workspace.java +++ b/src/com/gpl/rpg/atcontentstudio/model/Workspace.java @@ -1,22 +1,5 @@ package com.gpl.rpg.atcontentstudio.model; -import java.awt.Image; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.io.SettingsSave; @@ -25,343 +8,353 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.ProjectsTree.ProjectsTreeModel; import com.gpl.rpg.atcontentstudio.ui.WorkerDialog; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.nio.file.Files; +import java.util.List; +import java.util.*; + public class Workspace implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = 7938633033601384956L; + private static final long serialVersionUID = 7938633033601384956L; - public static final String WS_SETTINGS_FILE = ".workspace"; + public static final String WS_SETTINGS_FILE = ".workspace"; - public static Workspace activeWorkspace; + public static Workspace activeWorkspace; - public Preferences preferences = new Preferences(); - public File baseFolder; - public File settingsFile; - public transient WorkspaceSettings settings; - public transient List projects = new ArrayList(); - public Set projectsName = new HashSet(); - public Map projectsOpenByName = new HashMap(); - public Set knownMapSourcesFolders = new HashSet(); + public Preferences preferences = new Preferences(); + public File baseFolder; + public File settingsFile; + public transient WorkspaceSettings settings; + public transient List projects = new ArrayList(); + public Set projectsName = new HashSet(); + public Map projectsOpenByName = new HashMap(); + public Set knownMapSourcesFolders = new HashSet(); - public transient ProjectsTreeModel projectsTreeModel = null; + public transient ProjectsTreeModel projectsTreeModel = null; - public Workspace(File workspaceRoot) { - baseFolder = workspaceRoot; - if (!workspaceRoot.exists()) { - try { - workspaceRoot.mkdir(); - } catch (SecurityException e) { - Notification.addError("Error creating workspace directory: " - + e.getMessage()); - e.printStackTrace(); - } - } - settings = new WorkspaceSettings(this); - settingsFile = new File(workspaceRoot, WS_SETTINGS_FILE); - if (!settingsFile.exists()) { - try { - settingsFile.createNewFile(); - } catch (IOException e) { - Notification.addError("Error creating workspace datafile: " - + e.getMessage()); - e.printStackTrace(); - } - } - Notification.addSuccess("New workspace created: " - + workspaceRoot.getAbsolutePath()); - save(); - } + public Workspace(File workspaceRoot) { + baseFolder = workspaceRoot; + if (!workspaceRoot.exists()) { + try { + workspaceRoot.mkdir(); + } catch (SecurityException e) { + Notification.addError("Error creating workspace directory: " + + e.getMessage()); + e.printStackTrace(); + } + } + settings = new WorkspaceSettings(this); + settingsFile = new File(workspaceRoot, WS_SETTINGS_FILE); + if (!settingsFile.exists()) { + try { + settingsFile.createNewFile(); + } catch (IOException e) { + Notification.addError("Error creating workspace datafile: " + + e.getMessage()); + e.printStackTrace(); + } + } + Notification.addSuccess("New workspace created: " + + workspaceRoot.getAbsolutePath()); + save(); + } - public static void setActive(File workspaceRoot) { - Workspace w; - File f = new File(workspaceRoot, WS_SETTINGS_FILE); - if (!workspaceRoot.exists() || !f.exists()) { - w = new Workspace(workspaceRoot); - } else { - w = (Workspace) SettingsSave.loadInstance(f, "Workspace"); - if (w == null) { - w = new Workspace(workspaceRoot); - } else { - w.refreshTransients(); - } - } - activeWorkspace = w; - } + public static void setActive(File workspaceRoot) { + Workspace w; + File f = new File(workspaceRoot, WS_SETTINGS_FILE); + if (!workspaceRoot.exists() || !f.exists()) { + w = new Workspace(workspaceRoot); + } else { + w = (Workspace) SettingsSave.loadInstance(f, "Workspace"); + if (w == null) { + w = new Workspace(workspaceRoot); + } else { + w.refreshTransients(); + } + } + activeWorkspace = w; + } - public static void saveActive() { - activeWorkspace.save(); - } + public static void saveActive() { + activeWorkspace.save(); + } - public void save() { - settings.save(); - SettingsSave.saveInstance(this, settingsFile, "Workspace"); - } + public void save() { + settings.save(); + SettingsSave.saveInstance(this, settingsFile, "Workspace"); + } - @Override - public Enumeration children() { - return Collections.enumeration(projects); - } + @Override + public Enumeration children() { + return Collections.enumeration(projects); + } - @Override - public boolean getAllowsChildren() { - return true; - } + @Override + public boolean getAllowsChildren() { + return true; + } - @Override - public TreeNode getChildAt(int arg0) { - return projects.get(arg0); - } + @Override + public TreeNode getChildAt(int arg0) { + return projects.get(arg0); + } - @Override - public int getChildCount() { - return projects.size(); - } + @Override + public int getChildCount() { + return projects.size(); + } - @Override - public int getIndex(TreeNode arg0) { - return projects.indexOf(arg0); - } + @Override + public int getIndex(TreeNode arg0) { + return projects.indexOf(arg0); + } - @Override - public TreeNode getParent() { - return null; - } + @Override + public TreeNode getParent() { + return null; + } - @Override - public boolean isLeaf() { - return false; - } + @Override + public boolean isLeaf() { + return false; + } - @Override - public void childrenAdded(List path) { - path.add(0, this); - if (projectsTreeModel != null) - projectsTreeModel.insertNode(new TreePath(path.toArray())); - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + if (projectsTreeModel != null) + projectsTreeModel.insertNode(new TreePath(path.toArray())); + } - @Override - public void childrenChanged(List path) { - path.add(0, this); - ProjectTreeNode last = path.get(path.size() - 1); - if (projectsTreeModel != null) { - while (path.size() > 1) { - projectsTreeModel.changeNode(new TreePath(path.toArray())); - path.remove(path.size()-1); - } - - } - ATContentStudio.frame.editorChanged(last); - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + ProjectTreeNode last = path.get(path.size() - 1); + if (projectsTreeModel != null) { + while (path.size() > 1) { + projectsTreeModel.changeNode(new TreePath(path.toArray())); + path.remove(path.size() - 1); + } - @Override - public void childrenRemoved(List path) { - path.add(0, this); - if (projectsTreeModel != null) - projectsTreeModel.removeNode(new TreePath(path.toArray())); - } + } + ATContentStudio.frame.editorChanged(last); + } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (ProjectTreeNode node : projects) { - if (node != null) - node.notifyCreated(); - } - } + @Override + public void childrenRemoved(List path) { + path.add(0, this); + if (projectsTreeModel != null) + projectsTreeModel.removeNode(new TreePath(path.toArray())); + } - @Override - public String getDesc() { - return "Workspace: " + baseFolder.getAbsolutePath(); - } + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (ProjectTreeNode node : projects) { + if (node != null) + node.notifyCreated(); + } + } - public static void createProject(final String projectName, - final File gameSourceFolder, final Project.ResourceSet sourceSet) { - WorkerDialog.showTaskMessage("Creating project " + projectName + "...", - ATContentStudio.frame, new Runnable() { - @Override - public void run() { - if (activeWorkspace.projectsName.contains(projectName)) { - Notification.addError("A project named " - + projectName - + " already exists in this workspace."); - return; - } - Project p = new Project(activeWorkspace, projectName, - gameSourceFolder, sourceSet); - activeWorkspace.projects.add(p); - activeWorkspace.projectsName.add(projectName); - activeWorkspace.projectsOpenByName.put(projectName, - p.open); - activeWorkspace.knownMapSourcesFolders - .add(gameSourceFolder); - p.notifyCreated(); - Notification.addSuccess("Project " + projectName - + " successfully created"); - saveActive(); - } - }); - } + @Override + public String getDesc() { + return "Workspace: " + baseFolder.getAbsolutePath(); + } - public static void closeProject(Project p) { - int index = activeWorkspace.projects.indexOf(p); - if (index < 0) { - Notification.addError("Cannot close unknown project " + p.name); - return; - } - p.close(); - ClosedProject cp = new ClosedProject(activeWorkspace, p.name); - activeWorkspace.projects.set(index, cp); - activeWorkspace.projectsOpenByName.put(p.name, false); - cp.notifyCreated(); - saveActive(); - } + public static void createProject(final String projectName, + final File gameSourceFolder, final Project.ResourceSet sourceSet) { + WorkerDialog.showTaskMessage("Creating project " + projectName + "...", + ATContentStudio.frame, new Runnable() { + @Override + public void run() { + if (activeWorkspace.projectsName.contains(projectName)) { + Notification.addError("A project named " + + projectName + + " already exists in this workspace."); + return; + } + Project p = new Project(activeWorkspace, projectName, + gameSourceFolder, sourceSet); + activeWorkspace.projects.add(p); + activeWorkspace.projectsName.add(projectName); + activeWorkspace.projectsOpenByName.put(projectName, + p.open); + activeWorkspace.knownMapSourcesFolders + .add(gameSourceFolder); + p.notifyCreated(); + Notification.addSuccess("Project " + projectName + + " successfully created"); + saveActive(); + } + }); + } - public static void openProject(final ClosedProject cp) { - WorkerDialog.showTaskMessage("Opening project " + cp.name + "...", - ATContentStudio.frame, new Runnable() { - @Override - public void run() { - int index = activeWorkspace.projects.indexOf(cp); - if (index < 0) { - Notification - .addError("Cannot open unknown project " - + cp.name); - return; - } - cp.childrenRemoved(new ArrayList()); - Project p = Project.fromFolder(activeWorkspace, - new File(activeWorkspace.baseFolder, cp.name)); - p.open(); - activeWorkspace.projects.set(index, p); - activeWorkspace.projectsOpenByName.put(p.name, true); - p.notifyCreated(); - saveActive(); - } - }); - } - - public void refreshTransients() { - this.settings = new WorkspaceSettings(this); - this.projects = new ArrayList(); - Set projectsFailed = new HashSet(); - for (String projectName : projectsName) { - if (projectsOpenByName.get(projectName)) { - File projRoot = new File(this.baseFolder, projectName); - if (projRoot.exists()) { - Project p = Project.fromFolder(this, projRoot); - if (p != null) { - projects.add(p); - } else { - Notification - .addError("Failed to open project " - + projectName - + ". Removing it from workspace (not from filesystem though)."); - projectsFailed.add(projectName); - } - } else { - Notification.addError("Unable to find project " - + projectName - + "'s root folder. Removing it from workspace"); - projectsFailed.add(projectName); - } - } else { - projects.add(new ClosedProject(this, projectName)); - } - } - for (String projectName : projectsFailed) { - projectsName.remove(projectName); - projectsOpenByName.remove(projectName); - } - notifyCreated(); - } - - @Override - public Project getProject() { - return null; - } - - @Override - public Image getIcon() { - return null; - } - - @Override - public Image getClosedIcon() { - return null; - } - - @Override - public Image getLeafIcon() { - return null; - } - - @Override - public Image getOpenIcon() { - return null; - } - - public static void deleteProject(ClosedProject cp) { - cp.childrenRemoved(new ArrayList()); - activeWorkspace.projects.remove(cp); - activeWorkspace.projectsOpenByName.remove(cp.name); - activeWorkspace.projectsName.remove(cp.name); - if (delete(new File(activeWorkspace.baseFolder, cp.name))) { - Notification.addSuccess("Closed project " + cp.name - + " successfully deleted."); - } else { - Notification.addError("Error while deleting closed project " - + cp.name + ". Files may remain in the workspace."); - } + public static void closeProject(Project p) { + int index = activeWorkspace.projects.indexOf(p); + if (index < 0) { + Notification.addError("Cannot close unknown project " + p.name); + return; + } + p.close(); + ClosedProject cp = new ClosedProject(activeWorkspace, p.name); + activeWorkspace.projects.set(index, cp); + activeWorkspace.projectsOpenByName.put(p.name, false); + cp.notifyCreated(); saveActive(); - } + } - public static void deleteProject(Project p) { - p.childrenRemoved(new ArrayList()); - activeWorkspace.projects.remove(p); - activeWorkspace.projectsOpenByName.remove(p.name); - activeWorkspace.projectsName.remove(p.name); - if (delete(p.baseFolder)) { - Notification.addSuccess("Project " + p.name - + " successfully deleted."); - } else { - Notification.addError("Error while deleting project " + p.name - + ". Files may remain in the workspace."); - } + public static void openProject(final ClosedProject cp) { + WorkerDialog.showTaskMessage("Opening project " + cp.name + "...", + ATContentStudio.frame, new Runnable() { + @Override + public void run() { + int index = activeWorkspace.projects.indexOf(cp); + if (index < 0) { + Notification + .addError("Cannot open unknown project " + + cp.name); + return; + } + cp.childrenRemoved(new ArrayList()); + Project p = Project.fromFolder(activeWorkspace, + new File(activeWorkspace.baseFolder, cp.name)); + p.open(); + activeWorkspace.projects.set(index, p); + activeWorkspace.projectsOpenByName.put(p.name, true); + p.notifyCreated(); + saveActive(); + } + }); + } + + public void refreshTransients() { + this.settings = new WorkspaceSettings(this); + this.projects = new ArrayList(); + Set projectsFailed = new HashSet(); + for (String projectName : projectsName) { + if (projectsOpenByName.get(projectName)) { + File projRoot = new File(this.baseFolder, projectName); + if (projRoot.exists()) { + Project p = Project.fromFolder(this, projRoot); + if (p != null) { + projects.add(p); + } else { + Notification + .addError("Failed to open project " + + projectName + + ". Removing it from workspace (not from filesystem though)."); + projectsFailed.add(projectName); + } + } else { + Notification.addError("Unable to find project " + + projectName + + "'s root folder. Removing it from workspace"); + projectsFailed.add(projectName); + } + } else { + projects.add(new ClosedProject(this, projectName)); + } + } + for (String projectName : projectsFailed) { + projectsName.remove(projectName); + projectsOpenByName.remove(projectName); + } + notifyCreated(); + } + + @Override + public Project getProject() { + return null; + } + + @Override + public Image getIcon() { + return null; + } + + @Override + public Image getClosedIcon() { + return null; + } + + @Override + public Image getLeafIcon() { + return null; + } + + @Override + public Image getOpenIcon() { + return null; + } + + public static void deleteProject(ClosedProject cp) { + cp.childrenRemoved(new ArrayList()); + activeWorkspace.projects.remove(cp); + activeWorkspace.projectsOpenByName.remove(cp.name); + activeWorkspace.projectsName.remove(cp.name); + if (delete(new File(activeWorkspace.baseFolder, cp.name))) { + Notification.addSuccess("Closed project " + cp.name + + " successfully deleted."); + } else { + Notification.addError("Error while deleting closed project " + + cp.name + ". Files may remain in the workspace."); + } saveActive(); - } + } - private static boolean delete(File f) { - boolean b = true; - if (Files.isSymbolicLink(f.toPath())) { - b &= f.delete(); - } else if (f.isDirectory()) { - for (File c : f.listFiles()) - b &= delete(c); - } - return b & f.delete(); - } + public static void deleteProject(Project p) { + p.childrenRemoved(new ArrayList()); + activeWorkspace.projects.remove(p); + activeWorkspace.projectsOpenByName.remove(p.name); + activeWorkspace.projectsName.remove(p.name); + if (delete(p.baseFolder)) { + Notification.addSuccess("Project " + p.name + + " successfully deleted."); + } else { + Notification.addError("Error while deleting project " + p.name + + ". Files may remain in the workspace."); + } + saveActive(); + } - @Override - public GameDataSet getDataSet() { - return null; - } + private static boolean delete(File f) { + boolean b = true; + if (Files.isSymbolicLink(f.toPath())) { + b &= f.delete(); + } else if (f.isDirectory()) { + for (File c : f.listFiles()) + b &= delete(c); + } + return b & f.delete(); + } - @Override - public Type getDataType() { - return null; - } + @Override + public GameDataSet getDataSet() { + return null; + } - @Override - public boolean isEmpty() { - return projects.isEmpty(); - } - + @Override + public Type getDataType() { + return null; + } - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : projects) { - if (node.needsSaving()) return true; - } - return false; - } + @Override + public boolean isEmpty() { + return projects.isEmpty(); + } + + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : projects) { + if (node.needsSaving()) return true; + } + return false; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/WorkspaceSettings.java b/src/com/gpl/rpg/atcontentstudio/model/WorkspaceSettings.java index 3072542..37773e4 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/WorkspaceSettings.java +++ b/src/com/gpl/rpg/atcontentstudio/model/WorkspaceSettings.java @@ -1,220 +1,214 @@ package com.gpl.rpg.atcontentstudio.model; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; + +import java.io.*; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; - public class WorkspaceSettings { - - public static final String VERSION_KEY = "ATCS_Version"; - public static final String FILENAME = "workspace_settings.json"; - - public static final int SETTINGS_VERSION = 1; - public Workspace parent; - public File file; - - public static Boolean DEFAULT_USE_SYS_MAP_EDITOR = true; - public Setting useSystemDefaultMapEditor = new PrimitiveSetting("useSystemDefaultMapEditor", DEFAULT_USE_SYS_MAP_EDITOR); - public static String DEFAULT_MAP_EDITOR_COMMAND = "tiled"; - public Setting mapEditorCommand = new PrimitiveSetting("mapEditorCommand", DEFAULT_MAP_EDITOR_COMMAND); - - public static Boolean DEFAULT_USE_SYS_IMG_VIEWER = true; - public Setting useSystemDefaultImageViewer = new PrimitiveSetting("useSystemDefaultImageViewer", DEFAULT_USE_SYS_IMG_VIEWER); - public static Boolean DEFAULT_USE_SYS_IMG_EDITOR = false; - public Setting useSystemDefaultImageEditor = new PrimitiveSetting("useSystemDefaultImageEditor", DEFAULT_USE_SYS_IMG_EDITOR); - public static String DEFAULT_IMG_EDITOR_COMMAND = "gimp"; - public Setting imageEditorCommand = new PrimitiveSetting("imageEditorCommand", DEFAULT_IMG_EDITOR_COMMAND); + public static final String VERSION_KEY = "ATCS_Version"; + public static final String FILENAME = "workspace_settings.json"; - public static String[] LANGUAGE_LIST = new String[]{null, "de", "ru", "pl", "fr", "it", "es", "nl", "uk", "ca", "sv", "pt", "pt_BR", "zh_Hant", "zh_Hans", "ja", "cs", "tr", "ko", "hu", "sl", "bg", "id", "fi", "th", "gl", "ms" ,"pa", "az", "nb"}; - public Setting translatorLanguage = new NullDefaultPrimitiveSetting("translatorLanguage"); - public static Boolean DEFAULT_ALLOW_INTERNET = true; - public Setting useInternet = new PrimitiveSetting("useInternet", DEFAULT_ALLOW_INTERNET); - public static Boolean DEFAULT_CHECK_UPDATE = true; - public Setting checkUpdates = new PrimitiveSetting("checkUpdates", DEFAULT_CHECK_UPDATE); - + public static final int SETTINGS_VERSION = 1; - public List> settings = new ArrayList>(); - - public WorkspaceSettings(Workspace parent) { - this.parent = parent; - settings.add(useSystemDefaultMapEditor); - settings.add(mapEditorCommand); - settings.add(useSystemDefaultImageViewer); - settings.add(useSystemDefaultImageEditor); - settings.add(imageEditorCommand); - settings.add(translatorLanguage); - settings.add(useInternet); - settings.add(checkUpdates); - file = new File(parent.baseFolder, FILENAME); - if (file.exists()) { - load(file); - } - } - - public void load(File f) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(f); - @SuppressWarnings("rawtypes") - Map jsonSettings = (Map) parser.parse(reader); - Integer version = ((Number) jsonSettings.get(VERSION_KEY)).intValue(); - if (version != null) { - if (version >= 1) { - loadv1(jsonSettings); - } - } - - } catch (Exception e) { - Notification.addError("Error while parsing workspace settings: "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - private void loadv1(Map jsonSettings) { - for (Setting s : settings) { - s.readFromJson(jsonSettings); - } - } + public Workspace parent; + public File file; - @SuppressWarnings("unchecked") - public void save() { - @SuppressWarnings("rawtypes") - Map json = new LinkedHashMap(); - for (Setting s : settings) { - s.saveToJson(json); - } - - if (json.isEmpty()) { - //Everything is default. - file.delete(); - return; - } + public static Boolean DEFAULT_USE_SYS_MAP_EDITOR = true; + public Setting useSystemDefaultMapEditor = new PrimitiveSetting("useSystemDefaultMapEditor", DEFAULT_USE_SYS_MAP_EDITOR); + public static String DEFAULT_MAP_EDITOR_COMMAND = "tiled"; + public Setting mapEditorCommand = new PrimitiveSetting("mapEditorCommand", DEFAULT_MAP_EDITOR_COMMAND); - json.put(VERSION_KEY, SETTINGS_VERSION); - StringWriter writer = new JsonPrettyWriter(); - try { - JSONObject.writeJSONString(json, writer); - } catch (IOException e) { - //Impossible with a StringWriter - } - String toWrite = writer.toString(); - try { - FileWriter w = new FileWriter(file); - w.write(toWrite); - w.close(); - Notification.addSuccess("Workspace settings saved."); - } catch (IOException e) { - Notification.addError("Error while saving workspace settings : "+e.getMessage()); - e.printStackTrace(); - } - } - - public void resetDefault() { - for (Setting s : settings) { - s.resetDefault(); - } - } - - public abstract class Setting { + public static Boolean DEFAULT_USE_SYS_IMG_VIEWER = true; + public Setting useSystemDefaultImageViewer = new PrimitiveSetting("useSystemDefaultImageViewer", DEFAULT_USE_SYS_IMG_VIEWER); + public static Boolean DEFAULT_USE_SYS_IMG_EDITOR = false; + public Setting useSystemDefaultImageEditor = new PrimitiveSetting("useSystemDefaultImageEditor", DEFAULT_USE_SYS_IMG_EDITOR); + public static String DEFAULT_IMG_EDITOR_COMMAND = "gimp"; + public Setting imageEditorCommand = new PrimitiveSetting("imageEditorCommand", DEFAULT_IMG_EDITOR_COMMAND); - public String id; - public X value, defaultValue; - - public void setCurrentValue(X value) { - this.value = value; - } - - public X getCurrentValue() { - return value; - } - - public X getDefaultValue() { - return defaultValue; - } - - public void resetDefault() { - value = defaultValue; - } - - public abstract void readFromJson(@SuppressWarnings("rawtypes") Map json); - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void saveToJson(Map json) { - if (!defaultValue.equals(value)) json.put(id, value); - } - } - - public class PrimitiveSetting extends Setting { - - - public PrimitiveSetting(String id, X defaultValue) { - this.id = id; - this.value = this.defaultValue = defaultValue; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void readFromJson(Map json) { - if (json.get(id) != null) value = (X)json.get(id); - } - - - } - - public class NullDefaultPrimitiveSetting extends PrimitiveSetting { - - public NullDefaultPrimitiveSetting(String id) { - super(id, null); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void saveToJson(Map json) { - if (value != null) json.put(id, value); - } - } - - public class ListSetting extends Setting> { + public static String[] LANGUAGE_LIST = new String[]{null, "de", "ru", "pl", "fr", "it", "es", "nl", "uk", "ca", "sv", "pt", "pt_BR", "zh_Hant", "zh_Hans", "ja", "cs", "tr", "ko", "hu", "sl", "bg", "id", "fi", "th", "gl", "ms", "pa", "az", "nb"}; + public Setting translatorLanguage = new NullDefaultPrimitiveSetting("translatorLanguage"); + public static Boolean DEFAULT_ALLOW_INTERNET = true; + public Setting useInternet = new PrimitiveSetting("useInternet", DEFAULT_ALLOW_INTERNET); + public static Boolean DEFAULT_CHECK_UPDATE = true; + public Setting checkUpdates = new PrimitiveSetting("checkUpdates", DEFAULT_CHECK_UPDATE); + + + public List> settings = new ArrayList>(); + + public WorkspaceSettings(Workspace parent) { + this.parent = parent; + settings.add(useSystemDefaultMapEditor); + settings.add(mapEditorCommand); + settings.add(useSystemDefaultImageViewer); + settings.add(useSystemDefaultImageEditor); + settings.add(imageEditorCommand); + settings.add(translatorLanguage); + settings.add(useInternet); + settings.add(checkUpdates); + file = new File(parent.baseFolder, FILENAME); + if (file.exists()) { + load(file); + } + } + + public void load(File f) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(f); + @SuppressWarnings("rawtypes") + Map jsonSettings = (Map) parser.parse(reader); + Integer version = ((Number) jsonSettings.get(VERSION_KEY)).intValue(); + if (version != null) { + if (version >= 1) { + loadv1(jsonSettings); + } + } + + } catch (Exception e) { + Notification.addError("Error while parsing workspace settings: " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + private void loadv1(Map jsonSettings) { + for (Setting s : settings) { + s.readFromJson(jsonSettings); + } + } + + @SuppressWarnings("unchecked") + public void save() { + @SuppressWarnings("rawtypes") + Map json = new LinkedHashMap(); + for (Setting s : settings) { + s.saveToJson(json); + } + + if (json.isEmpty()) { + //Everything is default. + file.delete(); + return; + } + + json.put(VERSION_KEY, SETTINGS_VERSION); + StringWriter writer = new JsonPrettyWriter(); + try { + JSONObject.writeJSONString(json, writer); + } catch (IOException e) { + //Impossible with a StringWriter + } + String toWrite = writer.toString(); + try { + FileWriter w = new FileWriter(file); + w.write(toWrite); + w.close(); + Notification.addSuccess("Workspace settings saved."); + } catch (IOException e) { + Notification.addError("Error while saving workspace settings : " + e.getMessage()); + e.printStackTrace(); + } + } + + public void resetDefault() { + for (Setting s : settings) { + s.resetDefault(); + } + } + + public abstract class Setting { + + public String id; + public X value, defaultValue; + + public void setCurrentValue(X value) { + this.value = value; + } + + public X getCurrentValue() { + return value; + } + + public X getDefaultValue() { + return defaultValue; + } + + public void resetDefault() { + value = defaultValue; + } + + public abstract void readFromJson(@SuppressWarnings("rawtypes") Map json); + + @SuppressWarnings({"rawtypes", "unchecked"}) + public void saveToJson(Map json) { + if (!defaultValue.equals(value)) json.put(id, value); + } + } + + public class PrimitiveSetting extends Setting { + + + public PrimitiveSetting(String id, X defaultValue) { + this.id = id; + this.value = this.defaultValue = defaultValue; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public void readFromJson(Map json) { + if (json.get(id) != null) value = (X) json.get(id); + } + + + } + + public class NullDefaultPrimitiveSetting extends PrimitiveSetting { + + public NullDefaultPrimitiveSetting(String id) { + super(id, null); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void saveToJson(Map json) { + if (value != null) json.put(id, value); + } + } + + public class ListSetting extends Setting> { + + public ListSetting(String id, List defaultValue) { + this.id = id; + this.value = this.defaultValue = defaultValue; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void readFromJson(Map json) { + value = new ArrayList(); + if (json.get(id) != null) { + for (Object o : ((List) json.get(id))) { + value.add((X) o); + } + } + } + + } - public ListSetting(String id, List defaultValue) { - this.id = id; - this.value = this.defaultValue = defaultValue; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void readFromJson(Map json) { - value = new ArrayList(); - if (json.get(id) != null) { - for (Object o : ((List)json.get(id))) { - value.add((X)o); - } - } - } - - } - - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java index 17f811d..1827e20 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java +++ b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java @@ -1,12 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.bookmarks; -import java.awt.Image; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.Project; @@ -15,141 +8,148 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + public class BookmarkEntry implements BookmarkNode { - public GameDataElement bookmarkedElement; - public BookmarkFolder parent; - - public BookmarkEntry(BookmarkFolder parent, GameDataElement target) { - this.parent = parent; - this.bookmarkedElement = target; - target.bookmark = this; - parent.contents.add(this); - } - - @Override - public Enumeration children() { - return null; - } + public GameDataElement bookmarkedElement; + public BookmarkFolder parent; - @Override - public boolean getAllowsChildren() { - return false; - } + public BookmarkEntry(BookmarkFolder parent, GameDataElement target) { + this.parent = parent; + this.bookmarkedElement = target; + target.bookmark = this; + parent.contents.add(this); + } - @Override - public TreeNode getChildAt(int childIndex) { - return null; - } + @Override + public Enumeration children() { + return null; + } - @Override - public int getChildCount() { - return 0; - } + @Override + public boolean getAllowsChildren() { + return false; + } - @Override - public int getIndex(TreeNode node) { - return 0; - } + @Override + public TreeNode getChildAt(int childIndex) { + return null; + } - @Override - public TreeNode getParent() { - return parent; - } + @Override + public int getChildCount() { + return 0; + } - @Override - public boolean isLeaf() { - return true; - } + @Override + public int getIndex(TreeNode node) { + return 0; + } - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } + @Override + public boolean isLeaf() { + return true; + } - @Override - public void childrenRemoved(List path) { - path.add(0,this); - parent.childrenRemoved(path); - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } - @Override - public String getDesc() { - if (bookmarkedElement instanceof QuestStage) { - String text = ((GameDataElement)bookmarkedElement).getDesc(); - if (text.length() > 60) { - text = text.substring(0, 57)+"..."; - } - return ((GameDataElement)bookmarkedElement).getDataType().toString()+"/"+((Quest)((QuestStage)bookmarkedElement).parent).id+"#"+((QuestStage)bookmarkedElement).progress+":"+text; - } else { - return ((GameDataElement)bookmarkedElement).getDataType().toString()+"/"+((GameDataElement)bookmarkedElement).getDesc(); - } - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } - @Override - public Project getProject() { - return parent.getProject(); - } + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } - @Override - public GameDataSet getDataSet() { - return null; - } + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } - @Override - public Image getIcon() { - return bookmarkedElement.getIcon(); - } + @Override + public String getDesc() { + if (bookmarkedElement instanceof QuestStage) { + String text = ((GameDataElement) bookmarkedElement).getDesc(); + if (text.length() > 60) { + text = text.substring(0, 57) + "..."; + } + return ((GameDataElement) bookmarkedElement).getDataType().toString() + "/" + ((Quest) ((QuestStage) bookmarkedElement).parent).id + "#" + ((QuestStage) bookmarkedElement).progress + ":" + text; + } else { + return ((GameDataElement) bookmarkedElement).getDataType().toString() + "/" + ((GameDataElement) bookmarkedElement).getDesc(); + } + } - @Override - public Image getOpenIcon() { - return null; - } + @Override + public Project getProject() { + return parent.getProject(); + } - @Override - public Image getClosedIcon() { - return null; - } + @Override + public GameDataSet getDataSet() { + return null; + } - @Override - public Image getLeafIcon() { - return getIcon(); - } + @Override + public Image getIcon() { + return bookmarkedElement.getIcon(); + } - @Override - public Type getDataType() { - return null; - } + @Override + public Image getOpenIcon() { + return null; + } - @Override - public boolean isEmpty() { - return true; - } + @Override + public Image getClosedIcon() { + return null; + } - @Override - public boolean needsSaving() { - return false; - } - - public void delete() { - bookmarkedElement.bookmark = null; - parent.delete(this); - } - - @Override - public void save() { - parent.save(); - } + @Override + public Image getLeafIcon() { + return getIcon(); + } + + @Override + public Type getDataType() { + return null; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + public boolean needsSaving() { + return false; + } + + public void delete() { + bookmarkedElement.bookmark = null; + parent.delete(this); + } + + @Override + public void save() { + parent.save(); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkFolder.java b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkFolder.java index c34be73..b01b2f5 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkFolder.java +++ b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkFolder.java @@ -1,168 +1,165 @@ package com.gpl.rpg.atcontentstudio.model.bookmarks; -import java.awt.Image; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.util.List; +import java.util.*; + public class BookmarkFolder implements BookmarkNode { - List contents = new LinkedList(); - BookmarkNode parent; - String name; - Image closedIcon, openIcon; + List contents = new LinkedList(); + BookmarkNode parent; + String name; + Image closedIcon, openIcon; - public BookmarkFolder(BookmarkNode parent, String name) { - this(parent, name, DefaultIcons.getStdClosedIcon(), DefaultIcons.getStdOpenIcon()); - } - - public BookmarkFolder(BookmarkNode parent, String name, Image closedIcon, Image openIcon) { - this.parent = parent; - this.name = name; - this.closedIcon = closedIcon; - this.openIcon = openIcon; - } - - @Override - public Enumeration children() { - return Collections.enumeration(contents); - } + public BookmarkFolder(BookmarkNode parent, String name) { + this(parent, name, DefaultIcons.getStdClosedIcon(), DefaultIcons.getStdOpenIcon()); + } - @Override - public boolean getAllowsChildren() { - return true; - } + public BookmarkFolder(BookmarkNode parent, String name, Image closedIcon, Image openIcon) { + this.parent = parent; + this.name = name; + this.closedIcon = closedIcon; + this.openIcon = openIcon; + } - @Override - public TreeNode getChildAt(int childIndex) { - return contents.get(childIndex); - } + @Override + public Enumeration children() { + return Collections.enumeration(contents); + } - @Override - public int getChildCount() { - return contents.size(); - } + @Override + public boolean getAllowsChildren() { + return true; + } - @Override - public int getIndex(TreeNode node) { - return contents.indexOf(node); - } + @Override + public TreeNode getChildAt(int childIndex) { + return contents.get(childIndex); + } - @Override - public TreeNode getParent() { - return parent; - } + @Override + public int getChildCount() { + return contents.size(); + } - @Override - public boolean isLeaf() { - return false; - } - - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } + @Override + public int getIndex(TreeNode node) { + return contents.indexOf(node); + } - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.getChildCount() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } + @Override + public boolean isLeaf() { + return false; + } - @Override - public String getDesc() { - return name; - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } - @Override - public Project getProject() { - return parent.getProject(); - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } - @Override - public GameDataSet getDataSet() { - return null; - } + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.getChildCount() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } - @Override - public Image getIcon() { - return getClosedIcon(); - } + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } - @Override - public Image getOpenIcon() { - return openIcon; - } + @Override + public String getDesc() { + return name; + } - @Override - public Image getClosedIcon() { - return closedIcon; - } + @Override + public Project getProject() { + return parent.getProject(); + } - @Override - public Image getLeafIcon() { - return getClosedIcon(); - } + @Override + public GameDataSet getDataSet() { + return null; + } - @Override - public Type getDataType() { - return null; - } + @Override + public Image getIcon() { + return getClosedIcon(); + } - @Override - public boolean isEmpty() { - return contents.isEmpty(); - } + @Override + public Image getOpenIcon() { + return openIcon; + } - @Override - public boolean needsSaving() { - return false; - } + @Override + public Image getClosedIcon() { + return closedIcon; + } - public void delete(BookmarkEntry bookmarkEntry) { - if (contents.contains(bookmarkEntry)) { - bookmarkEntry.childrenRemoved(new ArrayList()); - contents.remove(bookmarkEntry); - save(); - } - } - - public void delete(BookmarkFolder bookmarkFolder) { - // TODO Auto-generated method stub - - } - - public void save() { - parent.save(); - } - - public void delete() { - - } + @Override + public Image getLeafIcon() { + return getClosedIcon(); + } + + @Override + public Type getDataType() { + return null; + } + + @Override + public boolean isEmpty() { + return contents.isEmpty(); + } + + @Override + public boolean needsSaving() { + return false; + } + + public void delete(BookmarkEntry bookmarkEntry) { + if (contents.contains(bookmarkEntry)) { + bookmarkEntry.childrenRemoved(new ArrayList()); + contents.remove(bookmarkEntry); + save(); + } + } + + public void delete(BookmarkFolder bookmarkFolder) { + // TODO Auto-generated method stub + + } + + public void save() { + parent.save(); + } + + public void delete() { + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkNode.java b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkNode.java index 4b64420..880f738 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkNode.java +++ b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkNode.java @@ -2,9 +2,10 @@ package com.gpl.rpg.atcontentstudio.model.bookmarks; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -public interface BookmarkNode extends ProjectTreeNode{ +public interface BookmarkNode extends ProjectTreeNode { + + public void save(); + + public void delete(); - public void save(); - public void delete(); - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java index 588c1f3..8308ffc 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java +++ b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarksRoot.java @@ -1,210 +1,206 @@ package com.gpl.rpg.atcontentstudio.model.bookmarks; -import java.awt.Image; -import java.io.File; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.SavedSlotCollection; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + public class BookmarksRoot implements BookmarkNode { - SavedSlotCollection v = new SavedSlotCollection(); + SavedSlotCollection v = new SavedSlotCollection(); - public transient Project parent; - - BookmarkFolder ac, diag, dl, it, ic, npc, q, tmx, sp, wm; - - public BookmarksRoot(Project parent) { - this.parent = parent; + public transient Project parent; - v.add(ac = new BookmarkFolder(this, ActorCondition.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - v.add(diag = new BookmarkFolder(this, Dialogue.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - v.add(dl = new BookmarkFolder(this, Droplist.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - v.add(it = new BookmarkFolder(this, Item.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - v.add(ic = new BookmarkFolder(this, ItemCategory.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - v.add(npc = new BookmarkFolder(this, NPC.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - v.add(q = new BookmarkFolder(this, Quest.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - - v.add(tmx = new BookmarkFolder(this, "TMX Maps", DefaultIcons.getTmxClosedIcon(), DefaultIcons.getTmxOpenIcon())); - v.add(sp = new BookmarkFolder(this, "Spritesheets", DefaultIcons.getSpriteClosedIcon(), DefaultIcons.getSpriteOpenIcon())); - v.add(wm = new BookmarkFolder(this, "Worldmap", DefaultIcons.getSpriteClosedIcon(), DefaultIcons.getSpriteOpenIcon())); - } - - @Override - public Enumeration children() { - return v.getNonEmptyElements(); - } + BookmarkFolder ac, diag, dl, it, ic, npc, q, tmx, sp, wm; - @Override - public boolean getAllowsChildren() { - return true; - } + public BookmarksRoot(Project parent) { + this.parent = parent; - @Override - public TreeNode getChildAt(int arg0) { - return v.getNonEmptyElementAt(arg0); - } + v.add(ac = new BookmarkFolder(this, ActorCondition.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); + v.add(diag = new BookmarkFolder(this, Dialogue.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); + v.add(dl = new BookmarkFolder(this, Droplist.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); + v.add(it = new BookmarkFolder(this, Item.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); + v.add(ic = new BookmarkFolder(this, ItemCategory.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); + v.add(npc = new BookmarkFolder(this, NPC.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); + v.add(q = new BookmarkFolder(this, Quest.getStaticDesc(), DefaultIcons.getJsonClosedIcon(), DefaultIcons.getJsonOpenIcon())); - @Override - public int getChildCount() { - return v.getNonEmptySize(); - } + v.add(tmx = new BookmarkFolder(this, "TMX Maps", DefaultIcons.getTmxClosedIcon(), DefaultIcons.getTmxOpenIcon())); + v.add(sp = new BookmarkFolder(this, "Spritesheets", DefaultIcons.getSpriteClosedIcon(), DefaultIcons.getSpriteOpenIcon())); + v.add(wm = new BookmarkFolder(this, "Worldmap", DefaultIcons.getSpriteClosedIcon(), DefaultIcons.getSpriteOpenIcon())); + } - @Override - public int getIndex(TreeNode arg0) { - return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); - } + @Override + public Enumeration children() { + return v.getNonEmptyElements(); + } - @Override - public TreeNode getParent() { - return parent; - } + @Override + public boolean getAllowsChildren() { + return true; + } - @Override - public boolean isLeaf() { - return false; - } + @Override + public TreeNode getChildAt(int arg0) { + return v.getNonEmptyElementAt(arg0); + } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.v.getNonEmptySize() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (ProjectTreeNode node : v.getNonEmptyIterable()) { - node.notifyCreated(); - } - } + @Override + public int getChildCount() { + return v.getNonEmptySize(); + } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+"Bookmarks"; - } + @Override + public int getIndex(TreeNode arg0) { + return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); + } - @Override - public Project getProject() { - return parent == null ? null : parent.getProject(); - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public GameDataSet getDataSet() { - return null; - } + @Override + public boolean isLeaf() { + return false; + } - @Override - public Image getIcon() { - return getOpenIcon(); - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } - @Override - public Image getOpenIcon() { - return DefaultIcons.getBookmarkOpenIcon(); - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } - @Override - public Image getClosedIcon() { - return DefaultIcons.getBookmarkClosedIcon(); - } + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.v.getNonEmptySize() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } - @Override - public Image getLeafIcon() { - return getClosedIcon(); - } + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (ProjectTreeNode node : v.getNonEmptyIterable()) { + node.notifyCreated(); + } + } - @Override - public Type getDataType() { - return null; - } + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + "Bookmarks"; + } - @Override - public boolean isEmpty() { - return v.isEmpty(); - } + @Override + public Project getProject() { + return parent == null ? null : parent.getProject(); + } - @Override - public boolean needsSaving() { - return false; - } - - public void save() { - - } + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getOpenIcon() { + return DefaultIcons.getBookmarkOpenIcon(); + } + + @Override + public Image getClosedIcon() { + return DefaultIcons.getBookmarkClosedIcon(); + } + + @Override + public Image getLeafIcon() { + return getClosedIcon(); + } + + @Override + public Type getDataType() { + return null; + } + + @Override + public boolean isEmpty() { + return v.isEmpty(); + } + + @Override + public boolean needsSaving() { + return false; + } + + public void save() { + + } + + @Override + public void delete() { + } + + public void addBookmark(GameDataElement target) { + BookmarkEntry node; + BookmarkFolder folder; + if (target instanceof ActorCondition) { + folder = ac; + } else if (target instanceof Dialogue) { + folder = diag; + } else if (target instanceof Droplist) { + folder = dl; + } else if (target instanceof Item) { + folder = it; + } else if (target instanceof ItemCategory) { + folder = ic; + } else if (target instanceof NPC) { + folder = npc; + } else if (target instanceof Quest) { + folder = q; + } else if (target instanceof TMXMap) { + folder = tmx; + } else if (target instanceof Spritesheet) { + folder = sp; + } else if (target instanceof WorldmapSegment) { + folder = wm; + } else { + return; + } + ProjectTreeNode higherEmptyParent = folder; + while (higherEmptyParent != null) { + if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty()) + higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent(); + else break; + } + if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; + + node = new BookmarkEntry(folder, target); + if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); + else node.notifyCreated(); + } - @Override - public void delete() {} - - public void addBookmark(GameDataElement target) { - BookmarkEntry node; - BookmarkFolder folder; - if (target instanceof ActorCondition) { - folder = ac; - } else if (target instanceof Dialogue) { - folder = diag; - } else if (target instanceof Droplist) { - folder = dl; - } else if (target instanceof Item) { - folder = it; - } else if (target instanceof ItemCategory) { - folder = ic; - } else if (target instanceof NPC) { - folder = npc; - } else if (target instanceof Quest) { - folder = q; - } else if (target instanceof TMXMap) { - folder = tmx; - } else if (target instanceof Spritesheet) { - folder = sp; - } else if (target instanceof WorldmapSegment) { - folder = wm; - } else { - return; - } - ProjectTreeNode higherEmptyParent = folder; - while (higherEmptyParent != null) { - if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); - else break; - } - if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; - - node = new BookmarkEntry(folder, target); - if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); - else node.notifyCreated(); - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java index 55fac35..e43088f 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java @@ -1,6 +1,12 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -9,364 +15,370 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; - public class ActorCondition extends JSONElement { - - private static final long serialVersionUID = -3969824899972048507L; - public static final Integer MAGNITUDE_CLEAR = -99; - public static final Integer DURATION_FOREVER = 999;; - public static final Integer DURATION_NONE = 0; - - // Available from init state - //public String id; inherited. - public String icon_id; - public String display_name; - public String description; + private static final long serialVersionUID = -3969824899972048507L; - // Available from parsed state - public ACCategory category = null; - public Integer positive = null; - public Integer stacking = null; - public RoundEffect round_effect = null; - public RoundEffect full_round_effect = null; - public AbilityEffect constant_ability_effect = null; - - public enum ACCategory { - spiritual, - mental, - physical, - blood - } - - public static enum VisualEffectID { - redSplash - ,blueSwirl - ,greenSplash - ,miss - } - - public static class RoundEffect implements Cloneable { - // Available from parsed state - public VisualEffectID visual_effect = null; - public Integer hp_boost_min = null; - public Integer hp_boost_max = null; - public Integer ap_boost_min = null; - public Integer ap_boost_max = null; - - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - } - return null; - } - } - - public static class AbilityEffect implements Cloneable { - // Available from parsed state - public Integer max_hp_boost = null; - public Integer max_ap_boost = null; - public Integer increase_move_cost = null; - public Integer increase_use_cost = null; - public Integer increase_reequip_cost = null; - public Integer increase_attack_cost = null; - public Integer increase_attack_chance = null; - public Integer increase_damage_min = null; - public Integer increase_damage_max = null; - public Integer increase_critical_skill = null; - public Integer increase_block_chance = null; - public Integer increase_damage_resistance = null; - - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - e.printStackTrace(); - } - return null; - } - } - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+display_name+" ("+id+")"; - } - - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List actorConditions = (List) parser.parse(reader); - for (Object obj : actorConditions) { - Map aCondJson = (Map)obj; - ActorCondition aCond = fromJson(aCondJson); - aCond.jsonFile = jsonFile; - aCond.parent = category; - if (aCond.getDataType() == GameSource.Type.created || aCond.getDataType() == GameSource.Type.altered) { - aCond.writable = true; - } - category.add(aCond); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static ActorCondition fromJson(String jsonString) throws ParseException { - Map aCondJson = (Map) new JSONParser().parse(jsonString); - ActorCondition aCond = fromJson(aCondJson); - aCond.parse(aCondJson); - return aCond; - } - - @SuppressWarnings("rawtypes") - public static ActorCondition fromJson(Map aCondJson) { - ActorCondition aCond = new ActorCondition(); - aCond.icon_id = (String) aCondJson.get("iconID"); - aCond.id = (String) aCondJson.get("id"); - aCond.display_name = (String) aCondJson.get("name"); - return aCond; - } - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map aCondJson) { + public static final Integer MAGNITUDE_CLEAR = -99; + public static final Integer DURATION_FOREVER = 999; + ; + public static final Integer DURATION_NONE = 0; - if (aCondJson.get("description") != null) this.description = (String) aCondJson.get("description"); - if (aCondJson.get("category") != null) this.category = ACCategory.valueOf((String) aCondJson.get("category")); - this.positive = JSONElement.getInteger((Number) aCondJson.get("isPositive")); - Map abilityEffect = (Map) aCondJson.get("abilityEffect"); - if (abilityEffect != null) { - this.constant_ability_effect = new AbilityEffect(); - this.constant_ability_effect.increase_attack_chance = JSONElement.getInteger((Number) abilityEffect.get("increaseAttackChance")); - if (abilityEffect.get("increaseAttackDamage") != null) { - this.constant_ability_effect.increase_damage_min = JSONElement.getInteger((Number) (((Map)abilityEffect.get("increaseAttackDamage")).get("min"))); - this.constant_ability_effect.increase_damage_max = JSONElement.getInteger((Number) (((Map)abilityEffect.get("increaseAttackDamage")).get("max"))); - } - this.constant_ability_effect.max_hp_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxHP")); - this.constant_ability_effect.max_ap_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxAP")); - this.constant_ability_effect.increase_move_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseMoveCost")); - this.constant_ability_effect.increase_use_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseUseItemCost")); - this.constant_ability_effect.increase_reequip_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseReequipCost")); - this.constant_ability_effect.increase_attack_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseAttackCost")); - this.constant_ability_effect.increase_critical_skill = JSONElement.getInteger((Number) abilityEffect.get("increaseCriticalSkill")); - this.constant_ability_effect.increase_block_chance = JSONElement.getInteger((Number) abilityEffect.get("increaseBlockChance")); - this.constant_ability_effect.increase_damage_resistance = JSONElement.getInteger((Number) abilityEffect.get("increaseDamageResistance")); - } - this.stacking = JSONElement.getInteger((Number) aCondJson.get("isStacking")); - Map roundEffect = (Map) aCondJson.get("roundEffect"); - if (roundEffect != null) { - this.round_effect = new RoundEffect(); - if (roundEffect.get("increaseCurrentHP") != null) { - this.round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentHP")).get("max"))); - this.round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentHP")).get("min"))); - } - if (roundEffect.get("increaseCurrentAP") != null) { - this.round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentAP")).get("max"))); - this.round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)roundEffect.get("increaseCurrentAP")).get("min"))); - } - String vfx = (String) roundEffect.get("visualEffectID"); - this.round_effect.visual_effect = null; - if (vfx != null) { - try { - this.round_effect.visual_effect = VisualEffectID.valueOf(vfx); - } catch(IllegalArgumentException e) {} - } - } - Map fullRoundEffect = (Map) aCondJson.get("fullRoundEffect"); - if (fullRoundEffect != null) { - this.full_round_effect = new RoundEffect(); - if (fullRoundEffect.get("increaseCurrentHP") != null) { - this.full_round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentHP")).get("max"))); - this.full_round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentHP")).get("min"))); - } - if (fullRoundEffect.get("increaseCurrentAP") != null) { - this.full_round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentAP")).get("max"))); - this.full_round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)fullRoundEffect.get("increaseCurrentAP")).get("min"))); - } - String vfx = (String) fullRoundEffect.get("visualEffectID"); - this.full_round_effect.visual_effect = null; - if (vfx != null) { - try { - this.full_round_effect.visual_effect = VisualEffectID.valueOf(vfx); - } catch(IllegalArgumentException e) {} - } - } - this.state = State.parsed; + // Available from init state + //public String id; inherited. + public String icon_id; + public String display_name; + public String description; - } - - @Override - public void link() { - if (!this.linkCheck()) return; - if (this.icon_id != null) { - String spritesheetId = this.icon_id.split(":")[0]; - if (getProject().getSpritesheet(spritesheetId) == null) { - System.out.println("Actor Condition"); - System.out.println(this.id); - System.out.println("failed to load spritesheet:"); - System.out.println(spritesheetId); - System.out.println("while creating backlink for icon_id:"); - System.out.println(this.icon_id); - } - getProject().getSpritesheet(spritesheetId).addBacklink(this); - } - - this.state = State.linked; - } + // Available from parsed state + public ACCategory category = null; + public Integer positive = null; + public Integer stacking = null; + public RoundEffect round_effect = null; + public RoundEffect full_round_effect = null; + public AbilityEffect constant_ability_effect = null; + + public enum ACCategory { + spiritual, + mental, + physical, + blood + } + + public static enum VisualEffectID { + redSplash, blueSwirl, greenSplash, miss + } + + public static class RoundEffect implements Cloneable { + // Available from parsed state + public VisualEffectID visual_effect = null; + public Integer hp_boost_min = null; + public Integer hp_boost_max = null; + public Integer ap_boost_min = null; + public Integer ap_boost_max = null; + + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return null; + } + } + + public static class AbilityEffect implements Cloneable { + // Available from parsed state + public Integer max_hp_boost = null; + public Integer max_ap_boost = null; + public Integer increase_move_cost = null; + public Integer increase_use_cost = null; + public Integer increase_reequip_cost = null; + public Integer increase_attack_cost = null; + public Integer increase_attack_chance = null; + public Integer increase_damage_min = null; + public Integer increase_damage_max = null; + public Integer increase_critical_skill = null; + public Integer increase_block_chance = null; + public Integer increase_damage_resistance = null; + + public Object clone() { + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + e.printStackTrace(); + } + return null; + } + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + display_name + " (" + id + ")"; + } + + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List actorConditions = (List) parser.parse(reader); + for (Object obj : actorConditions) { + Map aCondJson = (Map) obj; + ActorCondition aCond = fromJson(aCondJson); + aCond.jsonFile = jsonFile; + aCond.parent = category; + if (aCond.getDataType() == GameSource.Type.created || aCond.getDataType() == GameSource.Type.altered) { + aCond.writable = true; + } + category.add(aCond); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static ActorCondition fromJson(String jsonString) throws ParseException { + Map aCondJson = (Map) new JSONParser().parse(jsonString); + ActorCondition aCond = fromJson(aCondJson); + aCond.parse(aCondJson); + return aCond; + } + + @SuppressWarnings("rawtypes") + public static ActorCondition fromJson(Map aCondJson) { + ActorCondition aCond = new ActorCondition(); + aCond.icon_id = (String) aCondJson.get("iconID"); + aCond.id = (String) aCondJson.get("id"); + aCond.display_name = (String) aCondJson.get("name"); + return aCond; + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map aCondJson) { + + if (aCondJson.get("description") != null) this.description = (String) aCondJson.get("description"); + if (aCondJson.get("category") != null) this.category = ACCategory.valueOf((String) aCondJson.get("category")); + this.positive = JSONElement.getInteger((Number) aCondJson.get("isPositive")); + Map abilityEffect = (Map) aCondJson.get("abilityEffect"); + if (abilityEffect != null) { + this.constant_ability_effect = new AbilityEffect(); + this.constant_ability_effect.increase_attack_chance = JSONElement.getInteger((Number) abilityEffect.get("increaseAttackChance")); + if (abilityEffect.get("increaseAttackDamage") != null) { + this.constant_ability_effect.increase_damage_min = JSONElement.getInteger((Number) (((Map) abilityEffect.get("increaseAttackDamage")).get("min"))); + this.constant_ability_effect.increase_damage_max = JSONElement.getInteger((Number) (((Map) abilityEffect.get("increaseAttackDamage")).get("max"))); + } + this.constant_ability_effect.max_hp_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxHP")); + this.constant_ability_effect.max_ap_boost = JSONElement.getInteger((Number) abilityEffect.get("increaseMaxAP")); + this.constant_ability_effect.increase_move_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseMoveCost")); + this.constant_ability_effect.increase_use_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseUseItemCost")); + this.constant_ability_effect.increase_reequip_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseReequipCost")); + this.constant_ability_effect.increase_attack_cost = JSONElement.getInteger((Number) abilityEffect.get("increaseAttackCost")); + this.constant_ability_effect.increase_critical_skill = JSONElement.getInteger((Number) abilityEffect.get("increaseCriticalSkill")); + this.constant_ability_effect.increase_block_chance = JSONElement.getInteger((Number) abilityEffect.get("increaseBlockChance")); + this.constant_ability_effect.increase_damage_resistance = JSONElement.getInteger((Number) abilityEffect.get("increaseDamageResistance")); + } + this.stacking = JSONElement.getInteger((Number) aCondJson.get("isStacking")); + Map roundEffect = (Map) aCondJson.get("roundEffect"); + if (roundEffect != null) { + this.round_effect = new RoundEffect(); + if (roundEffect.get("increaseCurrentHP") != null) { + this.round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentHP")).get("max"))); + this.round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentHP")).get("min"))); + } + if (roundEffect.get("increaseCurrentAP") != null) { + this.round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentAP")).get("max"))); + this.round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) roundEffect.get("increaseCurrentAP")).get("min"))); + } + String vfx = (String) roundEffect.get("visualEffectID"); + this.round_effect.visual_effect = null; + if (vfx != null) { + try { + this.round_effect.visual_effect = VisualEffectID.valueOf(vfx); + } catch (IllegalArgumentException e) { + } + } + } + Map fullRoundEffect = (Map) aCondJson.get("fullRoundEffect"); + if (fullRoundEffect != null) { + this.full_round_effect = new RoundEffect(); + if (fullRoundEffect.get("increaseCurrentHP") != null) { + this.full_round_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentHP")).get("max"))); + this.full_round_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentHP")).get("min"))); + } + if (fullRoundEffect.get("increaseCurrentAP") != null) { + this.full_round_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentAP")).get("max"))); + this.full_round_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) fullRoundEffect.get("increaseCurrentAP")).get("min"))); + } + String vfx = (String) fullRoundEffect.get("visualEffectID"); + this.full_round_effect.visual_effect = null; + if (vfx != null) { + try { + this.full_round_effect.visual_effect = VisualEffectID.valueOf(vfx); + } catch (IllegalArgumentException e) { + } + } + } + this.state = State.parsed; + + } + + @Override + public void link() { + if (!this.linkCheck()) return; + if (this.icon_id != null) { + String spritesheetId = this.icon_id.split(":")[0]; + if (getProject().getSpritesheet(spritesheetId) == null) { + System.out.println("Actor Condition"); + System.out.println(this.id); + System.out.println("failed to load spritesheet:"); + System.out.println(spritesheetId); + System.out.println("while creating backlink for icon_id:"); + System.out.println(this.icon_id); + } + getProject().getSpritesheet(spritesheetId).addBacklink(this); + } + + this.state = State.linked; + } + public static String getStaticDesc() { + return "Actor Conditions"; + } - public static String getStaticDesc() { - return "Actor Conditions"; - } - - @Override - public Image getIcon() { - return getProject().getIcon(icon_id); - } - - public Image getImage() { - return getProject().getImage(icon_id); - } - - @Override - public JSONElement clone() { - ActorCondition clone = new ActorCondition(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.display_name = this.display_name; - clone.description = this.description; - clone.icon_id = this.icon_id; - clone.category = this.category; - clone.positive = this.positive; - clone.stacking = this.stacking; - if (this.round_effect != null) { - clone.round_effect = (RoundEffect) this.round_effect.clone(); - } - if (this.constant_ability_effect != null) { - clone.constant_ability_effect = (AbilityEffect) constant_ability_effect.clone(); - } - if (this.full_round_effect != null) { - clone.full_round_effect = (RoundEffect) this.full_round_effect.clone(); - } - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - //Nothing to link to. - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map jsonAC = new LinkedHashMap(); - jsonAC.put("id", this.id); - if (this.icon_id != null) jsonAC.put("iconID", this.icon_id); - if (this.display_name != null) jsonAC.put("name", this.display_name); - if (this.description != null) jsonAC.put("description", this.description); - if (this.category != null) jsonAC.put("category", this.category.toString()); - if (this.positive != null && this.positive == 1) jsonAC.put("isPositive", this.positive); - if (this.stacking != null && this.stacking == 1) jsonAC.put("isStacking", this.stacking); - if (this.round_effect != null) { - Map jsonRound = new LinkedHashMap(); - if (this.round_effect.visual_effect != null) jsonRound.put("visualEffectID", this.round_effect.visual_effect.toString()); - if (this.round_effect.hp_boost_min != null || this.round_effect.hp_boost_max != null) { - Map jsonHP = new LinkedHashMap(); - if (this.round_effect.hp_boost_min != null) jsonHP.put("min", this.round_effect.hp_boost_min); - else jsonHP.put("min", 0); - if (this.round_effect.hp_boost_max != null) jsonHP.put("max", this.round_effect.hp_boost_max); - else jsonHP.put("max", 0); - jsonRound.put("increaseCurrentHP", jsonHP); - } - if (this.round_effect.ap_boost_min != null || this.round_effect.ap_boost_max != null) { - Map jsonAP = new LinkedHashMap(); - if (this.round_effect.ap_boost_min != null) jsonAP.put("min", this.round_effect.ap_boost_min); - else jsonAP.put("min", 0); - if (this.round_effect.ap_boost_max != null) jsonAP.put("max", this.round_effect.ap_boost_max); - else jsonAP.put("max", 0); - jsonRound.put("increaseCurrentAP", jsonAP); - } - jsonAC.put("roundEffect", jsonRound); - } - if (this.full_round_effect != null) { - Map jsonFullRound = new LinkedHashMap(); - if (this.full_round_effect.visual_effect != null) jsonFullRound.put("visualEffectID", this.full_round_effect.visual_effect.toString()); - if (this.full_round_effect.hp_boost_min != null || this.full_round_effect.hp_boost_max != null) { - Map jsonHP = new LinkedHashMap(); - if (this.full_round_effect.hp_boost_min != null) jsonHP.put("min", this.full_round_effect.hp_boost_min); - else jsonHP.put("min", 0); - if (this.full_round_effect.hp_boost_max != null) jsonHP.put("max", this.full_round_effect.hp_boost_max); - else jsonHP.put("max", 0); - jsonFullRound.put("increaseCurrentHP", jsonHP); - } - if (this.full_round_effect.ap_boost_min != null || this.full_round_effect.ap_boost_max != null) { - Map jsonAP = new LinkedHashMap(); - if (this.full_round_effect.ap_boost_min != null) jsonAP.put("min", this.full_round_effect.ap_boost_min); - else jsonAP.put("min", 0); - if (this.full_round_effect.ap_boost_max != null) jsonAP.put("max", this.full_round_effect.ap_boost_max); - else jsonAP.put("max", 0); - jsonFullRound.put("increaseCurrentAP", jsonAP); - } - jsonAC.put("fullRoundEffect", jsonFullRound); - } - if (this.constant_ability_effect != null) { - Map jsonAbility = new LinkedHashMap(); - if (this.constant_ability_effect.increase_attack_chance != null) jsonAbility.put("increaseAttackChance", this.constant_ability_effect.increase_attack_chance); - if (this.constant_ability_effect.increase_damage_min != null || this.constant_ability_effect.increase_damage_max != null) { - Map jsonAD = new LinkedHashMap(); - if (this.constant_ability_effect.increase_damage_min != null) jsonAD.put("min", this.constant_ability_effect.increase_damage_min); - else jsonAD.put("min", 0); - if (this.constant_ability_effect.increase_damage_max != null) jsonAD.put("max", this.constant_ability_effect.increase_damage_max); - else jsonAD.put("max", 0); - jsonAbility.put("increaseAttackDamage", jsonAD); - } - if (this.constant_ability_effect.max_hp_boost != null) jsonAbility.put("increaseMaxHP", this.constant_ability_effect.max_hp_boost); - if (this.constant_ability_effect.max_ap_boost != null) jsonAbility.put("increaseMaxAP", this.constant_ability_effect.max_ap_boost); - if (this.constant_ability_effect.increase_move_cost != null) jsonAbility.put("increaseMoveCost", this.constant_ability_effect.increase_move_cost); - if (this.constant_ability_effect.increase_use_cost != null) jsonAbility.put("increaseUseItemCost", this.constant_ability_effect.increase_use_cost); - if (this.constant_ability_effect.increase_reequip_cost != null) jsonAbility.put("increaseReequipCost", this.constant_ability_effect.increase_reequip_cost); - if (this.constant_ability_effect.increase_attack_cost != null) jsonAbility.put("increaseAttackCost", this.constant_ability_effect.increase_attack_cost); - if (this.constant_ability_effect.increase_critical_skill != null) jsonAbility.put("increaseCriticalSkill", this.constant_ability_effect.increase_critical_skill); - if (this.constant_ability_effect.increase_block_chance != null) jsonAbility.put("increaseBlockChance", this.constant_ability_effect.increase_block_chance); - if (this.constant_ability_effect.increase_damage_resistance != null) jsonAbility.put("increaseDamageResistance", this.constant_ability_effect.increase_damage_resistance); - jsonAC.put("abilityEffect", jsonAbility); - } - return jsonAC; - } + @Override + public Image getIcon() { + return getProject().getIcon(icon_id); + } + + public Image getImage() { + return getProject().getImage(icon_id); + } + + @Override + public JSONElement clone() { + ActorCondition clone = new ActorCondition(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.display_name = this.display_name; + clone.description = this.description; + clone.icon_id = this.icon_id; + clone.category = this.category; + clone.positive = this.positive; + clone.stacking = this.stacking; + if (this.round_effect != null) { + clone.round_effect = (RoundEffect) this.round_effect.clone(); + } + if (this.constant_ability_effect != null) { + clone.constant_ability_effect = (AbilityEffect) constant_ability_effect.clone(); + } + if (this.full_round_effect != null) { + clone.full_round_effect = (RoundEffect) this.full_round_effect.clone(); + } + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + //Nothing to link to. + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map jsonAC = new LinkedHashMap(); + jsonAC.put("id", this.id); + if (this.icon_id != null) jsonAC.put("iconID", this.icon_id); + if (this.display_name != null) jsonAC.put("name", this.display_name); + if (this.description != null) jsonAC.put("description", this.description); + if (this.category != null) jsonAC.put("category", this.category.toString()); + if (this.positive != null && this.positive == 1) jsonAC.put("isPositive", this.positive); + if (this.stacking != null && this.stacking == 1) jsonAC.put("isStacking", this.stacking); + if (this.round_effect != null) { + Map jsonRound = new LinkedHashMap(); + if (this.round_effect.visual_effect != null) + jsonRound.put("visualEffectID", this.round_effect.visual_effect.toString()); + if (this.round_effect.hp_boost_min != null || this.round_effect.hp_boost_max != null) { + Map jsonHP = new LinkedHashMap(); + if (this.round_effect.hp_boost_min != null) jsonHP.put("min", this.round_effect.hp_boost_min); + else jsonHP.put("min", 0); + if (this.round_effect.hp_boost_max != null) jsonHP.put("max", this.round_effect.hp_boost_max); + else jsonHP.put("max", 0); + jsonRound.put("increaseCurrentHP", jsonHP); + } + if (this.round_effect.ap_boost_min != null || this.round_effect.ap_boost_max != null) { + Map jsonAP = new LinkedHashMap(); + if (this.round_effect.ap_boost_min != null) jsonAP.put("min", this.round_effect.ap_boost_min); + else jsonAP.put("min", 0); + if (this.round_effect.ap_boost_max != null) jsonAP.put("max", this.round_effect.ap_boost_max); + else jsonAP.put("max", 0); + jsonRound.put("increaseCurrentAP", jsonAP); + } + jsonAC.put("roundEffect", jsonRound); + } + if (this.full_round_effect != null) { + Map jsonFullRound = new LinkedHashMap(); + if (this.full_round_effect.visual_effect != null) + jsonFullRound.put("visualEffectID", this.full_round_effect.visual_effect.toString()); + if (this.full_round_effect.hp_boost_min != null || this.full_round_effect.hp_boost_max != null) { + Map jsonHP = new LinkedHashMap(); + if (this.full_round_effect.hp_boost_min != null) jsonHP.put("min", this.full_round_effect.hp_boost_min); + else jsonHP.put("min", 0); + if (this.full_round_effect.hp_boost_max != null) jsonHP.put("max", this.full_round_effect.hp_boost_max); + else jsonHP.put("max", 0); + jsonFullRound.put("increaseCurrentHP", jsonHP); + } + if (this.full_round_effect.ap_boost_min != null || this.full_round_effect.ap_boost_max != null) { + Map jsonAP = new LinkedHashMap(); + if (this.full_round_effect.ap_boost_min != null) jsonAP.put("min", this.full_round_effect.ap_boost_min); + else jsonAP.put("min", 0); + if (this.full_round_effect.ap_boost_max != null) jsonAP.put("max", this.full_round_effect.ap_boost_max); + else jsonAP.put("max", 0); + jsonFullRound.put("increaseCurrentAP", jsonAP); + } + jsonAC.put("fullRoundEffect", jsonFullRound); + } + if (this.constant_ability_effect != null) { + Map jsonAbility = new LinkedHashMap(); + if (this.constant_ability_effect.increase_attack_chance != null) + jsonAbility.put("increaseAttackChance", this.constant_ability_effect.increase_attack_chance); + if (this.constant_ability_effect.increase_damage_min != null || this.constant_ability_effect.increase_damage_max != null) { + Map jsonAD = new LinkedHashMap(); + if (this.constant_ability_effect.increase_damage_min != null) + jsonAD.put("min", this.constant_ability_effect.increase_damage_min); + else jsonAD.put("min", 0); + if (this.constant_ability_effect.increase_damage_max != null) + jsonAD.put("max", this.constant_ability_effect.increase_damage_max); + else jsonAD.put("max", 0); + jsonAbility.put("increaseAttackDamage", jsonAD); + } + if (this.constant_ability_effect.max_hp_boost != null) + jsonAbility.put("increaseMaxHP", this.constant_ability_effect.max_hp_boost); + if (this.constant_ability_effect.max_ap_boost != null) + jsonAbility.put("increaseMaxAP", this.constant_ability_effect.max_ap_boost); + if (this.constant_ability_effect.increase_move_cost != null) + jsonAbility.put("increaseMoveCost", this.constant_ability_effect.increase_move_cost); + if (this.constant_ability_effect.increase_use_cost != null) + jsonAbility.put("increaseUseItemCost", this.constant_ability_effect.increase_use_cost); + if (this.constant_ability_effect.increase_reequip_cost != null) + jsonAbility.put("increaseReequipCost", this.constant_ability_effect.increase_reequip_cost); + if (this.constant_ability_effect.increase_attack_cost != null) + jsonAbility.put("increaseAttackCost", this.constant_ability_effect.increase_attack_cost); + if (this.constant_ability_effect.increase_critical_skill != null) + jsonAbility.put("increaseCriticalSkill", this.constant_ability_effect.increase_critical_skill); + if (this.constant_ability_effect.increase_block_chance != null) + jsonAbility.put("increaseBlockChance", this.constant_ability_effect.increase_block_chance); + if (this.constant_ability_effect.increase_damage_resistance != null) + jsonAbility.put("increaseDamageResistance", this.constant_ability_effect.increase_damage_resistance); + jsonAC.put("abilityEffect", jsonAbility); + } + return jsonAC; + } + + @Override + public String getProjectFilename() { + return "actorconditions_" + getProject().name + ".json"; + } - @Override - public String getProjectFilename() { - return "actorconditions_"+getProject().name+".json"; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 2a8b305..0c58eea 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -9,7 +9,7 @@ import java.util.Map; public final class Common { - public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { + public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { if (conditions != null) { for (ConditionEffect ce : conditions) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); @@ -17,6 +17,7 @@ public final class Common { } } } + public static class TimedConditionEffect extends ConditionEffect { //Available from parsed state public Integer duration = null; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java index 75c9a62..d3e17c7 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java @@ -1,19 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; @@ -21,440 +7,452 @@ import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement.RequirementType; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.List; +import java.util.*; public class Dialogue extends JSONElement { - private static final long serialVersionUID = -6872164604703134683L; - - - //Available from init state - //public String id = null; inherited. - public String message = null; - - //Available from parsed state; - public List rewards = null; - public List replies = null; - public String switch_to_npc_id = null; - - //Available from linked state; - public NPC switch_to_npc = null; - - public static class Reward { - - //Available from parsed state - public RewardType type = null; - public String reward_obj_id = null; - public Integer reward_value = null; - public String map_name = null; - - //Available from linked state - public GameDataElement reward_obj = null; - public TMXMap map = null; - - public enum RewardType { - questProgress, - removeQuestProgress, - dropList, - skillIncrease, - actorCondition, - actorConditionImmunity, - alignmentChange, - alignmentSet, - giveItem, - createTimer, - spawnAll, - removeSpawnArea, - deactivateSpawnArea, - activateMapObjectGroup, - deactivateMapObjectGroup, - changeMapFilter, - mapchange - } - } - - public static class Reply { - - public static final String GO_NEXT_TEXT = "N"; - public static final String SHOP_PHRASE_ID = "S"; - public static final String FIGHT_PHRASE_ID = "F"; - public static final String EXIT_PHRASE_ID = "X"; - public static final String REMOVE_PHRASE_ID = "R"; - - public static final List KEY_PHRASE_ID = Arrays.asList(new String[]{SHOP_PHRASE_ID, FIGHT_PHRASE_ID, EXIT_PHRASE_ID, REMOVE_PHRASE_ID}); - - //Available from parsed state - public String text = null; - public String next_phrase_id = null; - public List requirements = null; - - //Available from linked state - public Dialogue next_phrase = null; - - } - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+id; - } - - public static String getStaticDesc() { - return "Dialogues"; - } - - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List dialogues = (List) parser.parse(reader); - for (Object obj : dialogues) { - Map dialogueJson = (Map)obj; - Dialogue dialogue = fromJson(dialogueJson); - dialogue.jsonFile = jsonFile; - dialogue.parent = category; - if (dialogue.getDataType() == GameSource.Type.created || dialogue.getDataType() == GameSource.Type.altered) { - dialogue.writable = true; - } - category.add(dialogue); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static Dialogue fromJson(String jsonString) throws ParseException { - Map dialogueJson = (Map) new JSONParser().parse(jsonString); - Dialogue dialogue = fromJson(dialogueJson); - dialogue.parse(dialogueJson); - return dialogue; - } - - @SuppressWarnings("rawtypes") - public static Dialogue fromJson(Map dialogueJson) { - Dialogue dialogue = new Dialogue(); - dialogue.id = (String) dialogueJson.get("id"); - dialogue.message = (String) dialogueJson.get("message"); - return dialogue; - } - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map dialogueJson) { - this.switch_to_npc_id = (String) dialogueJson.get("switchToNPC"); - List repliesJson = (List) dialogueJson.get("replies"); - if (repliesJson != null && !repliesJson.isEmpty()) { - this.replies = new ArrayList(); - for (Object replyJsonObj : repliesJson) { - Map replyJson = (Map)replyJsonObj; - Reply reply = new Reply(); - reply.text = (String) replyJson.get("text"); - reply.next_phrase_id = (String) replyJson.get("nextPhraseID"); - List requirementsJson = (List) replyJson.get("requires"); - if (requirementsJson != null && !requirementsJson.isEmpty()) { - reply.requirements = new ArrayList(); - for (Object requirementJsonObj : requirementsJson) { - Map requirementJson = (Map) requirementJsonObj; - Requirement requirement = new Requirement(); - requirement.jsonFile = this.jsonFile; - requirement.parent = this; - if (requirementJson.get("requireType") != null) requirement.type = RequirementType.valueOf((String) requirementJson.get("requireType")); - requirement.required_obj_id = (String) requirementJson.get("requireID"); - if (requirementJson.get("value") != null) requirement.required_value = JSONElement.getInteger(Integer.parseInt(requirementJson.get("value").toString())); - if (requirementJson.get("negate") != null) requirement.negated = (Boolean) requirementJson.get("negate"); - requirement.state = State.parsed; - reply.requirements.add(requirement); - } - } - this.replies.add(reply); - } - } - List rewardsJson = (List) dialogueJson.get("rewards"); - if (rewardsJson != null && !rewardsJson.isEmpty()) { - this.rewards = new ArrayList(); - for (Object rewardJsonObj : rewardsJson) { - Map rewardJson = (Map)rewardJsonObj; - Reward reward = new Reward(); - if (rewardJson.get("rewardType") != null) reward.type = Reward.RewardType.valueOf((String) rewardJson.get("rewardType")); - if (rewardJson.get("rewardID") != null) reward.reward_obj_id = (String) rewardJson.get("rewardID"); - if (rewardJson.get("value") != null) reward.reward_value = JSONElement.getInteger((Number) rewardJson.get("value")); - if (rewardJson.get("mapName") != null) reward.map_name = (String) rewardJson.get("mapName"); - this.rewards.add(reward); - } - } - this.state = State.parsed; - } - - - - - @Override - public void link() { - if (!this.linkCheck()) return; - Project proj = getProject(); - if (proj == null) { - Notification.addError("Error linking dialogue "+id+". No parent project found."); - return; - } - if (this.switch_to_npc_id != null) this.switch_to_npc = proj.getNPC(this.switch_to_npc_id); - if (this.switch_to_npc != null) this.switch_to_npc.addBacklink(this); - - if (replies != null) { - for (Reply reply : replies) { - if (reply.next_phrase_id != null) { - if (!Reply.KEY_PHRASE_ID.contains(reply.next_phrase_id)) { - reply.next_phrase = proj.getDialogue(reply.next_phrase_id); - } - } - if (reply.next_phrase != null) reply.next_phrase.addBacklink(this); - if (reply.requirements != null) { - for (Requirement requirement : reply.requirements) { - requirement.link(); - } - } - } - } - if (rewards != null) { - for (Reward reward : rewards) { - if (reward.reward_obj_id != null) { - switch (reward.type) { - case activateMapObjectGroup: - case deactivateMapObjectGroup: - case spawnAll: - case removeSpawnArea: - case deactivateSpawnArea: - case changeMapFilter: - case mapchange: - reward.map = reward.map_name != null ? proj.getMap(reward.map_name) : null; - break; - case actorCondition: - case actorConditionImmunity: - reward.reward_obj = proj.getActorCondition(reward.reward_obj_id); - break; - case alignmentChange: - case alignmentSet: - //Nothing to do (yet ?). - break; - case createTimer: - //Nothing to do. - break; - case dropList: - reward.reward_obj = proj.getDroplist(reward.reward_obj_id); - break; - case giveItem: - reward.reward_obj = proj.getItem(reward.reward_obj_id); - break; - case questProgress: - case removeQuestProgress: - reward.reward_obj = proj.getQuest(reward.reward_obj_id); - if (reward.reward_obj != null && reward.reward_value != null) { - QuestStage stage = ((Quest)reward.reward_obj).getStage(reward.reward_value); - if (stage != null) { - stage.addBacklink(this); - } - } - break; - case skillIncrease: - //Nothing to do (yet ?). - break; - } - if (reward.reward_obj != null) reward.reward_obj.addBacklink(this); - if (reward.map != null) reward.map.addBacklink(this); - } - } - } - - this.state = State.linked; - } - + private static final long serialVersionUID = -6872164604703134683L; - @Override - public Image getIcon() { - return DefaultIcons.getDialogueIcon(); - } - + //Available from init state + //public String id = null; inherited. + public String message = null; - public Image getImage() { - return DefaultIcons.getDialogueImage(); - } - - @Override - public GameDataElement clone() { - Dialogue clone = new Dialogue(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.message = this.message; - clone.switch_to_npc_id = this.switch_to_npc_id; - clone.switch_to_npc = this.switch_to_npc; - if (clone.switch_to_npc != null) { - clone.switch_to_npc.addBacklink(clone); - } - if (this.rewards != null) { - clone.rewards = new ArrayList(); - for (Reward r : this.rewards) { - Reward rclone = new Reward(); - rclone.type = r.type; - rclone.reward_obj_id = r.reward_obj_id; - rclone.reward_value = r.reward_value; - rclone.reward_obj = r.reward_obj; - if (rclone.reward_obj != null) { - rclone.reward_obj.addBacklink(clone); - } - rclone.map = r.map; - rclone.map_name = r.map_name; - if (rclone.map != null) { - rclone.map.addBacklink(clone); - } - clone.rewards.add(rclone); - } - } - if (this.replies != null) { - clone.replies = new ArrayList(); - for (Reply r : this.replies) { - Reply rclone = new Reply(); - rclone.text = r.text; - rclone.next_phrase_id = r.next_phrase_id; - rclone.next_phrase = r.next_phrase; - if (rclone.next_phrase != null) { - rclone.next_phrase.addBacklink(clone); - } - if (r.requirements != null) { - rclone.requirements = new ArrayList(); - for (Requirement req : r.requirements) { - //Special clone method, as Requirement is a special GDE, hidden from the project tree. - rclone.requirements.add((Requirement) req.clone(clone)); - } - } - clone.replies.add(rclone); - } - } - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (switch_to_npc == oldOne) { - oldOne.removeBacklink(this); - switch_to_npc = (NPC) newOne; - if (newOne != null) newOne.addBacklink(this); - } else { - if (replies != null) { - for (Reply r : replies) { - if (r.next_phrase == oldOne) { - oldOne.removeBacklink(this); - r.next_phrase = (Dialogue) newOne; - if (newOne != null) newOne.addBacklink(this); - } - if (r.requirements != null) { - for (Requirement req : r.requirements) { - req.elementChanged(oldOne, newOne); - } - } - } - } - if (rewards != null) { - for (Reward r : rewards) { - if (r.reward_obj == oldOne) { - oldOne.removeBacklink(this); - r.reward_obj = newOne; - if (newOne != null) newOne.addBacklink(this); - } - if (oldOne instanceof QuestStage) { - if (r.reward_obj != null && r.reward_obj.equals(oldOne.parent) && r.reward_value != null && r.reward_value.equals(((QuestStage) oldOne).progress)) { - oldOne.removeBacklink((GameDataElement) this); - if (newOne != null) newOne.addBacklink((GameDataElement) this); - } - } - } - } - } - } + //Available from parsed state; + public List rewards = null; + public List replies = null; + public String switch_to_npc_id = null; - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map dialogueJson = new LinkedHashMap(); - dialogueJson.put("id", this.id); - if (this.message != null) dialogueJson.put("message", this.message); - if (this.switch_to_npc != null) { - dialogueJson.put("switchToNPC", this.switch_to_npc.id); - } else if (this.switch_to_npc_id != null) { - dialogueJson.put("switchToNPC", this.switch_to_npc_id); - } - if (this.replies != null) { - List repliesJson = new ArrayList(); - dialogueJson.put("replies", repliesJson); - for (Reply reply : this.replies){ - Map replyJson = new LinkedHashMap(); - repliesJson.add(replyJson); - if (reply.text != null) replyJson.put("text", reply.text); - if (reply.next_phrase != null) { - replyJson.put("nextPhraseID", reply.next_phrase.id); - } else if (reply.next_phrase_id != null) { - replyJson.put("nextPhraseID", reply.next_phrase_id); - } - if (reply.requirements != null) { - List requirementsJson = new ArrayList(); - replyJson.put("requires", requirementsJson); - for (Requirement requirement : reply.requirements) { - Map requirementJson = new LinkedHashMap(); - requirementsJson.add(requirementJson); - if (requirement.type != null) requirementJson.put("requireType", requirement.type.toString()); - if (requirement.required_obj != null) { - requirementJson.put("requireID", requirement.required_obj.id); - } else if (requirement.required_obj_id != null) { - requirementJson.put("requireID", requirement.required_obj_id); - } - if (requirement.required_value != null) { - requirementJson.put("value", requirement.required_value); - } - if (requirement.negated != null) requirementJson.put("negate", requirement.negated); - } - } - } - } - if (this.rewards != null) { - List rewardsJson = new ArrayList(); - dialogueJson.put("rewards", rewardsJson); - for (Reward reward : this.rewards) { - Map rewardJson = new LinkedHashMap(); - rewardsJson.add(rewardJson); - if (reward.type != null) rewardJson.put("rewardType", reward.type.toString()); - if (reward.reward_obj != null) { - rewardJson.put("rewardID", reward.reward_obj.id); - } else if (reward.reward_obj_id != null) { - rewardJson.put("rewardID", reward.reward_obj_id); - } - if (reward.reward_value != null) rewardJson.put("value", reward.reward_value); - if (reward.map != null) { - rewardJson.put("mapName", reward.map.id); - } else if (reward.map_name != null) rewardJson.put("mapName", reward.map_name); - } - } - return dialogueJson; - } + //Available from linked state; + public NPC switch_to_npc = null; + + public static class Reward { + + //Available from parsed state + public RewardType type = null; + public String reward_obj_id = null; + public Integer reward_value = null; + public String map_name = null; + + //Available from linked state + public GameDataElement reward_obj = null; + public TMXMap map = null; + + public enum RewardType { + questProgress, + removeQuestProgress, + dropList, + skillIncrease, + actorCondition, + actorConditionImmunity, + alignmentChange, + alignmentSet, + giveItem, + createTimer, + spawnAll, + removeSpawnArea, + deactivateSpawnArea, + activateMapObjectGroup, + deactivateMapObjectGroup, + changeMapFilter, + mapchange + } + } + + public static class Reply { + + public static final String GO_NEXT_TEXT = "N"; + public static final String SHOP_PHRASE_ID = "S"; + public static final String FIGHT_PHRASE_ID = "F"; + public static final String EXIT_PHRASE_ID = "X"; + public static final String REMOVE_PHRASE_ID = "R"; + + public static final List KEY_PHRASE_ID = Arrays.asList(new String[]{SHOP_PHRASE_ID, FIGHT_PHRASE_ID, EXIT_PHRASE_ID, REMOVE_PHRASE_ID}); + + //Available from parsed state + public String text = null; + public String next_phrase_id = null; + public List requirements = null; + + //Available from linked state + public Dialogue next_phrase = null; + + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + id; + } + + public static String getStaticDesc() { + return "Dialogues"; + } + + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List dialogues = (List) parser.parse(reader); + for (Object obj : dialogues) { + Map dialogueJson = (Map) obj; + Dialogue dialogue = fromJson(dialogueJson); + dialogue.jsonFile = jsonFile; + dialogue.parent = category; + if (dialogue.getDataType() == GameSource.Type.created || dialogue.getDataType() == GameSource.Type.altered) { + dialogue.writable = true; + } + category.add(dialogue); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static Dialogue fromJson(String jsonString) throws ParseException { + Map dialogueJson = (Map) new JSONParser().parse(jsonString); + Dialogue dialogue = fromJson(dialogueJson); + dialogue.parse(dialogueJson); + return dialogue; + } + + @SuppressWarnings("rawtypes") + public static Dialogue fromJson(Map dialogueJson) { + Dialogue dialogue = new Dialogue(); + dialogue.id = (String) dialogueJson.get("id"); + dialogue.message = (String) dialogueJson.get("message"); + return dialogue; + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map dialogueJson) { + this.switch_to_npc_id = (String) dialogueJson.get("switchToNPC"); + List repliesJson = (List) dialogueJson.get("replies"); + if (repliesJson != null && !repliesJson.isEmpty()) { + this.replies = new ArrayList(); + for (Object replyJsonObj : repliesJson) { + Map replyJson = (Map) replyJsonObj; + Reply reply = new Reply(); + reply.text = (String) replyJson.get("text"); + reply.next_phrase_id = (String) replyJson.get("nextPhraseID"); + List requirementsJson = (List) replyJson.get("requires"); + if (requirementsJson != null && !requirementsJson.isEmpty()) { + reply.requirements = new ArrayList(); + for (Object requirementJsonObj : requirementsJson) { + Map requirementJson = (Map) requirementJsonObj; + Requirement requirement = new Requirement(); + requirement.jsonFile = this.jsonFile; + requirement.parent = this; + if (requirementJson.get("requireType") != null) + requirement.type = RequirementType.valueOf((String) requirementJson.get("requireType")); + requirement.required_obj_id = (String) requirementJson.get("requireID"); + if (requirementJson.get("value") != null) + requirement.required_value = JSONElement.getInteger(Integer.parseInt(requirementJson.get("value").toString())); + if (requirementJson.get("negate") != null) + requirement.negated = (Boolean) requirementJson.get("negate"); + requirement.state = State.parsed; + reply.requirements.add(requirement); + } + } + this.replies.add(reply); + } + } + List rewardsJson = (List) dialogueJson.get("rewards"); + if (rewardsJson != null && !rewardsJson.isEmpty()) { + this.rewards = new ArrayList(); + for (Object rewardJsonObj : rewardsJson) { + Map rewardJson = (Map) rewardJsonObj; + Reward reward = new Reward(); + if (rewardJson.get("rewardType") != null) + reward.type = Reward.RewardType.valueOf((String) rewardJson.get("rewardType")); + if (rewardJson.get("rewardID") != null) reward.reward_obj_id = (String) rewardJson.get("rewardID"); + if (rewardJson.get("value") != null) + reward.reward_value = JSONElement.getInteger((Number) rewardJson.get("value")); + if (rewardJson.get("mapName") != null) reward.map_name = (String) rewardJson.get("mapName"); + this.rewards.add(reward); + } + } + this.state = State.parsed; + } + + + @Override + public void link() { + if (!this.linkCheck()) return; + Project proj = getProject(); + if (proj == null) { + Notification.addError("Error linking dialogue " + id + ". No parent project found."); + return; + } + if (this.switch_to_npc_id != null) this.switch_to_npc = proj.getNPC(this.switch_to_npc_id); + if (this.switch_to_npc != null) this.switch_to_npc.addBacklink(this); + + if (replies != null) { + for (Reply reply : replies) { + if (reply.next_phrase_id != null) { + if (!Reply.KEY_PHRASE_ID.contains(reply.next_phrase_id)) { + reply.next_phrase = proj.getDialogue(reply.next_phrase_id); + } + } + if (reply.next_phrase != null) reply.next_phrase.addBacklink(this); + if (reply.requirements != null) { + for (Requirement requirement : reply.requirements) { + requirement.link(); + } + } + } + } + if (rewards != null) { + for (Reward reward : rewards) { + if (reward.reward_obj_id != null) { + switch (reward.type) { + case activateMapObjectGroup: + case deactivateMapObjectGroup: + case spawnAll: + case removeSpawnArea: + case deactivateSpawnArea: + case changeMapFilter: + case mapchange: + reward.map = reward.map_name != null ? proj.getMap(reward.map_name) : null; + break; + case actorCondition: + case actorConditionImmunity: + reward.reward_obj = proj.getActorCondition(reward.reward_obj_id); + break; + case alignmentChange: + case alignmentSet: + //Nothing to do (yet ?). + break; + case createTimer: + //Nothing to do. + break; + case dropList: + reward.reward_obj = proj.getDroplist(reward.reward_obj_id); + break; + case giveItem: + reward.reward_obj = proj.getItem(reward.reward_obj_id); + break; + case questProgress: + case removeQuestProgress: + reward.reward_obj = proj.getQuest(reward.reward_obj_id); + if (reward.reward_obj != null && reward.reward_value != null) { + QuestStage stage = ((Quest) reward.reward_obj).getStage(reward.reward_value); + if (stage != null) { + stage.addBacklink(this); + } + } + break; + case skillIncrease: + //Nothing to do (yet ?). + break; + } + if (reward.reward_obj != null) reward.reward_obj.addBacklink(this); + if (reward.map != null) reward.map.addBacklink(this); + } + } + } + + this.state = State.linked; + } + + + @Override + public Image getIcon() { + return DefaultIcons.getDialogueIcon(); + } + + + public Image getImage() { + return DefaultIcons.getDialogueImage(); + } + + @Override + public GameDataElement clone() { + Dialogue clone = new Dialogue(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.message = this.message; + clone.switch_to_npc_id = this.switch_to_npc_id; + clone.switch_to_npc = this.switch_to_npc; + if (clone.switch_to_npc != null) { + clone.switch_to_npc.addBacklink(clone); + } + if (this.rewards != null) { + clone.rewards = new ArrayList(); + for (Reward r : this.rewards) { + Reward rclone = new Reward(); + rclone.type = r.type; + rclone.reward_obj_id = r.reward_obj_id; + rclone.reward_value = r.reward_value; + rclone.reward_obj = r.reward_obj; + if (rclone.reward_obj != null) { + rclone.reward_obj.addBacklink(clone); + } + rclone.map = r.map; + rclone.map_name = r.map_name; + if (rclone.map != null) { + rclone.map.addBacklink(clone); + } + clone.rewards.add(rclone); + } + } + if (this.replies != null) { + clone.replies = new ArrayList(); + for (Reply r : this.replies) { + Reply rclone = new Reply(); + rclone.text = r.text; + rclone.next_phrase_id = r.next_phrase_id; + rclone.next_phrase = r.next_phrase; + if (rclone.next_phrase != null) { + rclone.next_phrase.addBacklink(clone); + } + if (r.requirements != null) { + rclone.requirements = new ArrayList(); + for (Requirement req : r.requirements) { + //Special clone method, as Requirement is a special GDE, hidden from the project tree. + rclone.requirements.add((Requirement) req.clone(clone)); + } + } + clone.replies.add(rclone); + } + } + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (switch_to_npc == oldOne) { + oldOne.removeBacklink(this); + switch_to_npc = (NPC) newOne; + if (newOne != null) newOne.addBacklink(this); + } else { + if (replies != null) { + for (Reply r : replies) { + if (r.next_phrase == oldOne) { + oldOne.removeBacklink(this); + r.next_phrase = (Dialogue) newOne; + if (newOne != null) newOne.addBacklink(this); + } + if (r.requirements != null) { + for (Requirement req : r.requirements) { + req.elementChanged(oldOne, newOne); + } + } + } + } + if (rewards != null) { + for (Reward r : rewards) { + if (r.reward_obj == oldOne) { + oldOne.removeBacklink(this); + r.reward_obj = newOne; + if (newOne != null) newOne.addBacklink(this); + } + if (oldOne instanceof QuestStage) { + if (r.reward_obj != null && r.reward_obj.equals(oldOne.parent) && r.reward_value != null && r.reward_value.equals(((QuestStage) oldOne).progress)) { + oldOne.removeBacklink((GameDataElement) this); + if (newOne != null) newOne.addBacklink((GameDataElement) this); + } + } + } + } + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map dialogueJson = new LinkedHashMap(); + dialogueJson.put("id", this.id); + if (this.message != null) dialogueJson.put("message", this.message); + if (this.switch_to_npc != null) { + dialogueJson.put("switchToNPC", this.switch_to_npc.id); + } else if (this.switch_to_npc_id != null) { + dialogueJson.put("switchToNPC", this.switch_to_npc_id); + } + if (this.replies != null) { + List repliesJson = new ArrayList(); + dialogueJson.put("replies", repliesJson); + for (Reply reply : this.replies) { + Map replyJson = new LinkedHashMap(); + repliesJson.add(replyJson); + if (reply.text != null) replyJson.put("text", reply.text); + if (reply.next_phrase != null) { + replyJson.put("nextPhraseID", reply.next_phrase.id); + } else if (reply.next_phrase_id != null) { + replyJson.put("nextPhraseID", reply.next_phrase_id); + } + if (reply.requirements != null) { + List requirementsJson = new ArrayList(); + replyJson.put("requires", requirementsJson); + for (Requirement requirement : reply.requirements) { + Map requirementJson = new LinkedHashMap(); + requirementsJson.add(requirementJson); + if (requirement.type != null) requirementJson.put("requireType", requirement.type.toString()); + if (requirement.required_obj != null) { + requirementJson.put("requireID", requirement.required_obj.id); + } else if (requirement.required_obj_id != null) { + requirementJson.put("requireID", requirement.required_obj_id); + } + if (requirement.required_value != null) { + requirementJson.put("value", requirement.required_value); + } + if (requirement.negated != null) requirementJson.put("negate", requirement.negated); + } + } + } + } + if (this.rewards != null) { + List rewardsJson = new ArrayList(); + dialogueJson.put("rewards", rewardsJson); + for (Reward reward : this.rewards) { + Map rewardJson = new LinkedHashMap(); + rewardsJson.add(rewardJson); + if (reward.type != null) rewardJson.put("rewardType", reward.type.toString()); + if (reward.reward_obj != null) { + rewardJson.put("rewardID", reward.reward_obj.id); + } else if (reward.reward_obj_id != null) { + rewardJson.put("rewardID", reward.reward_obj_id); + } + if (reward.reward_value != null) rewardJson.put("value", reward.reward_value); + if (reward.map != null) { + rewardJson.put("mapName", reward.map.id); + } else if (reward.map_name != null) rewardJson.put("mapName", reward.map_name); + } + } + return dialogueJson; + } + + @Override + public String getProjectFilename() { + return "conversationlist_" + getProject().name + ".json"; + } - @Override - public String getProjectFilename() { - return "conversationlist_"+getProject().name+".json"; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java index 0ae34a0..c835ee5 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java @@ -1,6 +1,14 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -10,223 +18,213 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; - public class Droplist extends JSONElement { - private static final long serialVersionUID = -2903944916807382571L; - - //Available from init state - //public String id = null; inherited. + private static final long serialVersionUID = -2903944916807382571L; - //Available from parsed state; - public List dropped_items = null; - - //Available from linked state; - //None - - public static class DroppedItem { - //Available from parsed state; - public String item_id = null; - public String chance = null; - public Integer quantity_min = null; - public Integer quantity_max = null; - - //Available from linked state; - public Item item = null; - } - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+id; - } + //Available from init state + //public String id = null; inherited. - public static String getStaticDesc() { - return "Droplists"; - } + //Available from parsed state; + public List dropped_items = null; - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List droplists = (List) parser.parse(reader); - for (Object obj : droplists) { - Map droplistJson = (Map)obj; - Droplist droplist = fromJson(droplistJson); - droplist.jsonFile = jsonFile; - droplist.parent = category; - if (droplist.getDataType() == GameSource.Type.created || droplist.getDataType() == GameSource.Type.altered) { - droplist.writable = true; - } - category.add(droplist); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static Droplist fromJson(String jsonString) throws ParseException { - Map droplistJson = (Map) new JSONParser().parse(jsonString); - Droplist droplist = fromJson(droplistJson); - droplist.parse(droplistJson); - return droplist; - } - - @SuppressWarnings("rawtypes") - public static Droplist fromJson(Map droplistJson) { - Droplist droplist = new Droplist(); - droplist.id = (String) droplistJson.get("id"); - return droplist; - } - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map droplistJson) { - List droppedItemsJson = (List) droplistJson.get("items"); - if (droppedItemsJson != null && !droppedItemsJson.isEmpty()) { - this.dropped_items = new ArrayList(); - for (Object droppedItemJsonObj : droppedItemsJson) { - Map droppedItemJson = (Map)droppedItemJsonObj; - DroppedItem droppedItem = new DroppedItem(); - droppedItem.item_id = (String) droppedItemJson.get("itemID"); - //if (droppedItemJson.get("chance") != null) droppedItem.chance = JSONElement.parseChance(droppedItemJson.get("chance").toString()); - droppedItem.chance = (String) droppedItemJson.get("chance"); - Map droppedItemQtyJson = (Map) droppedItemJson.get("quantity"); - if (droppedItemQtyJson != null) { - droppedItem.quantity_min = JSONElement.getInteger((Number) droppedItemQtyJson.get("min")); - droppedItem.quantity_max = JSONElement.getInteger((Number) droppedItemQtyJson.get("max")); - } - this.dropped_items.add(droppedItem); - } - } - this.state = State.parsed; - } - - @Override - public void link() { - if (!this.linkCheck()) return; - Project proj = getProject(); - if (proj == null) { - Notification.addError("Error linking droplist "+id+". No parent project found."); - return; - } - if (dropped_items != null) { - for (DroppedItem droppedItem : dropped_items) { - if (droppedItem.item_id != null) droppedItem.item = proj.getItem(droppedItem.item_id); - if (droppedItem.item != null) droppedItem.item.addBacklink(this); - } - } - this.state = State.linked; - } - + //Available from linked state; + //None + + public static class DroppedItem { + //Available from parsed state; + public String item_id = null; + public String chance = null; + public Integer quantity_min = null; + public Integer quantity_max = null; + + //Available from linked state; + public Item item = null; + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + id; + } + + public static String getStaticDesc() { + return "Droplists"; + } + + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List droplists = (List) parser.parse(reader); + for (Object obj : droplists) { + Map droplistJson = (Map) obj; + Droplist droplist = fromJson(droplistJson); + droplist.jsonFile = jsonFile; + droplist.parent = category; + if (droplist.getDataType() == GameSource.Type.created || droplist.getDataType() == GameSource.Type.altered) { + droplist.writable = true; + } + category.add(droplist); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static Droplist fromJson(String jsonString) throws ParseException { + Map droplistJson = (Map) new JSONParser().parse(jsonString); + Droplist droplist = fromJson(droplistJson); + droplist.parse(droplistJson); + return droplist; + } + + @SuppressWarnings("rawtypes") + public static Droplist fromJson(Map droplistJson) { + Droplist droplist = new Droplist(); + droplist.id = (String) droplistJson.get("id"); + return droplist; + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map droplistJson) { + List droppedItemsJson = (List) droplistJson.get("items"); + if (droppedItemsJson != null && !droppedItemsJson.isEmpty()) { + this.dropped_items = new ArrayList(); + for (Object droppedItemJsonObj : droppedItemsJson) { + Map droppedItemJson = (Map) droppedItemJsonObj; + DroppedItem droppedItem = new DroppedItem(); + droppedItem.item_id = (String) droppedItemJson.get("itemID"); + //if (droppedItemJson.get("chance") != null) droppedItem.chance = JSONElement.parseChance(droppedItemJson.get("chance").toString()); + droppedItem.chance = (String) droppedItemJson.get("chance"); + Map droppedItemQtyJson = (Map) droppedItemJson.get("quantity"); + if (droppedItemQtyJson != null) { + droppedItem.quantity_min = JSONElement.getInteger((Number) droppedItemQtyJson.get("min")); + droppedItem.quantity_max = JSONElement.getInteger((Number) droppedItemQtyJson.get("max")); + } + this.dropped_items.add(droppedItem); + } + } + this.state = State.parsed; + } + + @Override + public void link() { + if (!this.linkCheck()) return; + Project proj = getProject(); + if (proj == null) { + Notification.addError("Error linking droplist " + id + ". No parent project found."); + return; + } + if (dropped_items != null) { + for (DroppedItem droppedItem : dropped_items) { + if (droppedItem.item_id != null) droppedItem.item = proj.getItem(droppedItem.item_id); + if (droppedItem.item != null) droppedItem.item.addBacklink(this); + } + } + this.state = State.linked; + } - public static Image getImage() { - return DefaultIcons.getDroplistImage(); - } - - @Override - public Image getIcon() { - return DefaultIcons.getDroplistIcon(); - } - - @Override - public GameDataElement clone() { - Droplist clone = new Droplist(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - if (this.dropped_items != null) { - clone.dropped_items = new ArrayList(); - for (DroppedItem di : this.dropped_items) { - DroppedItem diclone = new DroppedItem(); - diclone.chance = di.chance; - diclone.item_id = di.item_id; - diclone.quantity_min = di.quantity_min; - diclone.quantity_max = di.quantity_max; - diclone.item = di.item; - if (diclone.item != null) { - diclone.item.addBacklink(clone); - } - clone.dropped_items.add(diclone); - } - } - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (dropped_items != null) { - for (DroppedItem di : dropped_items) { - if (di.item == oldOne) { - oldOne.removeBacklink(this); - di.item = (Item) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map droplistJson = new LinkedHashMap(); - droplistJson.put("id", this.id); - if (this.dropped_items != null) { - List droppedItemsJson = new ArrayList(); - droplistJson.put("items", droppedItemsJson); - for (DroppedItem droppedItem : this.dropped_items) { - Map droppedItemJson = new LinkedHashMap(); - droppedItemsJson.add(droppedItemJson); - if (droppedItem.item != null) { - droppedItemJson.put("itemID", droppedItem.item.id); - } else if (droppedItem.item_id != null) { - droppedItemJson.put("itemID", droppedItem.item_id); - } - //if (droppedItem.chance != null) droppedItemJson.put("chance", JSONElement.printJsonChance(droppedItem.chance)); - if (droppedItem.chance != null) droppedItemJson.put("chance", droppedItem.chance); - if (droppedItem.quantity_min != null || droppedItem.quantity_max != null) { - Map quantityJson = new LinkedHashMap(); - droppedItemJson.put("quantity", quantityJson); - if (droppedItem.quantity_min != null) quantityJson.put("min", droppedItem.quantity_min); - else quantityJson.put("min", 0); - if (droppedItem.quantity_max != null) quantityJson.put("max", droppedItem.quantity_max); - else quantityJson.put("max", 0); - } - } - } - return droplistJson; - } - + public static Image getImage() { + return DefaultIcons.getDroplistImage(); + } + + @Override + public Image getIcon() { + return DefaultIcons.getDroplistIcon(); + } + + @Override + public GameDataElement clone() { + Droplist clone = new Droplist(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + if (this.dropped_items != null) { + clone.dropped_items = new ArrayList(); + for (DroppedItem di : this.dropped_items) { + DroppedItem diclone = new DroppedItem(); + diclone.chance = di.chance; + diclone.item_id = di.item_id; + diclone.quantity_min = di.quantity_min; + diclone.quantity_max = di.quantity_max; + diclone.item = di.item; + if (diclone.item != null) { + diclone.item.addBacklink(clone); + } + clone.dropped_items.add(diclone); + } + } + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (dropped_items != null) { + for (DroppedItem di : dropped_items) { + if (di.item == oldOne) { + oldOne.removeBacklink(this); + di.item = (Item) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map droplistJson = new LinkedHashMap(); + droplistJson.put("id", this.id); + if (this.dropped_items != null) { + List droppedItemsJson = new ArrayList(); + droplistJson.put("items", droppedItemsJson); + for (DroppedItem droppedItem : this.dropped_items) { + Map droppedItemJson = new LinkedHashMap(); + droppedItemsJson.add(droppedItemJson); + if (droppedItem.item != null) { + droppedItemJson.put("itemID", droppedItem.item.id); + } else if (droppedItem.item_id != null) { + droppedItemJson.put("itemID", droppedItem.item_id); + } + //if (droppedItem.chance != null) droppedItemJson.put("chance", JSONElement.printJsonChance(droppedItem.chance)); + if (droppedItem.chance != null) droppedItemJson.put("chance", droppedItem.chance); + if (droppedItem.quantity_min != null || droppedItem.quantity_max != null) { + Map quantityJson = new LinkedHashMap(); + droppedItemJson.put("quantity", quantityJson); + if (droppedItem.quantity_min != null) quantityJson.put("min", droppedItem.quantity_min); + else quantityJson.put("min", 0); + if (droppedItem.quantity_max != null) quantityJson.put("max", droppedItem.quantity_max); + else quantityJson.put("max", 0); + } + } + } + return droplistJson; + } + + + @Override + public String getProjectFilename() { + return "droplists_" + getProject().name + ".json"; + } - @Override - public String getProjectFilename() { - return "droplists_"+getProject().name+".json"; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java index 9e9ac41..3b1edd3 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java @@ -1,253 +1,247 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Serializable; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.tree.TreeNode; - -import org.json.simple.JSONArray; - import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.*; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.json.simple.JSONArray; + +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.*; +import java.util.List; +import java.util.*; public class GameDataCategory extends ArrayList implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = 5486008219704443733L; - - public GameDataSet parent; - public String name; - - public GameDataCategory(GameDataSet parent, String name) { - super(); - this.parent = parent; - this.name = name; - } + private static final long serialVersionUID = 5486008219704443733L; - @Override - public TreeNode getChildAt(int childIndex) { - return get(childIndex); - } + public GameDataSet parent; + public String name; - @Override - public int getChildCount() { - return size(); - } + public GameDataCategory(GameDataSet parent, String name) { + super(); + this.parent = parent; + this.name = name; + } - @Override - public TreeNode getParent() { - return parent; - } + @Override + public TreeNode getChildAt(int childIndex) { + return get(childIndex); + } - @Override - public int getIndex(TreeNode node) { - return indexOf(node); - } + @Override + public int getChildCount() { + return size(); + } - @Override - public boolean getAllowsChildren() { - return true; - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public boolean isLeaf() { - return false; - } + @Override + public int getIndex(TreeNode node) { + return indexOf(node); + } - @Override - public Enumeration children() { - return Collections.enumeration(this); - } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.getChildCount() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (E node : this) { - node.notifyCreated(); - } - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+this.name; - } + @Override + public boolean getAllowsChildren() { + return true; + } - @Override - public boolean equals(Object o) { - return (o == this); - } - - @Override - public Project getProject() { - return parent.getProject(); - } - - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - return DefaultIcons.getJsonClosedIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getJsonClosedIcon(); - } - @Override - public Image getOpenIcon() { - return DefaultIcons.getJsonOpenIcon(); - } - - @Override - public GameDataSet getDataSet() { - return parent.getDataSet(); - } + @Override + public boolean isLeaf() { + return false; + } - @Override - public Type getDataType() { - return parent.getDataType(); - } - - @SuppressWarnings("rawtypes") - public void save(File jsonFile) { - if (getDataType() != GameSource.Type.created && getDataType() != GameSource.Type.altered) { - Notification.addError("Error while trying to write json file "+jsonFile.getAbsolutePath()+" : Game Source type "+getDataType().toString()+" should not be saved."); - return; - } - List dataToSave = new ArrayList(); - for (E element : this) { - if (element.jsonFile.equals(jsonFile)) { - dataToSave.add(element.toJson()); - } - } - if (dataToSave.isEmpty() && jsonFile.exists()) { - if (jsonFile.delete()) { - Notification.addSuccess("File "+jsonFile.getAbsolutePath()+" deleted."); - } else { - Notification.addError("Error deleting file "+jsonFile.getAbsolutePath()); - } - - return; - } - StringWriter writer = new JsonPrettyWriter(); - try { - JSONArray.writeJSONString(dataToSave, writer); - } catch (IOException e) { - //Impossible with a StringWriter - } - String toWrite = writer.toString(); - try { - FileWriter w = new FileWriter(jsonFile); - w.write(toWrite); - w.close(); - for (E element : this) { - element.state = GameDataElement.State.saved; - } - Notification.addSuccess("Json file "+jsonFile.getAbsolutePath()+" saved."); - } catch (IOException e) { - Notification.addError("Error while writing json file "+jsonFile.getAbsolutePath()+" : "+e.getMessage()); - e.printStackTrace(); - } - - } - + @Override + public Enumeration children() { + return Collections.enumeration(this); + } - public List attemptSave(boolean checkImpactedCategory, String fileName) { - List events = new ArrayList(); - GameDataCategory impactedCategory = null; - String impactedFileName = fileName; - Map containedIds = new LinkedHashMap(); - for (JSONElement node : this) { - if (node.getDataType() == GameSource.Type.created && getProject().baseContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { - if (getProject().alteredContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { - events.add(new SaveEvent(SaveEvent.Type.moveToAltered, node, true, "Element ID matches one already present in the altered game content. Change this ID before saving.")); - } else { - events.add(new SaveEvent(SaveEvent.Type.moveToAltered, node)); - impactedFileName = getProject().baseContent.gameData.getGameDataElement(node.getClass(), node.id).jsonFile.getName(); - impactedCategory = getProject().alteredContent.gameData.getCategory(node.getClass()); - } - } else if (this.getDataType() == GameSource.Type.altered && getProject().baseContent.gameData.getGameDataElement(node.getClass(), node.id) == null) { - if (getProject().createdContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { - events.add(new SaveEvent(SaveEvent.Type.moveToCreated, node, true, "Element ID matches one already present in the created game content. Change this ID before saving.")); - } else { - events.add(new SaveEvent(SaveEvent.Type.moveToCreated, node)); - impactedCategory = getProject().createdContent.gameData.getCategory(node.getClass()); - impactedFileName = node.getProjectFilename(); - } - } else if (node.needsSaving()) { - events.add(new SaveEvent(SaveEvent.Type.alsoSave, node)); - } - if (containedIds.containsKey(node.id)) { - containedIds.put(node.id, containedIds.get(node.id) + 1); - } else { - containedIds.put(node.id, 1); - } - } - for (String key : containedIds.keySet()) { - if (containedIds.get(key) > 1) { - E node = null; - for (E n : this) { - if (key.equals(n.id)) { - node = n; - break; - } - } - events.add(new SaveEvent(SaveEvent.Type.alsoSave, node, true, "There are "+containedIds.get(node.id)+" elements with this ID in this category. Change the conflicting IDs before saving.")); - } - } - if (checkImpactedCategory && impactedCategory != null) { - events.addAll(impactedCategory.attemptSave(false, impactedFileName)); - } - return events; - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.getChildCount() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (E node : this) { + node.notifyCreated(); + } + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + this.name; + } + + @Override + public boolean equals(Object o) { + return (o == this); + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + return DefaultIcons.getJsonClosedIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getJsonClosedIcon(); + } + + @Override + public Image getOpenIcon() { + return DefaultIcons.getJsonOpenIcon(); + } + + @Override + public GameDataSet getDataSet() { + return parent.getDataSet(); + } + + @Override + public Type getDataType() { + return parent.getDataType(); + } + + @SuppressWarnings("rawtypes") + public void save(File jsonFile) { + if (getDataType() != GameSource.Type.created && getDataType() != GameSource.Type.altered) { + Notification.addError("Error while trying to write json file " + jsonFile.getAbsolutePath() + " : Game Source type " + getDataType().toString() + " should not be saved."); + return; + } + List dataToSave = new ArrayList(); + for (E element : this) { + if (element.jsonFile.equals(jsonFile)) { + dataToSave.add(element.toJson()); + } + } + if (dataToSave.isEmpty() && jsonFile.exists()) { + if (jsonFile.delete()) { + Notification.addSuccess("File " + jsonFile.getAbsolutePath() + " deleted."); + } else { + Notification.addError("Error deleting file " + jsonFile.getAbsolutePath()); + } + + return; + } + StringWriter writer = new JsonPrettyWriter(); + try { + JSONArray.writeJSONString(dataToSave, writer); + } catch (IOException e) { + //Impossible with a StringWriter + } + String toWrite = writer.toString(); + try { + FileWriter w = new FileWriter(jsonFile); + w.write(toWrite); + w.close(); + for (E element : this) { + element.state = GameDataElement.State.saved; + } + Notification.addSuccess("Json file " + jsonFile.getAbsolutePath() + " saved."); + } catch (IOException e) { + Notification.addError("Error while writing json file " + jsonFile.getAbsolutePath() + " : " + e.getMessage()); + e.printStackTrace(); + } + + } + + + public List attemptSave(boolean checkImpactedCategory, String fileName) { + List events = new ArrayList(); + GameDataCategory impactedCategory = null; + String impactedFileName = fileName; + Map containedIds = new LinkedHashMap(); + for (JSONElement node : this) { + if (node.getDataType() == GameSource.Type.created && getProject().baseContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { + if (getProject().alteredContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { + events.add(new SaveEvent(SaveEvent.Type.moveToAltered, node, true, "Element ID matches one already present in the altered game content. Change this ID before saving.")); + } else { + events.add(new SaveEvent(SaveEvent.Type.moveToAltered, node)); + impactedFileName = getProject().baseContent.gameData.getGameDataElement(node.getClass(), node.id).jsonFile.getName(); + impactedCategory = getProject().alteredContent.gameData.getCategory(node.getClass()); + } + } else if (this.getDataType() == GameSource.Type.altered && getProject().baseContent.gameData.getGameDataElement(node.getClass(), node.id) == null) { + if (getProject().createdContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { + events.add(new SaveEvent(SaveEvent.Type.moveToCreated, node, true, "Element ID matches one already present in the created game content. Change this ID before saving.")); + } else { + events.add(new SaveEvent(SaveEvent.Type.moveToCreated, node)); + impactedCategory = getProject().createdContent.gameData.getCategory(node.getClass()); + impactedFileName = node.getProjectFilename(); + } + } else if (node.needsSaving()) { + events.add(new SaveEvent(SaveEvent.Type.alsoSave, node)); + } + if (containedIds.containsKey(node.id)) { + containedIds.put(node.id, containedIds.get(node.id) + 1); + } else { + containedIds.put(node.id, 1); + } + } + for (String key : containedIds.keySet()) { + if (containedIds.get(key) > 1) { + E node = null; + for (E n : this) { + if (key.equals(n.id)) { + node = n; + break; + } + } + events.add(new SaveEvent(SaveEvent.Type.alsoSave, node, true, "There are " + containedIds.get(node.id) + " elements with this ID in this category. Change the conflicting IDs before saving.")); + } + } + if (checkImpactedCategory && impactedCategory != null) { + events.addAll(impactedCategory.attemptSave(false, impactedFileName)); + } + return events; + } + + public boolean remove(E o) { + int index = getProject().getNodeIndex(o); + boolean result = super.remove(o); + getProject().fireElementRemoved(o, index); + return result; + } + + @Override + public boolean needsSaving() { + for (E node : this) { + if (node.needsSaving()) return true; + } + return false; + } - public boolean remove(E o) { - int index = getProject().getNodeIndex(o); - boolean result = super.remove(o); - getProject().fireElementRemoved(o, index); - return result; - } - - @Override - public boolean needsSaving() { - for (E node : this) { - if (node.needsSaving()) return true; - } - return false; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataSet.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataSet.java index 187dbcb..6d1ca11 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataSet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataSet.java @@ -1,14 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; -import java.io.File; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; @@ -18,456 +9,479 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.SavedSlotCollection; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.File; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + public class GameDataSet implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = -8558067213826970968L; - - public static final String DEFAULT_REL_PATH_IN_SOURCE = "res"+File.separator+"raw"+File.separator; - public static final String DEFAULT_REL_PATH_IN_PROJECT = "json"+File.separator; - - public static final String GAME_AC_ARRAY_NAME = "loadresource_actorconditions"; - public static final String GAME_DIALOGUES_ARRAY_NAME = "loadresource_conversationlists"; - public static final String GAME_DROPLISTS_ARRAY_NAME = "loadresource_droplists"; - public static final String GAME_ITEMS_ARRAY_NAME = "loadresource_items"; - public static final String GAME_ITEMCAT_ARRAY_NAME = "loadresource_itemcategories"; - public static final String GAME_NPC_ARRAY_NAME = "loadresource_monsters"; - public static final String GAME_QUESTS_ARRAY_NAME = "loadresource_quests"; - public static final String DEBUG_SUFFIX = "_debug"; - public static final String RESOURCE_PREFIX = "@raw/"; - public static final String FILENAME_SUFFIX = ".json"; - - public File baseFolder; - - public GameDataCategory actorConditions; - public GameDataCategory dialogues; - public GameDataCategory droplists; - public GameDataCategory items; - public GameDataCategory itemCategories; - public GameDataCategory npcs; - public GameDataCategory quests; - - public GameSource parent; - public SavedSlotCollection v; - - public GameDataSet(GameSource source) { - - this.parent = source; - v = new SavedSlotCollection(); + private static final long serialVersionUID = -8558067213826970968L; - if (parent.type.equals(GameSource.Type.altered) || parent.type.equals(GameSource.Type.created)) { - this.baseFolder = new File(parent.baseFolder, GameDataSet.DEFAULT_REL_PATH_IN_PROJECT); - if (!baseFolder.exists()) this.baseFolder.mkdirs(); - } else if (parent.type.equals(GameSource.Type.source)) { - this.baseFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); - } - - actorConditions = new GameDataCategory(this, ActorCondition.getStaticDesc()); - dialogues = new GameDataCategory(this, Dialogue.getStaticDesc()); - droplists = new GameDataCategory(this, Droplist.getStaticDesc()); - items = new GameDataCategory(this, Item.getStaticDesc()); - itemCategories = new GameDataCategory(this, ItemCategory.getStaticDesc()); - npcs = new GameDataCategory(this, NPC.getStaticDesc()); - quests = new GameDataCategory(this, Quest.getStaticDesc()); - - v.add(actorConditions); - v.add(dialogues); - v.add(droplists); - v.add(items); - v.add(itemCategories); - v.add(npcs); - v.add(quests); - - //Start parsing to populate categories' content. - if (parent.type == GameSource.Type.source && (parent.parent.sourceSetToUse == ResourceSet.debugData || parent.parent.sourceSetToUse == ResourceSet.gameData)) { - String suffix = (parent.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : ""; - - if (parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME+suffix) != null) { - for (String resource : parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME+suffix)) { - File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - ActorCondition.fromJson(f, actorConditions); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - if (parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME+suffix) != null) { - for (String resource : parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME+suffix)) { - File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - Dialogue.fromJson(f, dialogues); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - if (parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME+suffix) != null) { - for (String resource : parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME+suffix)) { - File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - Droplist.fromJson(f, droplists); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - if (parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME+suffix) != null) { - for (String resource : parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME+suffix)) { - File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - Item.fromJson(f, items); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - if (parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME+suffix) != null) { - for (String resource : parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME+suffix)) { - File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - ItemCategory.fromJson(f, itemCategories); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - if (parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME+suffix) != null) { - for (String resource : parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME+suffix)) { - File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - NPC.fromJson(f, npcs); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - if (parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME+suffix) != null) { - for (String resource : parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME+suffix)) { - File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - Quest.fromJson(f, quests); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - } else if (parent.type != GameSource.Type.referenced) { - for (File f : baseFolder.listFiles()) { - if (f.getName().startsWith("actorconditions_")) { - ActorCondition.fromJson(f, actorConditions); - } else if (f.getName().startsWith("conversationlist_")) { - Dialogue.fromJson(f, dialogues); - } else if (f.getName().startsWith("droplists_")) { - Droplist.fromJson(f, droplists); - } else if (f.getName().startsWith("itemlist_")) { - Item.fromJson(f, items); - } else if (f.getName().startsWith("itemcategories_")) { - ItemCategory.fromJson(f, itemCategories); - } else if (f.getName().startsWith("monsterlist_")) { - NPC.fromJson(f, npcs); - } else if (f.getName().startsWith("questlist")) { - Quest.fromJson(f, quests); - } - } - } - } - - @Override - public Enumeration children() { - return v.getNonEmptyElements(); - } - @Override - public boolean getAllowsChildren() { - return true; - } - @Override - public TreeNode getChildAt(int arg0) { - return v.getNonEmptyElementAt(arg0); - } - @Override - public int getChildCount() { - return v.getNonEmptySize(); - } - @Override - public int getIndex(TreeNode arg0) { - return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); - } - @Override - public TreeNode getParent() { - return parent; - } - @Override - public boolean isLeaf() { - return false; - } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.v.getNonEmptySize() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (ProjectTreeNode node : v.getNonEmptyIterable()) { - node.notifyCreated(); - } - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+"JSON data"; - } - + public static final String DEFAULT_REL_PATH_IN_SOURCE = "res" + File.separator + "raw" + File.separator; + public static final String DEFAULT_REL_PATH_IN_PROJECT = "json" + File.separator; - public void refreshTransients() { - - } - - public ActorCondition getActorCondition(String id) { - if (actorConditions == null) return null; - for (ActorCondition gde : actorConditions) { - if (id.equals(gde.id)){ - return gde; - } - } - return null; - } - - public Dialogue getDialogue(String id) { - if (dialogues == null) return null; - for (Dialogue gde : dialogues) { - if (id.equals(gde.id)){ - return gde; - } - } - return null; - } - - public Droplist getDroplist(String id) { - if (droplists == null) return null; - for (Droplist gde : droplists) { - if (id.equals(gde.id)){ - return gde; - } - } - return null; - } - - public Item getItem(String id) { - if (items == null) return null; - for (Item gde : items) { - if (id.equals(gde.id)){ - return gde; - } - } - return null; - } - - public ItemCategory getItemCategory(String id) { - if (itemCategories == null) return null; - for (ItemCategory gde : itemCategories) { - if (id.equals(gde.id)){ - return gde; - } - } - return null; - } - - public NPC getNPC(String id) { - if (npcs == null) return null; - for (NPC gde : npcs) { - if (id.equals(gde.id)){ - return gde; - } - } - return null; - } - - public NPC getNPCIgnoreCase(String id) { - if (npcs == null) return null; - for (NPC gde : npcs) { - if (id.equalsIgnoreCase(gde.id)){ - return gde; - } - } - return null; - } - - public Quest getQuest(String id) { - if (quests == null) return null; - for (Quest gde : quests) { - if (id.equals(gde.id)){ - return gde; - } - } - return null; - } - - @Override - public Project getProject() { - return parent.getProject(); - } - + public static final String GAME_AC_ARRAY_NAME = "loadresource_actorconditions"; + public static final String GAME_DIALOGUES_ARRAY_NAME = "loadresource_conversationlists"; + public static final String GAME_DROPLISTS_ARRAY_NAME = "loadresource_droplists"; + public static final String GAME_ITEMS_ARRAY_NAME = "loadresource_items"; + public static final String GAME_ITEMCAT_ARRAY_NAME = "loadresource_itemcategories"; + public static final String GAME_NPC_ARRAY_NAME = "loadresource_monsters"; + public static final String GAME_QUESTS_ARRAY_NAME = "loadresource_quests"; + public static final String DEBUG_SUFFIX = "_debug"; + public static final String RESOURCE_PREFIX = "@raw/"; + public static final String FILENAME_SUFFIX = ".json"; - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - return DefaultIcons.getJsonClosedIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getJsonClosedIcon(); - } - @Override - public Image getOpenIcon() { - return DefaultIcons.getJsonOpenIcon(); - } + public File baseFolder; - public void addElement(JSONElement node) { - ProjectTreeNode higherEmptyParent = this; - while (higherEmptyParent != null) { - if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); - else break; - } - if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; - if (node instanceof ActorCondition) { - if (actorConditions.isEmpty() && higherEmptyParent == null) higherEmptyParent = actorConditions; - actorConditions.add((ActorCondition) node); - node.parent = actorConditions; - } else if (node instanceof Dialogue) { - if (dialogues.isEmpty() && higherEmptyParent == null) higherEmptyParent = dialogues; - dialogues.add((Dialogue) node); - node.parent = dialogues; - } else if (node instanceof Droplist) { - if (droplists.isEmpty() && higherEmptyParent == null) higherEmptyParent = droplists; - droplists.add((Droplist) node); - node.parent = droplists; - } else if (node instanceof Item) { - if (items.isEmpty() && higherEmptyParent == null) higherEmptyParent = items; - items.add((Item) node); - node.parent = items; - } else if (node instanceof ItemCategory) { - if (itemCategories.isEmpty() && higherEmptyParent == null) higherEmptyParent = itemCategories; - itemCategories.add((ItemCategory) node); - node.parent = itemCategories; - } else if (node instanceof NPC) { - if (npcs.isEmpty() && higherEmptyParent == null) higherEmptyParent = npcs; - npcs.add((NPC) node); - node.parent = npcs; - } else if (node instanceof Quest) { - if (quests.isEmpty() && higherEmptyParent == null) higherEmptyParent = quests; - quests.add((Quest) node); - node.parent = quests; - } else { - Notification.addError("Cannot add "+node.getDesc()+". Unknown data type."); - return; - } - if (node.jsonFile != null && parent.type == GameSource.Type.altered) { - //Altered node. - node.jsonFile = new File(this.baseFolder, node.jsonFile.getName()); - } else { - //Created node. - node.jsonFile = new File(this.baseFolder, node.getProjectFilename()); - } - if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); - else node.notifyCreated(); - } - + public GameDataCategory actorConditions; + public GameDataCategory dialogues; + public GameDataCategory droplists; + public GameDataCategory items; + public GameDataCategory itemCategories; + public GameDataCategory npcs; + public GameDataCategory quests; - @Override - public GameDataSet getDataSet() { - return this; - } - - @Override - public Type getDataType() { - return parent.getDataType(); - } - - @Override - public boolean isEmpty() { - return v.isEmpty(); - } + public GameSource parent; + public SavedSlotCollection v; - public JSONElement getGameDataElement(Class gdeClass, String id) { - if (gdeClass == ActorCondition.class) { - return getActorCondition(id); - } - if (gdeClass == Dialogue.class) { - return getDialogue(id); - } - if (gdeClass == Droplist.class) { - return getDroplist(id); - } - if (gdeClass == ItemCategory.class) { - return getItemCategory(id); - } - if (gdeClass == Item.class) { - return getItem(id); - } - if (gdeClass == NPC.class) { - return getNPC(id); - } - if (gdeClass == Quest.class) { - return getQuest(id); - } - return null; - } + public GameDataSet(GameSource source) { - public GameDataCategory getCategory(Class gdeClass) { - if (gdeClass == ActorCondition.class) { - return actorConditions; - } - if (gdeClass == Dialogue.class) { - return dialogues; - } - if (gdeClass == Droplist.class) { - return droplists; - } - if (gdeClass == ItemCategory.class) { - return itemCategories; - } - if (gdeClass == Item.class) { - return items; - } - if (gdeClass == NPC.class) { - return npcs; - } - if (gdeClass == Quest.class) { - return quests; - } - return null; - } - - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : v.getNonEmptyIterable()) { - if (node.needsSaving()) return true; - } - return false; - } + this.parent = source; + v = new SavedSlotCollection(); + + if (parent.type.equals(GameSource.Type.altered) || parent.type.equals(GameSource.Type.created)) { + this.baseFolder = new File(parent.baseFolder, GameDataSet.DEFAULT_REL_PATH_IN_PROJECT); + if (!baseFolder.exists()) this.baseFolder.mkdirs(); + } else if (parent.type.equals(GameSource.Type.source)) { + this.baseFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); + } + + actorConditions = new GameDataCategory(this, ActorCondition.getStaticDesc()); + dialogues = new GameDataCategory(this, Dialogue.getStaticDesc()); + droplists = new GameDataCategory(this, Droplist.getStaticDesc()); + items = new GameDataCategory(this, Item.getStaticDesc()); + itemCategories = new GameDataCategory(this, ItemCategory.getStaticDesc()); + npcs = new GameDataCategory(this, NPC.getStaticDesc()); + quests = new GameDataCategory(this, Quest.getStaticDesc()); + + v.add(actorConditions); + v.add(dialogues); + v.add(droplists); + v.add(items); + v.add(itemCategories); + v.add(npcs); + v.add(quests); + + //Start parsing to populate categories' content. + if (parent.type == GameSource.Type.source && (parent.parent.sourceSetToUse == ResourceSet.debugData || parent.parent.sourceSetToUse == ResourceSet.gameData)) { + String suffix = (parent.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : ""; + + if (parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME + suffix) != null) { + for (String resource : parent.referencedSourceFiles.get(GAME_AC_ARRAY_NAME + suffix)) { + File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + ActorCondition.fromJson(f, actorConditions); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + if (parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME + suffix) != null) { + for (String resource : parent.referencedSourceFiles.get(GAME_DIALOGUES_ARRAY_NAME + suffix)) { + File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + Dialogue.fromJson(f, dialogues); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + if (parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME + suffix) != null) { + for (String resource : parent.referencedSourceFiles.get(GAME_DROPLISTS_ARRAY_NAME + suffix)) { + File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + Droplist.fromJson(f, droplists); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + if (parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME + suffix) != null) { + for (String resource : parent.referencedSourceFiles.get(GAME_ITEMS_ARRAY_NAME + suffix)) { + File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + Item.fromJson(f, items); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + if (parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME + suffix) != null) { + for (String resource : parent.referencedSourceFiles.get(GAME_ITEMCAT_ARRAY_NAME + suffix)) { + File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + ItemCategory.fromJson(f, itemCategories); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + if (parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME + suffix) != null) { + for (String resource : parent.referencedSourceFiles.get(GAME_NPC_ARRAY_NAME + suffix)) { + File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + NPC.fromJson(f, npcs); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + if (parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME + suffix) != null) { + for (String resource : parent.referencedSourceFiles.get(GAME_QUESTS_ARRAY_NAME + suffix)) { + File f = new File(baseFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + Quest.fromJson(f, quests); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + } else if (parent.type != GameSource.Type.referenced) { + for (File f : baseFolder.listFiles()) { + if (f.getName().startsWith("actorconditions_")) { + ActorCondition.fromJson(f, actorConditions); + } else if (f.getName().startsWith("conversationlist_")) { + Dialogue.fromJson(f, dialogues); + } else if (f.getName().startsWith("droplists_")) { + Droplist.fromJson(f, droplists); + } else if (f.getName().startsWith("itemlist_")) { + Item.fromJson(f, items); + } else if (f.getName().startsWith("itemcategories_")) { + ItemCategory.fromJson(f, itemCategories); + } else if (f.getName().startsWith("monsterlist_")) { + NPC.fromJson(f, npcs); + } else if (f.getName().startsWith("questlist")) { + Quest.fromJson(f, quests); + } + } + } + } + + @Override + public Enumeration children() { + return v.getNonEmptyElements(); + } + + @Override + public boolean getAllowsChildren() { + return true; + } + + @Override + public TreeNode getChildAt(int arg0) { + return v.getNonEmptyElementAt(arg0); + } + + @Override + public int getChildCount() { + return v.getNonEmptySize(); + } + + @Override + public int getIndex(TreeNode arg0) { + return v.getNonEmptyIndexOf((ProjectTreeNode) arg0); + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.v.getNonEmptySize() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (ProjectTreeNode node : v.getNonEmptyIterable()) { + node.notifyCreated(); + } + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + "JSON data"; + } + + + public void refreshTransients() { + + } + + public ActorCondition getActorCondition(String id) { + if (actorConditions == null) return null; + for (ActorCondition gde : actorConditions) { + if (id.equals(gde.id)) { + return gde; + } + } + return null; + } + + public Dialogue getDialogue(String id) { + if (dialogues == null) return null; + for (Dialogue gde : dialogues) { + if (id.equals(gde.id)) { + return gde; + } + } + return null; + } + + public Droplist getDroplist(String id) { + if (droplists == null) return null; + for (Droplist gde : droplists) { + if (id.equals(gde.id)) { + return gde; + } + } + return null; + } + + public Item getItem(String id) { + if (items == null) return null; + for (Item gde : items) { + if (id.equals(gde.id)) { + return gde; + } + } + return null; + } + + public ItemCategory getItemCategory(String id) { + if (itemCategories == null) return null; + for (ItemCategory gde : itemCategories) { + if (id.equals(gde.id)) { + return gde; + } + } + return null; + } + + public NPC getNPC(String id) { + if (npcs == null) return null; + for (NPC gde : npcs) { + if (id.equals(gde.id)) { + return gde; + } + } + return null; + } + + public NPC getNPCIgnoreCase(String id) { + if (npcs == null) return null; + for (NPC gde : npcs) { + if (id.equalsIgnoreCase(gde.id)) { + return gde; + } + } + return null; + } + + public Quest getQuest(String id) { + if (quests == null) return null; + for (Quest gde : quests) { + if (id.equals(gde.id)) { + return gde; + } + } + return null; + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + return DefaultIcons.getJsonClosedIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getJsonClosedIcon(); + } + + @Override + public Image getOpenIcon() { + return DefaultIcons.getJsonOpenIcon(); + } + + public void addElement(JSONElement node) { + ProjectTreeNode higherEmptyParent = this; + while (higherEmptyParent != null) { + if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty()) + higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent(); + else break; + } + if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; + if (node instanceof ActorCondition) { + if (actorConditions.isEmpty() && higherEmptyParent == null) higherEmptyParent = actorConditions; + actorConditions.add((ActorCondition) node); + node.parent = actorConditions; + } else if (node instanceof Dialogue) { + if (dialogues.isEmpty() && higherEmptyParent == null) higherEmptyParent = dialogues; + dialogues.add((Dialogue) node); + node.parent = dialogues; + } else if (node instanceof Droplist) { + if (droplists.isEmpty() && higherEmptyParent == null) higherEmptyParent = droplists; + droplists.add((Droplist) node); + node.parent = droplists; + } else if (node instanceof Item) { + if (items.isEmpty() && higherEmptyParent == null) higherEmptyParent = items; + items.add((Item) node); + node.parent = items; + } else if (node instanceof ItemCategory) { + if (itemCategories.isEmpty() && higherEmptyParent == null) higherEmptyParent = itemCategories; + itemCategories.add((ItemCategory) node); + node.parent = itemCategories; + } else if (node instanceof NPC) { + if (npcs.isEmpty() && higherEmptyParent == null) higherEmptyParent = npcs; + npcs.add((NPC) node); + node.parent = npcs; + } else if (node instanceof Quest) { + if (quests.isEmpty() && higherEmptyParent == null) higherEmptyParent = quests; + quests.add((Quest) node); + node.parent = quests; + } else { + Notification.addError("Cannot add " + node.getDesc() + ". Unknown data type."); + return; + } + if (node.jsonFile != null && parent.type == GameSource.Type.altered) { + //Altered node. + node.jsonFile = new File(this.baseFolder, node.jsonFile.getName()); + } else { + //Created node. + node.jsonFile = new File(this.baseFolder, node.getProjectFilename()); + } + if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); + else node.notifyCreated(); + } + + + @Override + public GameDataSet getDataSet() { + return this; + } + + @Override + public Type getDataType() { + return parent.getDataType(); + } + + @Override + public boolean isEmpty() { + return v.isEmpty(); + } + + public JSONElement getGameDataElement(Class gdeClass, String id) { + if (gdeClass == ActorCondition.class) { + return getActorCondition(id); + } + if (gdeClass == Dialogue.class) { + return getDialogue(id); + } + if (gdeClass == Droplist.class) { + return getDroplist(id); + } + if (gdeClass == ItemCategory.class) { + return getItemCategory(id); + } + if (gdeClass == Item.class) { + return getItem(id); + } + if (gdeClass == NPC.class) { + return getNPC(id); + } + if (gdeClass == Quest.class) { + return getQuest(id); + } + return null; + } + + public GameDataCategory getCategory(Class gdeClass) { + if (gdeClass == ActorCondition.class) { + return actorConditions; + } + if (gdeClass == Dialogue.class) { + return dialogues; + } + if (gdeClass == Droplist.class) { + return droplists; + } + if (gdeClass == ItemCategory.class) { + return itemCategories; + } + if (gdeClass == Item.class) { + return items; + } + if (gdeClass == NPC.class) { + return npcs; + } + if (gdeClass == Quest.class) { + return quests; + } + return null; + } + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : v.getNonEmptyIterable()) { + if (node.needsSaving()) return true; + } + return false; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 5917a4e..ba03e82 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -1,6 +1,13 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -10,653 +17,674 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; - import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; public class Item extends JSONElement { - private static final long serialVersionUID = -516874303672548638L; + private static final long serialVersionUID = -516874303672548638L; - //Available from init state - //public String id = null; inherited. - public String name = null; - public DisplayType display_type = null; - public String icon_id = null; - - //Available from parsed state - public Integer has_manual_price = null; - public Integer base_market_cost = null; - public String category_id = null; - public String description = null; - public HitEffect hit_effect = null; - public HitReceivedEffect hit_received_effect = null; - public DeathEffect kill_effect = null; - public EquipEffect equip_effect = null; - - //Available from linked state - public ItemCategory category = null; + //Available from init state + //public String id = null; inherited. + public String name = null; + public DisplayType display_type = null; + public String icon_id = null; - - public static class EquipEffect { - //Available from parsed state - public Integer damage_boost_min = null; - public Integer damage_boost_max = null; - public Integer max_hp_boost = null; - public Integer max_ap_boost = null; - public List conditions = null; - public Integer increase_move_cost = null; - public Integer increase_use_item_cost = null; - public Integer increase_reequip_cost = null; - public Integer increase_attack_cost = null; - public Integer increase_attack_chance = null; - public Integer increase_critical_skill = null; - public Integer increase_block_chance = null; - public Integer increase_damage_resistance = null; - public Double critical_multiplier = null; - public Integer damage_modifier = null; - } + //Available from parsed state + public Integer has_manual_price = null; + public Integer base_market_cost = null; + public String category_id = null; + public String description = null; + public HitEffect hit_effect = null; + public HitReceivedEffect hit_received_effect = null; + public DeathEffect kill_effect = null; + public EquipEffect equip_effect = null; - - public static enum DisplayType { - ordinary, - quest, - extraordinary, - legendary, - rare - } - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+name+" ("+id+")"; - } + //Available from linked state + public ItemCategory category = null; - public static String getStaticDesc() { - return "Items"; - } - - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List items = (List) parser.parse(reader); - for (Object obj : items) { - Map itemJson = (Map)obj; - Item item = fromJson(itemJson); - item.jsonFile = jsonFile; - item.parent = category; - if (item.getDataType() == GameSource.Type.created || item.getDataType() == GameSource.Type.altered) { - item.writable = true; - } - category.add(item); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static Item fromJson(String jsonString) throws ParseException { - Map itemJson = (Map) new JSONParser().parse(jsonString); - Item item = fromJson(itemJson); - item.parse(itemJson); - return item; - } - - @SuppressWarnings("rawtypes") - public static Item fromJson(Map itemJson) { - Item item = new Item(); - item.icon_id = (String) itemJson.get("iconID"); - item.id = (String) itemJson.get("id"); - item.name = (String) itemJson.get("name"); - if (itemJson.get("displaytype") != null) item.display_type = DisplayType.valueOf((String) itemJson.get("displaytype")); - return item; - } - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map itemJson) { - this.has_manual_price = JSONElement.getInteger((Number) itemJson.get("hasManualPrice")); - this.base_market_cost = JSONElement.getInteger((Number) itemJson.get("baseMarketCost")); - //TODO change the debug json data.... + public static class EquipEffect { + //Available from parsed state + public Integer damage_boost_min = null; + public Integer damage_boost_max = null; + public Integer max_hp_boost = null; + public Integer max_ap_boost = null; + public List conditions = null; + public Integer increase_move_cost = null; + public Integer increase_use_item_cost = null; + public Integer increase_reequip_cost = null; + public Integer increase_attack_cost = null; + public Integer increase_attack_chance = null; + public Integer increase_critical_skill = null; + public Integer increase_block_chance = null; + public Integer increase_damage_resistance = null; + public Double critical_multiplier = null; + public Integer damage_modifier = null; + } + + + public static enum DisplayType { + ordinary, + quest, + extraordinary, + legendary, + rare + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + name + " (" + id + ")"; + } + + public static String getStaticDesc() { + return "Items"; + } + + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List items = (List) parser.parse(reader); + for (Object obj : items) { + Map itemJson = (Map) obj; + Item item = fromJson(itemJson); + item.jsonFile = jsonFile; + item.parent = category; + if (item.getDataType() == GameSource.Type.created || item.getDataType() == GameSource.Type.altered) { + item.writable = true; + } + category.add(item); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static Item fromJson(String jsonString) throws ParseException { + Map itemJson = (Map) new JSONParser().parse(jsonString); + Item item = fromJson(itemJson); + item.parse(itemJson); + return item; + } + + @SuppressWarnings("rawtypes") + public static Item fromJson(Map itemJson) { + Item item = new Item(); + item.icon_id = (String) itemJson.get("iconID"); + item.id = (String) itemJson.get("id"); + item.name = (String) itemJson.get("name"); + if (itemJson.get("displaytype") != null) + item.display_type = DisplayType.valueOf((String) itemJson.get("displaytype")); + return item; + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map itemJson) { + + this.has_manual_price = JSONElement.getInteger((Number) itemJson.get("hasManualPrice")); + this.base_market_cost = JSONElement.getInteger((Number) itemJson.get("baseMarketCost")); + //TODO change the debug json data.... // this.category_id = (String) itemJson.get("category"); - if (itemJson.get("category") != null) this.category_id = (String) itemJson.get("category").toString(); - this.description = (String) itemJson.get("description"); - - Map equipEffect = (Map) itemJson.get("equipEffect"); - if (equipEffect != null) { - this.equip_effect = new EquipEffect(); - if (equipEffect.get("increaseAttackDamage") != null) { - this.equip_effect.damage_boost_min = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("min"))); - this.equip_effect.damage_boost_max = JSONElement.getInteger((Number) (((Map)equipEffect.get("increaseAttackDamage")).get("max"))); - } - this.equip_effect.max_hp_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxHP")); - this.equip_effect.max_ap_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxAP")); - this.equip_effect.increase_move_cost = JSONElement.getInteger((Number) equipEffect.get("increaseMoveCost")); - this.equip_effect.increase_use_item_cost = JSONElement.getInteger((Number) equipEffect.get("increaseUseItemCost")); - this.equip_effect.increase_reequip_cost = JSONElement.getInteger((Number) equipEffect.get("increaseReequipCost")); - this.equip_effect.increase_attack_cost = JSONElement.getInteger((Number) equipEffect.get("increaseAttackCost")); - this.equip_effect.increase_attack_chance = JSONElement.getInteger((Number) equipEffect.get("increaseAttackChance")); - this.equip_effect.increase_critical_skill = JSONElement.getInteger((Number) equipEffect.get("increaseCriticalSkill")); - this.equip_effect.increase_block_chance = JSONElement.getInteger((Number) equipEffect.get("increaseBlockChance")); - this.equip_effect.increase_damage_resistance = JSONElement.getInteger((Number) equipEffect.get("increaseDamageResistance")); - //TODO correct game data, to unify format. + if (itemJson.get("category") != null) this.category_id = (String) itemJson.get("category").toString(); + this.description = (String) itemJson.get("description"); + + Map equipEffect = (Map) itemJson.get("equipEffect"); + if (equipEffect != null) { + this.equip_effect = new EquipEffect(); + if (equipEffect.get("increaseAttackDamage") != null) { + this.equip_effect.damage_boost_min = JSONElement.getInteger((Number) (((Map) equipEffect.get("increaseAttackDamage")).get("min"))); + this.equip_effect.damage_boost_max = JSONElement.getInteger((Number) (((Map) equipEffect.get("increaseAttackDamage")).get("max"))); + } + this.equip_effect.max_hp_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxHP")); + this.equip_effect.max_ap_boost = JSONElement.getInteger((Number) equipEffect.get("increaseMaxAP")); + this.equip_effect.increase_move_cost = JSONElement.getInteger((Number) equipEffect.get("increaseMoveCost")); + this.equip_effect.increase_use_item_cost = JSONElement.getInteger((Number) equipEffect.get("increaseUseItemCost")); + this.equip_effect.increase_reequip_cost = JSONElement.getInteger((Number) equipEffect.get("increaseReequipCost")); + this.equip_effect.increase_attack_cost = JSONElement.getInteger((Number) equipEffect.get("increaseAttackCost")); + this.equip_effect.increase_attack_chance = JSONElement.getInteger((Number) equipEffect.get("increaseAttackChance")); + this.equip_effect.increase_critical_skill = JSONElement.getInteger((Number) equipEffect.get("increaseCriticalSkill")); + this.equip_effect.increase_block_chance = JSONElement.getInteger((Number) equipEffect.get("increaseBlockChance")); + this.equip_effect.increase_damage_resistance = JSONElement.getInteger((Number) equipEffect.get("increaseDamageResistance")); + //TODO correct game data, to unify format. // this.equip_effect.critical_multiplier = JSONElement.getDouble((Number) equipEffect.get("setCriticalMultiplier")); - if (equipEffect.get("setCriticalMultiplier") != null) this.equip_effect.critical_multiplier = JSONElement.getDouble(Double.parseDouble(equipEffect.get("setCriticalMultiplier").toString())); - this.equip_effect.damage_modifier = JSONElement.getInteger((Number) equipEffect.get("setNonWeaponDamageModifier")); - - List conditionsJson = (List) equipEffect.get("addedConditions"); - if (conditionsJson != null && !conditionsJson.isEmpty()) { - this.equip_effect.conditions = new ArrayList<>(); - for (Object conditionJsonObj : conditionsJson) { - Map conditionJson = (Map)conditionJsonObj; - ConditionEffect condition = new ConditionEffect(); - condition.condition_id = (String) conditionJson.get("condition"); - condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); - this.equip_effect.conditions.add(condition); - } - } - } - - - Map hitEffect = (Map) itemJson.get("hitEffect"); - if (hitEffect != null) { - this.hit_effect = parseHitEffect(hitEffect); - } - - Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); - if (hitReceivedEffect != null) { - this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); - } - - Map killEffect = (Map) itemJson.get("killEffect"); - if (killEffect == null) { - killEffect = (Map) itemJson.get("useEffect"); - } - if (killEffect != null) { + if (equipEffect.get("setCriticalMultiplier") != null) + this.equip_effect.critical_multiplier = JSONElement.getDouble(Double.parseDouble(equipEffect.get("setCriticalMultiplier").toString())); + this.equip_effect.damage_modifier = JSONElement.getInteger((Number) equipEffect.get("setNonWeaponDamageModifier")); + + List conditionsJson = (List) equipEffect.get("addedConditions"); + if (conditionsJson != null && !conditionsJson.isEmpty()) { + this.equip_effect.conditions = new ArrayList<>(); + for (Object conditionJsonObj : conditionsJson) { + Map conditionJson = (Map) conditionJsonObj; + ConditionEffect condition = new ConditionEffect(); + condition.condition_id = (String) conditionJson.get("condition"); + condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); + this.equip_effect.conditions.add(condition); + } + } + } + + + Map hitEffect = (Map) itemJson.get("hitEffect"); + if (hitEffect != null) { + this.hit_effect = parseHitEffect(hitEffect); + } + + Map hitReceivedEffect = (Map) itemJson.get("hitReceivedEffect"); + if (hitReceivedEffect != null) { + this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); + } + + Map killEffect = (Map) itemJson.get("killEffect"); + if (killEffect == null) { + killEffect = (Map) itemJson.get("useEffect"); + } + if (killEffect != null) { this.kill_effect = parseDeathEffect(killEffect); - } - this.state = State.parsed; - } + } + this.state = State.parsed; + } + @Override + public void link() { + if (!this.linkCheck()) return; + Project proj = getProject(); + if (proj == null) { + Notification.addError("Error linking item " + id + ". No parent project found."); + return; + } - @Override - public void link() { - if (!this.linkCheck()) return; - Project proj = getProject(); - if (proj == null) { - Notification.addError("Error linking item "+id+". No parent project found."); - return; - } + if (this.icon_id != null) { + String spritesheetId = this.icon_id.split(":")[0]; + proj.getSpritesheet(spritesheetId).addBacklink(this); + } + if (this.category_id != null) this.category = proj.getItemCategory(this.category_id); + if (this.category != null) this.category.addBacklink(this); + if (this.equip_effect != null && this.equip_effect.conditions != null) { + linkConditions(this.equip_effect.conditions, proj, this); + } - if (this.icon_id != null) { - String spritesheetId = this.icon_id.split(":")[0]; - proj.getSpritesheet(spritesheetId).addBacklink(this); - } - if (this.category_id != null) this.category = proj.getItemCategory(this.category_id); - if (this.category != null) this.category.addBacklink(this); - if (this.equip_effect != null && this.equip_effect.conditions != null) { - linkConditions(this.equip_effect.conditions, proj, this); - } + if (this.hit_effect != null) { + linkConditions(this.hit_effect.conditions_source, proj, this); + linkConditions(this.hit_effect.conditions_target, proj, this); + } - if (this.hit_effect != null) { - linkConditions(this.hit_effect.conditions_source, proj, this); - linkConditions(this.hit_effect.conditions_target, proj, this); - } + if (this.hit_received_effect != null) { + linkConditions(this.hit_received_effect.conditions_source, proj, this); + linkConditions(this.hit_received_effect.conditions_target, proj, this); + } - if (this.hit_received_effect != null) { - linkConditions(this.hit_received_effect.conditions_source, proj, this); - linkConditions(this.hit_received_effect.conditions_target, proj, this); - } + if (this.kill_effect != null) { + linkConditions(this.kill_effect.conditions_source, proj, this); + } + this.state = State.linked; + } - if (this.kill_effect != null) { - linkConditions(this.kill_effect.conditions_source, proj, this); - } - this.state = State.linked; - } + @Override + public Image getIcon() { + return getProject().getIcon(icon_id); + } - @Override - public Image getIcon() { - return getProject().getIcon(icon_id); - } - - public Image getImage() { - return getProject().getImage(icon_id); - } - - @Override - public GameDataElement clone() { - Item clone = new Item(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.name = this.name; - clone.icon_id = this.icon_id; - clone.base_market_cost = this.base_market_cost; - clone.category = this.category; - if (clone.category != null) { - clone.category.addBacklink(clone); - } - clone.category_id = this.category_id; - clone.description = this.description; - clone.display_type = this.display_type; - clone.has_manual_price = this.has_manual_price; - if (this.equip_effect != null) { - clone.equip_effect = new EquipEffect(); - clone.equip_effect.damage_modifier = this.equip_effect.damage_modifier; - clone.equip_effect.critical_multiplier = this.equip_effect.critical_multiplier; - clone.equip_effect.damage_boost_max = this.equip_effect.damage_boost_max; - clone.equip_effect.damage_boost_min = this.equip_effect.damage_boost_min; - clone.equip_effect.increase_attack_chance = this.equip_effect.increase_attack_chance; - clone.equip_effect.increase_attack_cost = this.equip_effect.increase_attack_cost; - clone.equip_effect.increase_block_chance = this.equip_effect.increase_block_chance; - clone.equip_effect.increase_critical_skill = this.equip_effect.increase_critical_skill; - clone.equip_effect.increase_damage_resistance = this.equip_effect.increase_damage_resistance; - clone.equip_effect.increase_move_cost = this.equip_effect.increase_move_cost; - clone.equip_effect.increase_reequip_cost = this.equip_effect.increase_reequip_cost; - clone.equip_effect.increase_use_item_cost = this.equip_effect.increase_use_item_cost; - clone.equip_effect.max_ap_boost = this.equip_effect.max_ap_boost; - clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; - if (this.equip_effect.conditions != null) { - clone.equip_effect.conditions = new ArrayList<>(); - for (ConditionEffect c : this.equip_effect.conditions) { - ConditionEffect cclone = new ConditionEffect(); - cclone.magnitude = c.magnitude; - cclone.condition_id = c.condition_id; - cclone.condition = c.condition; - if (cclone.condition != null) { - cclone.condition.addBacklink(clone); - } - clone.equip_effect.conditions.add(cclone); - } - } - } - if (this.hit_effect != null) { - clone.hit_effect = new HitEffect(); - copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); - } - if (this.hit_received_effect != null) { - clone.hit_received_effect = new HitReceivedEffect(); - copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); - } - if (this.kill_effect != null) { - clone.kill_effect = new DeathEffect(); - copyDeathEffectValues(clone.kill_effect, this.kill_effect, clone); - } - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (this.category == oldOne) { - oldOne.removeBacklink(this); - this.category = (ItemCategory) newOne; - if (newOne != null) newOne.addBacklink(this); - } else { - if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (ConditionEffect c : this.equip_effect.conditions) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect c : this.hit_effect.conditions_source) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect c : this.hit_effect.conditions_target) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } + public Image getImage() { + return getProject().getImage(icon_id); + } - if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (TimedConditionEffect c : this.kill_effect.conditions_source) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map itemJson = new LinkedHashMap(); - itemJson.put("id", this.id); - if (this.icon_id != null) itemJson.put("iconID", this.icon_id); - if (this.name != null) itemJson.put("name", this.name); - if(this.display_type != null) itemJson.put("displaytype", this.display_type.toString()); - - if (this.has_manual_price != null) itemJson.put("hasManualPrice", this.has_manual_price); - if (this.base_market_cost != null) itemJson.put("baseMarketCost", this.base_market_cost); - if (this.category != null) { - itemJson.put("category", this.category.id); - } else if (this.category_id != null) { - itemJson.put("category", this.category_id); - } - if (this.description != null) itemJson.put("description", this.description); - if (this.equip_effect != null) { - Map equipEffectJson = new LinkedHashMap(); - itemJson.put("equipEffect", equipEffectJson); - if (this.equip_effect.damage_boost_min != null || this.equip_effect.damage_boost_max != null) { - Map damageJson = new LinkedHashMap(); - equipEffectJson.put("increaseAttackDamage", damageJson); - if (this.equip_effect.damage_boost_min != null) damageJson.put("min", this.equip_effect.damage_boost_min); - else damageJson.put("min", 0); - if (this.equip_effect.damage_boost_max != null) damageJson.put("max", this.equip_effect.damage_boost_max); - else damageJson.put("max", 0); - } - if (this.equip_effect.max_hp_boost != null) equipEffectJson.put("increaseMaxHP", this.equip_effect.max_hp_boost); - if (this.equip_effect.max_ap_boost != null) equipEffectJson.put("increaseMaxAP", this.equip_effect.max_ap_boost); - if (this.equip_effect.increase_move_cost != null) equipEffectJson.put("increaseMoveCost", this.equip_effect.increase_move_cost); - if (this.equip_effect.increase_use_item_cost != null) equipEffectJson.put("increaseUseItemCost", this.equip_effect.increase_use_item_cost); - if (this.equip_effect.increase_reequip_cost != null) equipEffectJson.put("increaseReequipCost", this.equip_effect.increase_reequip_cost); - if (this.equip_effect.increase_attack_cost != null) equipEffectJson.put("increaseAttackCost", this.equip_effect.increase_attack_cost); - if (this.equip_effect.increase_attack_chance != null) equipEffectJson.put("increaseAttackChance", this.equip_effect.increase_attack_chance); - if (this.equip_effect.increase_critical_skill != null) equipEffectJson.put("increaseCriticalSkill", this.equip_effect.increase_critical_skill); - if (this.equip_effect.increase_block_chance != null) equipEffectJson.put("increaseBlockChance", this.equip_effect.increase_block_chance); - if (this.equip_effect.increase_damage_resistance != null) equipEffectJson.put("increaseDamageResistance", this.equip_effect.increase_damage_resistance); - if (this.equip_effect.critical_multiplier != null) equipEffectJson.put("setCriticalMultiplier", this.equip_effect.critical_multiplier); - if (this.equip_effect.damage_modifier != null) equipEffectJson.put("setNonWeaponDamageModifier", this.equip_effect.damage_modifier); - if (this.equip_effect.conditions != null) { - List conditionsJson = new ArrayList(); - equipEffectJson.put("addedConditions", conditionsJson); - for (ConditionEffect condition : this.equip_effect.conditions) { - Map conditionJson = new LinkedHashMap(); - conditionsJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - } - } - } - if (this.hit_effect != null) { - Map hitEffectJson = new LinkedHashMap(); - itemJson.put("hitEffect", hitEffectJson); - if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.hit_received_effect != null) { - Map hitReceivedEffectJson = new LinkedHashMap(); - itemJson.put("hitReceivedEffect", hitReceivedEffectJson); - if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min != null) hpJson.put("min", this.hit_received_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max != null) hpJson.put("max", this.hit_received_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min != null) apJson.put("min", this.hit_received_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max != null) apJson.put("max", this.hit_received_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min_target != null) hpJson.put("min", this.hit_received_effect.hp_boost_min_target); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max_target != null) hpJson.put("max", this.hit_received_effect.hp_boost_max_target); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min_target != null) apJson.put("min", this.hit_received_effect.ap_boost_min_target); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max_target != null) apJson.put("max", this.hit_received_effect.ap_boost_max_target); - else apJson.put("max", 0); - } - if (this.hit_received_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_received_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.kill_effect != null) { - Map killEffectJson = new LinkedHashMap(); - if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { - itemJson.put("killEffect", killEffectJson); - } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { - itemJson.put("useEffect", killEffectJson); - } - if (this.kill_effect.hp_boost_min != null || this.kill_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - killEffectJson.put("increaseCurrentHP", hpJson); - if (this.kill_effect.hp_boost_min != null) hpJson.put("min", this.kill_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.kill_effect.hp_boost_max != null) hpJson.put("max", this.kill_effect.hp_boost_max); - else hpJson.put("min", 0); - } - if (this.kill_effect.ap_boost_min != null || this.kill_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - killEffectJson.put("increaseCurrentAP", apJson); - if (this.kill_effect.ap_boost_min != null) apJson.put("min", this.kill_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.kill_effect.ap_boost_max != null) apJson.put("max", this.kill_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.kill_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - killEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.kill_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - return itemJson; - } + @Override + public GameDataElement clone() { + Item clone = new Item(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.name = this.name; + clone.icon_id = this.icon_id; + clone.base_market_cost = this.base_market_cost; + clone.category = this.category; + if (clone.category != null) { + clone.category.addBacklink(clone); + } + clone.category_id = this.category_id; + clone.description = this.description; + clone.display_type = this.display_type; + clone.has_manual_price = this.has_manual_price; + if (this.equip_effect != null) { + clone.equip_effect = new EquipEffect(); + clone.equip_effect.damage_modifier = this.equip_effect.damage_modifier; + clone.equip_effect.critical_multiplier = this.equip_effect.critical_multiplier; + clone.equip_effect.damage_boost_max = this.equip_effect.damage_boost_max; + clone.equip_effect.damage_boost_min = this.equip_effect.damage_boost_min; + clone.equip_effect.increase_attack_chance = this.equip_effect.increase_attack_chance; + clone.equip_effect.increase_attack_cost = this.equip_effect.increase_attack_cost; + clone.equip_effect.increase_block_chance = this.equip_effect.increase_block_chance; + clone.equip_effect.increase_critical_skill = this.equip_effect.increase_critical_skill; + clone.equip_effect.increase_damage_resistance = this.equip_effect.increase_damage_resistance; + clone.equip_effect.increase_move_cost = this.equip_effect.increase_move_cost; + clone.equip_effect.increase_reequip_cost = this.equip_effect.increase_reequip_cost; + clone.equip_effect.increase_use_item_cost = this.equip_effect.increase_use_item_cost; + clone.equip_effect.max_ap_boost = this.equip_effect.max_ap_boost; + clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; + if (this.equip_effect.conditions != null) { + clone.equip_effect.conditions = new ArrayList<>(); + for (ConditionEffect c : this.equip_effect.conditions) { + ConditionEffect cclone = new ConditionEffect(); + cclone.magnitude = c.magnitude; + cclone.condition_id = c.condition_id; + cclone.condition = c.condition; + if (cclone.condition != null) { + cclone.condition.addBacklink(clone); + } + clone.equip_effect.conditions.add(cclone); + } + } + } + if (this.hit_effect != null) { + clone.hit_effect = new HitEffect(); + copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); + } + if (this.hit_received_effect != null) { + clone.hit_received_effect = new HitReceivedEffect(); + copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); + } + if (this.kill_effect != null) { + clone.kill_effect = new DeathEffect(); + copyDeathEffectValues(clone.kill_effect, this.kill_effect, clone); + } + return clone; + } - @Override - public String getProjectFilename() { - return "itemlist_"+getProject().name+".json"; - } + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (this.category == oldOne) { + oldOne.removeBacklink(this); + this.category = (ItemCategory) newOne; + if (newOne != null) newOne.addBacklink(this); + } else { + if (this.equip_effect != null && this.equip_effect.conditions != null) { + for (ConditionEffect c : this.equip_effect.conditions) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + if (this.hit_effect != null && this.hit_effect.conditions_source != null) { + for (TimedConditionEffect c : this.hit_effect.conditions_source) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + if (this.hit_effect != null && this.hit_effect.conditions_target != null) { + for (TimedConditionEffect c : this.hit_effect.conditions_target) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } - public Integer computePrice() { - int price = 0; - if (category != null && category.action_type != null) { - if (category.action_type == ItemCategory.ActionType.use) { - price += kill_effect == null ? 0 : calculateUseCost(); - } else if (category.action_type == ItemCategory.ActionType.equip) { - price += equip_effect == null ? 0 : calculateEquipCost(isWeapon());; - price += hit_effect == null ? 0 : calculateHitCost(); - price += kill_effect == null ? 0 : calculateKillCost(); - } - } - return Math.max(1, price); - } - - public int zeroForNull(Integer val) { - return val == null ? 0 : val; - } - - public double zeroForNull(Double val) { - return val == null ? 0 : val; - } - - public boolean isWeapon() { - return category != null && category.action_type != null && category.action_type == ItemCategory.ActionType.equip && category.slot != null && category.slot == ItemCategory.InventorySlot.weapon; - } - - public int calculateUseCost() { - final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; - if (averageHPBoost == 0) return 0; - return (int) (0.1*Math.signum(averageHPBoost)*Math.pow(Math.abs(averageHPBoost), 2) + 3*averageHPBoost); - } + if (this.kill_effect != null && this.kill_effect.conditions_source != null) { + for (TimedConditionEffect c : this.kill_effect.conditions_source) { + if (c.condition == oldOne) { + oldOne.removeBacklink(this); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + } + } - public int calculateEquipCost(boolean isWeapon) { - final int costBC = (int) (3*Math.pow(Math.max(0, zeroForNull(equip_effect.increase_block_chance)), 2.5) + 28*zeroForNull(equip_effect.increase_block_chance)); - final int costAC = (int) (0.4*Math.pow(Math.max(0,zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6*Math.pow(Math.abs(Math.min(0,zeroForNull(equip_effect.increase_attack_chance))),2.7)); - final int costAP = isWeapon ? - (int) (0.2*Math.pow(10.0f/zeroForNull(equip_effect.increase_attack_cost), 8) - 25*zeroForNull(equip_effect.increase_attack_cost)) - :-3125 * zeroForNull(equip_effect.increase_attack_cost); - final int costDR = 1325 * zeroForNull(equip_effect.increase_damage_resistance); - final int costDMG_Min = isWeapon ? - (int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 2.5)) - :(int) (10*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 3) + zeroForNull(equip_effect.damage_boost_min)*80); - final int costDMG_Max = isWeapon ? - (int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 2.1)) - :(int) (2*Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 3) + zeroForNull(equip_effect.damage_boost_max)*20); - final int costCS = (int) (2.2*Math.pow(zeroForNull(equip_effect.increase_critical_skill), 3)); - final int costCM = (int) (50*Math.pow(Math.max(0, zeroForNull(equip_effect.critical_multiplier)), 2)); + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map itemJson = new LinkedHashMap(); + itemJson.put("id", this.id); + if (this.icon_id != null) itemJson.put("iconID", this.icon_id); + if (this.name != null) itemJson.put("name", this.name); + if (this.display_type != null) itemJson.put("displaytype", this.display_type.toString()); - final int costMaxHP = (int) (30*Math.pow(Math.max(0,zeroForNull(equip_effect.max_hp_boost)), 1.2) + 70*zeroForNull(equip_effect.max_hp_boost)); - final int costMaxAP = (int) (50*Math.pow(Math.max(0,zeroForNull(equip_effect.max_ap_boost)), 3) + 750*zeroForNull(equip_effect.max_ap_boost)); - final int costMovement = (int) (510*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_move_cost)), 2.5) - 350*zeroForNull(equip_effect.increase_move_cost)); - final int costUseItem = (int)(915*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_use_item_cost)), 3) - 430*zeroForNull(equip_effect.increase_use_item_cost)); - final int costReequip = (int)(450*Math.pow(Math.max(0,-zeroForNull(equip_effect.increase_reequip_cost)), 2) - 250*zeroForNull(equip_effect.increase_reequip_cost)); + if (this.has_manual_price != null) itemJson.put("hasManualPrice", this.has_manual_price); + if (this.base_market_cost != null) itemJson.put("baseMarketCost", this.base_market_cost); + if (this.category != null) { + itemJson.put("category", this.category.id); + } else if (this.category_id != null) { + itemJson.put("category", this.category_id); + } + if (this.description != null) itemJson.put("description", this.description); + if (this.equip_effect != null) { + Map equipEffectJson = new LinkedHashMap(); + itemJson.put("equipEffect", equipEffectJson); + if (this.equip_effect.damage_boost_min != null || this.equip_effect.damage_boost_max != null) { + Map damageJson = new LinkedHashMap(); + equipEffectJson.put("increaseAttackDamage", damageJson); + if (this.equip_effect.damage_boost_min != null) + damageJson.put("min", this.equip_effect.damage_boost_min); + else damageJson.put("min", 0); + if (this.equip_effect.damage_boost_max != null) + damageJson.put("max", this.equip_effect.damage_boost_max); + else damageJson.put("max", 0); + } + if (this.equip_effect.max_hp_boost != null) + equipEffectJson.put("increaseMaxHP", this.equip_effect.max_hp_boost); + if (this.equip_effect.max_ap_boost != null) + equipEffectJson.put("increaseMaxAP", this.equip_effect.max_ap_boost); + if (this.equip_effect.increase_move_cost != null) + equipEffectJson.put("increaseMoveCost", this.equip_effect.increase_move_cost); + if (this.equip_effect.increase_use_item_cost != null) + equipEffectJson.put("increaseUseItemCost", this.equip_effect.increase_use_item_cost); + if (this.equip_effect.increase_reequip_cost != null) + equipEffectJson.put("increaseReequipCost", this.equip_effect.increase_reequip_cost); + if (this.equip_effect.increase_attack_cost != null) + equipEffectJson.put("increaseAttackCost", this.equip_effect.increase_attack_cost); + if (this.equip_effect.increase_attack_chance != null) + equipEffectJson.put("increaseAttackChance", this.equip_effect.increase_attack_chance); + if (this.equip_effect.increase_critical_skill != null) + equipEffectJson.put("increaseCriticalSkill", this.equip_effect.increase_critical_skill); + if (this.equip_effect.increase_block_chance != null) + equipEffectJson.put("increaseBlockChance", this.equip_effect.increase_block_chance); + if (this.equip_effect.increase_damage_resistance != null) + equipEffectJson.put("increaseDamageResistance", this.equip_effect.increase_damage_resistance); + if (this.equip_effect.critical_multiplier != null) + equipEffectJson.put("setCriticalMultiplier", this.equip_effect.critical_multiplier); + if (this.equip_effect.damage_modifier != null) + equipEffectJson.put("setNonWeaponDamageModifier", this.equip_effect.damage_modifier); + if (this.equip_effect.conditions != null) { + List conditionsJson = new ArrayList(); + equipEffectJson.put("addedConditions", conditionsJson); + for (ConditionEffect condition : this.equip_effect.conditions) { + Map conditionJson = new LinkedHashMap(); + conditionsJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + } + } + } + if (this.hit_effect != null) { + Map hitEffectJson = new LinkedHashMap(); + itemJson.put("hitEffect", hitEffectJson); + if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedConditionEffect condition : this.hit_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitEffectJson.put("conditionsTarget", conditionsTargetJson); + for (TimedConditionEffect condition : this.hit_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.hit_received_effect != null) { + Map hitReceivedEffectJson = new LinkedHashMap(); + itemJson.put("hitReceivedEffect", hitReceivedEffectJson); + if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min != null) + hpJson.put("min", this.hit_received_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max != null) + hpJson.put("max", this.hit_received_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min != null) + apJson.put("min", this.hit_received_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max != null) + apJson.put("max", this.hit_received_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min_target != null) + hpJson.put("min", this.hit_received_effect.hp_boost_min_target); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max_target != null) + hpJson.put("max", this.hit_received_effect.hp_boost_max_target); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min_target != null) + apJson.put("min", this.hit_received_effect.ap_boost_min_target); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max_target != null) + apJson.put("max", this.hit_received_effect.ap_boost_max_target); + else apJson.put("max", 0); + } + if (this.hit_received_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_received_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); + for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.kill_effect != null) { + Map killEffectJson = new LinkedHashMap(); + if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { + itemJson.put("killEffect", killEffectJson); + } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { + itemJson.put("useEffect", killEffectJson); + } + if (this.kill_effect.hp_boost_min != null || this.kill_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + killEffectJson.put("increaseCurrentHP", hpJson); + if (this.kill_effect.hp_boost_min != null) hpJson.put("min", this.kill_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.kill_effect.hp_boost_max != null) hpJson.put("max", this.kill_effect.hp_boost_max); + else hpJson.put("min", 0); + } + if (this.kill_effect.ap_boost_min != null || this.kill_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + killEffectJson.put("increaseCurrentAP", apJson); + if (this.kill_effect.ap_boost_min != null) apJson.put("min", this.kill_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.kill_effect.ap_boost_max != null) apJson.put("max", this.kill_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.kill_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + killEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedConditionEffect condition : this.kill_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + return itemJson; + } - return costBC + costAC + costAP + costDR + costDMG_Min + costDMG_Max + costCS + costCM - + costMaxHP + costMaxAP - + costMovement + costUseItem + costReequip; - } - + @Override + public String getProjectFilename() { + return "itemlist_" + getProject().name + ".json"; + } - public int calculateHitCost() { - final float averageHPBoost = (zeroForNull(hit_effect.hp_boost_min) + zeroForNull(hit_effect.hp_boost_max)) / 2.0f; - final float averageAPBoost = (zeroForNull(hit_effect.ap_boost_min) + zeroForNull(hit_effect.ap_boost_max)) / 2.0f; - if (averageHPBoost == 0 && averageAPBoost == 0) return 0; + public Integer computePrice() { + int price = 0; + if (category != null && category.action_type != null) { + if (category.action_type == ItemCategory.ActionType.use) { + price += kill_effect == null ? 0 : calculateUseCost(); + } else if (category.action_type == ItemCategory.ActionType.equip) { + price += equip_effect == null ? 0 : calculateEquipCost(isWeapon()); + ; + price += hit_effect == null ? 0 : calculateHitCost(); + price += kill_effect == null ? 0 : calculateKillCost(); + } + } + return Math.max(1, price); + } - final int costBoostHP = (int)(2770*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); - final int costBoostAP = (int)(3100*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); - return costBoostHP + costBoostAP; - } + public int zeroForNull(Integer val) { + return val == null ? 0 : val; + } - public int calculateKillCost() { - final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; - final float averageAPBoost = (zeroForNull(kill_effect.ap_boost_min) + zeroForNull(kill_effect.ap_boost_max)) / 2.0f; - if (averageHPBoost == 0 && averageAPBoost == 0) return 0; + public double zeroForNull(Double val) { + return val == null ? 0 : val; + } - final int costBoostHP = (int)(923*Math.pow(Math.max(0,averageHPBoost), 2.5) + 450*averageHPBoost); - final int costBoostAP = (int)(1033*Math.pow(Math.max(0,averageAPBoost), 2.5) + 300*averageAPBoost); - return costBoostHP + costBoostAP; - } + public boolean isWeapon() { + return category != null && category.action_type != null && category.action_type == ItemCategory.ActionType.equip && category.slot != null && category.slot == ItemCategory.InventorySlot.weapon; + } + + public int calculateUseCost() { + final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; + if (averageHPBoost == 0) return 0; + return (int) (0.1 * Math.signum(averageHPBoost) * Math.pow(Math.abs(averageHPBoost), 2) + 3 * averageHPBoost); + } + + public int calculateEquipCost(boolean isWeapon) { + final int costBC = (int) (3 * Math.pow(Math.max(0, zeroForNull(equip_effect.increase_block_chance)), 2.5) + 28 * zeroForNull(equip_effect.increase_block_chance)); + final int costAC = (int) (0.4 * Math.pow(Math.max(0, zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6 * Math.pow(Math.abs(Math.min(0, zeroForNull(equip_effect.increase_attack_chance))), 2.7)); + final int costAP = isWeapon ? + (int) (0.2 * Math.pow(10.0f / zeroForNull(equip_effect.increase_attack_cost), 8) - 25 * zeroForNull(equip_effect.increase_attack_cost)) + : -3125 * zeroForNull(equip_effect.increase_attack_cost); + final int costDR = 1325 * zeroForNull(equip_effect.increase_damage_resistance); + final int costDMG_Min = isWeapon ? + (int) (10 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 2.5)) + : (int) (10 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_min)), 3) + zeroForNull(equip_effect.damage_boost_min) * 80); + final int costDMG_Max = isWeapon ? + (int) (2 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 2.1)) + : (int) (2 * Math.pow(Math.max(0, zeroForNull(equip_effect.damage_boost_max)), 3) + zeroForNull(equip_effect.damage_boost_max) * 20); + final int costCS = (int) (2.2 * Math.pow(zeroForNull(equip_effect.increase_critical_skill), 3)); + final int costCM = (int) (50 * Math.pow(Math.max(0, zeroForNull(equip_effect.critical_multiplier)), 2)); + + final int costMaxHP = (int) (30 * Math.pow(Math.max(0, zeroForNull(equip_effect.max_hp_boost)), 1.2) + 70 * zeroForNull(equip_effect.max_hp_boost)); + final int costMaxAP = (int) (50 * Math.pow(Math.max(0, zeroForNull(equip_effect.max_ap_boost)), 3) + 750 * zeroForNull(equip_effect.max_ap_boost)); + final int costMovement = (int) (510 * Math.pow(Math.max(0, -zeroForNull(equip_effect.increase_move_cost)), 2.5) - 350 * zeroForNull(equip_effect.increase_move_cost)); + final int costUseItem = (int) (915 * Math.pow(Math.max(0, -zeroForNull(equip_effect.increase_use_item_cost)), 3) - 430 * zeroForNull(equip_effect.increase_use_item_cost)); + final int costReequip = (int) (450 * Math.pow(Math.max(0, -zeroForNull(equip_effect.increase_reequip_cost)), 2) - 250 * zeroForNull(equip_effect.increase_reequip_cost)); + + return costBC + costAC + costAP + costDR + costDMG_Min + costDMG_Max + costCS + costCM + + costMaxHP + costMaxAP + + costMovement + costUseItem + costReequip; + } + + + public int calculateHitCost() { + final float averageHPBoost = (zeroForNull(hit_effect.hp_boost_min) + zeroForNull(hit_effect.hp_boost_max)) / 2.0f; + final float averageAPBoost = (zeroForNull(hit_effect.ap_boost_min) + zeroForNull(hit_effect.ap_boost_max)) / 2.0f; + if (averageHPBoost == 0 && averageAPBoost == 0) return 0; + + final int costBoostHP = (int) (2770 * Math.pow(Math.max(0, averageHPBoost), 2.5) + 450 * averageHPBoost); + final int costBoostAP = (int) (3100 * Math.pow(Math.max(0, averageAPBoost), 2.5) + 300 * averageAPBoost); + return costBoostHP + costBoostAP; + } + + public int calculateKillCost() { + final float averageHPBoost = (zeroForNull(kill_effect.hp_boost_min) + zeroForNull(kill_effect.hp_boost_max)) / 2.0f; + final float averageAPBoost = (zeroForNull(kill_effect.ap_boost_min) + zeroForNull(kill_effect.ap_boost_max)) / 2.0f; + if (averageHPBoost == 0 && averageAPBoost == 0) return 0; + + final int costBoostHP = (int) (923 * Math.pow(Math.max(0, averageHPBoost), 2.5) + 450 * averageHPBoost); + final int costBoostAP = (int) (1033 * Math.pow(Math.max(0, averageAPBoost), 2.5) + 300 * averageAPBoost); + return costBoostHP + costBoostAP; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java index ecb0f8d..7c8db56 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java @@ -1,6 +1,13 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import javax.imageio.ImageIO; +import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -9,311 +16,304 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import javax.imageio.ImageIO; - -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; - public class ItemCategory extends JSONElement { - private static final long serialVersionUID = -348864002519568300L; - - public static final String ICON_NO_SLOT_RES = "/com/gpl/rpg/atcontentstudio/img/equip_square.png"; - public static final String ICON_BODY_RES = "/com/gpl/rpg/atcontentstudio/img/equip_body.png"; - public static final String ICON_FEET_RES = "/com/gpl/rpg/atcontentstudio/img/equip_feet.png"; - public static final String ICON_HAND_RES = "/com/gpl/rpg/atcontentstudio/img/equip_hand.png"; - public static final String ICON_HEAD_RES = "/com/gpl/rpg/atcontentstudio/img/equip_head.png"; - public static final String ICON_NECK_RES = "/com/gpl/rpg/atcontentstudio/img/equip_neck.png"; - public static final String ICON_RING_RES = "/com/gpl/rpg/atcontentstudio/img/equip_ring.png"; - public static final String ICON_SHIELD_RES = "/com/gpl/rpg/atcontentstudio/img/equip_shield.png"; - public static final String ICON_WEAPON_RES = "/com/gpl/rpg/atcontentstudio/img/equip_weapon.png"; + private static final long serialVersionUID = -348864002519568300L; - public static Image no_slot_image = null; - public static Image no_slot_icon = null; + public static final String ICON_NO_SLOT_RES = "/com/gpl/rpg/atcontentstudio/img/equip_square.png"; + public static final String ICON_BODY_RES = "/com/gpl/rpg/atcontentstudio/img/equip_body.png"; + public static final String ICON_FEET_RES = "/com/gpl/rpg/atcontentstudio/img/equip_feet.png"; + public static final String ICON_HAND_RES = "/com/gpl/rpg/atcontentstudio/img/equip_hand.png"; + public static final String ICON_HEAD_RES = "/com/gpl/rpg/atcontentstudio/img/equip_head.png"; + public static final String ICON_NECK_RES = "/com/gpl/rpg/atcontentstudio/img/equip_neck.png"; + public static final String ICON_RING_RES = "/com/gpl/rpg/atcontentstudio/img/equip_ring.png"; + public static final String ICON_SHIELD_RES = "/com/gpl/rpg/atcontentstudio/img/equip_shield.png"; + public static final String ICON_WEAPON_RES = "/com/gpl/rpg/atcontentstudio/img/equip_weapon.png"; - public static Image body_image = null; - public static Image body_icon = null; + public static Image no_slot_image = null; + public static Image no_slot_icon = null; - public static Image feet_image = null; - public static Image feet_icon = null; + public static Image body_image = null; + public static Image body_icon = null; - public static Image hand_image = null; - public static Image hand_icon = null; + public static Image feet_image = null; + public static Image feet_icon = null; - public static Image head_image = null; - public static Image head_icon = null; + public static Image hand_image = null; + public static Image hand_icon = null; - public static Image neck_image = null; - public static Image neck_icon = null; + public static Image head_image = null; + public static Image head_icon = null; - public static Image ring_image = null; - public static Image ring_icon = null; + public static Image neck_image = null; + public static Image neck_icon = null; - public static Image shield_image = null; - public static Image shield_icon = null; + public static Image ring_image = null; + public static Image ring_icon = null; - public static Image weapon_image = null; - public static Image weapon_icon = null; - - - //Available from init state - //public String id = null; inherited. - public String name = null; - public InventorySlot slot = null; - - //Available from parsed state - public ActionType action_type = null; - public Size size = null; - - //Available from linked state - //None - - public static enum ActionType { - none, - use, - equip - } - - public static enum Size { - none, - light, - std, - large - } - - public static enum InventorySlot { - weapon, - shield, - head, - body, - hand, - feet, - neck, - leftring, - rightring - } + public static Image shield_image = null; + public static Image shield_icon = null; - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+name+" ("+id+")"; - } + public static Image weapon_image = null; + public static Image weapon_icon = null; - public static String getStaticDesc() { - return "Item categories"; - } - - - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List itemCategories = (List) parser.parse(reader); - for (Object obj : itemCategories) { - Map itemCatJson = (Map)obj; - ItemCategory itemCat = fromJson(itemCatJson); - itemCat.jsonFile = jsonFile; - itemCat.parent = category; - if (itemCat.getDataType() == GameSource.Type.created || itemCat.getDataType() == GameSource.Type.altered) { - itemCat.writable = true; - } - category.add(itemCat); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static ItemCategory fromJson(String jsonString) throws ParseException { - Map itemCatJson = (Map) new JSONParser().parse(jsonString); - ItemCategory item = fromJson(itemCatJson); - item.parse(itemCatJson); - return item; - } - - @SuppressWarnings("rawtypes") - public static ItemCategory fromJson(Map itemCatJson) { - ItemCategory itemCat = new ItemCategory(); - itemCat.id = (String) itemCatJson.get("id"); - itemCat.name = (String) itemCatJson.get("name"); - if (itemCatJson.get("inventorySlot") != null) itemCat.slot = InventorySlot.valueOf((String) itemCatJson.get("inventorySlot")); - return itemCat; - } - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map itemCatJson) { - if (itemCatJson.get("actionType") != null) action_type = ActionType.valueOf((String) itemCatJson.get("actionType")); - if (itemCatJson.get("size") != null) size = Size.valueOf((String) itemCatJson.get("size")); - this.state = State.parsed; - - } - - @Override - public void link() { - if (!this.linkCheck()) return; - - //Nothing to link to :D - this.state = State.linked; - } - - @Override - public Image getIcon() { - return getIcon(this.slot); - } - - public Image getImage() { - return getImage(this.slot); - } - - public static Image getImage(InventorySlot slot) { - if (slot == null) { - return getImage(ICON_NO_SLOT_RES, no_slot_image, "no_slot_image"); - } - switch (slot) { - case body: - return getImage(ICON_BODY_RES, body_image, "body_image"); - case feet: - return getImage(ICON_FEET_RES, feet_image, "feet_image"); - case hand: - return getImage(ICON_HAND_RES, hand_image, "hand_image"); - case head: - return getImage(ICON_HEAD_RES, head_image, "head_image"); - case leftring: - case rightring: - return getImage(ICON_RING_RES, ring_image, "ring_image"); - case neck: - return getImage(ICON_NECK_RES, neck_image, "neck_image"); - case shield: - return getImage(ICON_SHIELD_RES, shield_image, "shield_image"); - case weapon: - return getImage(ICON_WEAPON_RES, weapon_image, "weapon_image"); - default: - return getImage(ICON_NO_SLOT_RES, no_slot_image, "no_slot_image"); - } - } - - public static Image getIcon(InventorySlot slot) { - if (slot == null) { - return getIcon(ICON_NO_SLOT_RES, no_slot_image, no_slot_icon, "no_slot_image", "no_slot_icon"); - } - switch (slot) { - case body: - return getIcon(ICON_BODY_RES, body_image, body_icon, "body_image", "body_icon"); - case feet: - return getIcon(ICON_FEET_RES, feet_image, feet_icon, "feet_image", "feet_icon"); - case hand: - return getIcon(ICON_HAND_RES, hand_image, hand_icon, "hand_image", "hand_icon"); - case head: - return getIcon(ICON_HEAD_RES, head_image, head_icon, "head_image", "head_icon"); - case leftring: - case rightring: - return getIcon(ICON_RING_RES, ring_image, ring_icon, "ring_image", "ring_icon"); - case neck: - return getIcon(ICON_NECK_RES, neck_image, neck_icon, "neck_image", "neck_icon"); - case shield: - return getIcon(ICON_SHIELD_RES, shield_image, shield_icon, "shield_image", "shield_icon"); - case weapon: - return getIcon(ICON_WEAPON_RES, weapon_image, weapon_icon, "weapon_image", "weapon_icon"); - default: - return getIcon(ICON_NO_SLOT_RES, no_slot_image, no_slot_icon, "no_slot_image", "no_slot_icon"); - } - } - public static Image getImage(String res, Image img, String fieldName) { - if (img == null) { - try { - img = ImageIO.read(ItemCategory.class.getResourceAsStream(res)); - ItemCategory.class.getField(fieldName).set(null, img); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Failed to load item category icon "+res); - e.printStackTrace(); - } - } - return img; - } - - public static Image getIcon(String res, Image img, Image icon, String imgFieldName, String iconFieldName) { - if (icon == null) { - icon = getImage(res, img, imgFieldName).getScaledInstance(16, 16, Image.SCALE_SMOOTH); - try { - ItemCategory.class.getField(iconFieldName).set(null, icon); - } catch (IllegalArgumentException e) { - e.printStackTrace(); - } catch (SecurityException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } - } - return icon; - } - - @Override - public GameDataElement clone() { - ItemCategory clone = new ItemCategory(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.name = this.name; - clone.size = this.size; - clone.slot = this.slot; - clone.action_type = this.action_type; - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - // Nothing to link to. - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map itemCatJson = new LinkedHashMap(); - itemCatJson.put("id", this.id); - if (this.name != null) itemCatJson.put("name", this.name); - if (this.action_type != null) itemCatJson.put("actionType", this.action_type.toString()); - if (this.size != null) itemCatJson.put("size", this.size.toString()); - if (this.slot != null) itemCatJson.put("inventorySlot", this.slot.toString()); - return itemCatJson; - } - + //Available from init state + //public String id = null; inherited. + public String name = null; + public InventorySlot slot = null; + + //Available from parsed state + public ActionType action_type = null; + public Size size = null; + + //Available from linked state + //None + + public static enum ActionType { + none, + use, + equip + } + + public static enum Size { + none, + light, + std, + large + } + + public static enum InventorySlot { + weapon, + shield, + head, + body, + hand, + feet, + neck, + leftring, + rightring + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + name + " (" + id + ")"; + } + + public static String getStaticDesc() { + return "Item categories"; + } + + + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List itemCategories = (List) parser.parse(reader); + for (Object obj : itemCategories) { + Map itemCatJson = (Map) obj; + ItemCategory itemCat = fromJson(itemCatJson); + itemCat.jsonFile = jsonFile; + itemCat.parent = category; + if (itemCat.getDataType() == GameSource.Type.created || itemCat.getDataType() == GameSource.Type.altered) { + itemCat.writable = true; + } + category.add(itemCat); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static ItemCategory fromJson(String jsonString) throws ParseException { + Map itemCatJson = (Map) new JSONParser().parse(jsonString); + ItemCategory item = fromJson(itemCatJson); + item.parse(itemCatJson); + return item; + } + + @SuppressWarnings("rawtypes") + public static ItemCategory fromJson(Map itemCatJson) { + ItemCategory itemCat = new ItemCategory(); + itemCat.id = (String) itemCatJson.get("id"); + itemCat.name = (String) itemCatJson.get("name"); + if (itemCatJson.get("inventorySlot") != null) + itemCat.slot = InventorySlot.valueOf((String) itemCatJson.get("inventorySlot")); + return itemCat; + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map itemCatJson) { + if (itemCatJson.get("actionType") != null) + action_type = ActionType.valueOf((String) itemCatJson.get("actionType")); + if (itemCatJson.get("size") != null) size = Size.valueOf((String) itemCatJson.get("size")); + this.state = State.parsed; + + } + + @Override + public void link() { + if (!this.linkCheck()) return; + + //Nothing to link to :D + this.state = State.linked; + } + + @Override + public Image getIcon() { + return getIcon(this.slot); + } + + public Image getImage() { + return getImage(this.slot); + } + + public static Image getImage(InventorySlot slot) { + if (slot == null) { + return getImage(ICON_NO_SLOT_RES, no_slot_image, "no_slot_image"); + } + switch (slot) { + case body: + return getImage(ICON_BODY_RES, body_image, "body_image"); + case feet: + return getImage(ICON_FEET_RES, feet_image, "feet_image"); + case hand: + return getImage(ICON_HAND_RES, hand_image, "hand_image"); + case head: + return getImage(ICON_HEAD_RES, head_image, "head_image"); + case leftring: + case rightring: + return getImage(ICON_RING_RES, ring_image, "ring_image"); + case neck: + return getImage(ICON_NECK_RES, neck_image, "neck_image"); + case shield: + return getImage(ICON_SHIELD_RES, shield_image, "shield_image"); + case weapon: + return getImage(ICON_WEAPON_RES, weapon_image, "weapon_image"); + default: + return getImage(ICON_NO_SLOT_RES, no_slot_image, "no_slot_image"); + } + } + + public static Image getIcon(InventorySlot slot) { + if (slot == null) { + return getIcon(ICON_NO_SLOT_RES, no_slot_image, no_slot_icon, "no_slot_image", "no_slot_icon"); + } + switch (slot) { + case body: + return getIcon(ICON_BODY_RES, body_image, body_icon, "body_image", "body_icon"); + case feet: + return getIcon(ICON_FEET_RES, feet_image, feet_icon, "feet_image", "feet_icon"); + case hand: + return getIcon(ICON_HAND_RES, hand_image, hand_icon, "hand_image", "hand_icon"); + case head: + return getIcon(ICON_HEAD_RES, head_image, head_icon, "head_image", "head_icon"); + case leftring: + case rightring: + return getIcon(ICON_RING_RES, ring_image, ring_icon, "ring_image", "ring_icon"); + case neck: + return getIcon(ICON_NECK_RES, neck_image, neck_icon, "neck_image", "neck_icon"); + case shield: + return getIcon(ICON_SHIELD_RES, shield_image, shield_icon, "shield_image", "shield_icon"); + case weapon: + return getIcon(ICON_WEAPON_RES, weapon_image, weapon_icon, "weapon_image", "weapon_icon"); + default: + return getIcon(ICON_NO_SLOT_RES, no_slot_image, no_slot_icon, "no_slot_image", "no_slot_icon"); + } + } + + public static Image getImage(String res, Image img, String fieldName) { + if (img == null) { + try { + img = ImageIO.read(ItemCategory.class.getResourceAsStream(res)); + ItemCategory.class.getField(fieldName).set(null, img); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Failed to load item category icon " + res); + e.printStackTrace(); + } + } + return img; + } + + public static Image getIcon(String res, Image img, Image icon, String imgFieldName, String iconFieldName) { + if (icon == null) { + icon = getImage(res, img, imgFieldName).getScaledInstance(16, 16, Image.SCALE_SMOOTH); + try { + ItemCategory.class.getField(iconFieldName).set(null, icon); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (SecurityException e) { + e.printStackTrace(); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (NoSuchFieldException e) { + e.printStackTrace(); + } + } + return icon; + } + + @Override + public GameDataElement clone() { + ItemCategory clone = new ItemCategory(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.name = this.name; + clone.size = this.size; + clone.slot = this.slot; + clone.action_type = this.action_type; + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + // Nothing to link to. + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map itemCatJson = new LinkedHashMap(); + itemCatJson.put("id", this.id); + if (this.name != null) itemCatJson.put("name", this.name); + if (this.action_type != null) itemCatJson.put("actionType", this.action_type.toString()); + if (this.size != null) itemCatJson.put("size", this.size.toString()); + if (this.slot != null) itemCatJson.put("inventorySlot", this.slot.toString()); + return itemCatJson; + } + + + @Override + public String getProjectFilename() { + return "itemcategories_" + getProject().name + ".json"; + } + - @Override - public String getProjectFilename() { - return "itemcategories_"+getProject().name+".json"; - } - - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java index 3910742..b044670 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java @@ -1,133 +1,128 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.StringWriter; -import java.util.List; -import java.util.Map; - -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.SaveEvent; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.io.*; +import java.util.List; +import java.util.Map; public abstract class JSONElement extends GameDataElement { - private static final long serialVersionUID = -8015398814080503982L; + private static final long serialVersionUID = -8015398814080503982L; - //Available from state init. - public File jsonFile; - - @SuppressWarnings("rawtypes") - public void parse() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return; - } - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List gameDataElements = (List) parser.parse(reader); - for (Object obj : gameDataElements) { - Map jsonObj = (Map)obj; - String id = (String) jsonObj.get("id"); - try { - if (id != null && id.equals(this.id )) { - this.parse(jsonObj); - this.state = State.parsed; - break; - } - } - catch(Exception e){ - System.out.println("Error in ID: " + id); - System.out.println(e.getMessage()); - } - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IllegalArgumentException e) { - System.out.println(id); - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - public abstract void parse(@SuppressWarnings("rawtypes") Map jsonObj); - - @SuppressWarnings("rawtypes") - public abstract Map toJson(); - public String toJsonString() { - StringWriter writer = new JsonPrettyWriter(); - try { - JSONObject.writeJSONString(this.toJson(), writer); - } catch (IOException e) { - //Impossible with a StringWriter - } - return writer.toString(); - } - - - @Override - public GameDataSet getDataSet() { - if (parent == null) { - System.out.println("blerf."); - } - return parent.getDataSet(); - } - - public void save() { - if (this.getParent() instanceof GameDataCategory && writable) { - ((GameDataCategory)this.getParent()).save(this.jsonFile); - } - } - - /** - * Returns null if save occurred (no notable events). - */ - public List attemptSave() { - List events = ((GameDataCategory)this.getParent()).attemptSave(true, this.jsonFile.getName()); - if (events == null || events.isEmpty()) { - return null; - } - if (events.size() == 1 && events.get(0).type == SaveEvent.Type.alsoSave && events.get(0).target == this) { - save(); - return null; - } - return events; - } + //Available from state init. + public File jsonFile; - public static Integer getInteger(Number n) { - return n == null ? null : n.intValue(); - } + @SuppressWarnings("rawtypes") + public void parse() { + if (this.state == State.created || this.state == State.modified || this.state == State.saved) { + //This type of state is unrelated to parsing/linking. + return; + } + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List gameDataElements = (List) parser.parse(reader); + for (Object obj : gameDataElements) { + Map jsonObj = (Map) obj; + String id = (String) jsonObj.get("id"); + try { + if (id != null && id.equals(this.id)) { + this.parse(jsonObj); + this.state = State.parsed; + break; + } + } catch (Exception e) { + System.out.println("Error in ID: " + id); + System.out.println(e.getMessage()); + } + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IllegalArgumentException e) { + System.out.println(id); + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } - public static Double getDouble(Number n) { - return n == null ? null : n.doubleValue(); - } - - public static Double parseChance(String s) { - if (s.equals("100")) return 100d; + } + + public abstract void parse(@SuppressWarnings("rawtypes") Map jsonObj); + + @SuppressWarnings("rawtypes") + public abstract Map toJson(); + + public String toJsonString() { + StringWriter writer = new JsonPrettyWriter(); + try { + JSONObject.writeJSONString(this.toJson(), writer); + } catch (IOException e) { + //Impossible with a StringWriter + } + return writer.toString(); + } + + + @Override + public GameDataSet getDataSet() { + if (parent == null) { + System.out.println("blerf."); + } + return parent.getDataSet(); + } + + public void save() { + if (this.getParent() instanceof GameDataCategory && writable) { + ((GameDataCategory) this.getParent()).save(this.jsonFile); + } + } + + /** + * Returns null if save occurred (no notable events). + */ + public List attemptSave() { + List events = ((GameDataCategory) this.getParent()).attemptSave(true, this.jsonFile.getName()); + if (events == null || events.isEmpty()) { + return null; + } + if (events.size() == 1 && events.get(0).type == SaveEvent.Type.alsoSave && events.get(0).target == this) { + save(); + return null; + } + return events; + } + + public static Integer getInteger(Number n) { + return n == null ? null : n.intValue(); + } + + public static Double getDouble(Number n) { + return n == null ? null : n.doubleValue(); + } + + public static Double parseChance(String s) { + if (s.equals("100")) return 100d; else if (s.equals("70")) return 70d; else if (s.equals("30")) return 30d; else if (s.equals("25")) return 25d; @@ -138,28 +133,30 @@ public abstract class JSONElement extends GameDataElement { else if (s.equals("1/1000")) return 0.1; else if (s.equals("1/10000")) return 0.01; else if (s.indexOf('/') >= 0) { - int c = s.indexOf('/'); - double a = 1; - try { - a = Integer.parseInt(s.substring(0, c)); - } catch (NumberFormatException nfe) {} - double b = 100; - try { - b = Integer.parseInt(s.substring(c+1)); - } catch (NumberFormatException nfe) {} - return a/b; + int c = s.indexOf('/'); + double a = 1; + try { + a = Integer.parseInt(s.substring(0, c)); + } catch (NumberFormatException nfe) { + } + double b = 100; + try { + b = Integer.parseInt(s.substring(c + 1)); + } catch (NumberFormatException nfe) { + } + return a / b; + } else { + double a = 10; + try { + a = Double.parseDouble(s); + } catch (NumberFormatException nfe) { + } + return a; } - else { - double a = 10; - try { - a = Double.parseDouble(s); - } catch (NumberFormatException nfe) {} - return a; - } - } - - public static String printJsonChance(Double chance) { - if (chance.equals(100d)) return "100"; + } + + public static String printJsonChance(Double chance) { + if (chance.equals(100d)) return "100"; else if (chance.equals(70d)) return "70"; else if (chance.equals(30d)) return "30"; else if (chance.equals(25d)) return "25"; @@ -170,11 +167,11 @@ public abstract class JSONElement extends GameDataElement { else if (chance.equals(0.1d)) return "1/1000"; else if (chance.equals(0.01d)) return "1/10000"; else { - if (chance.intValue() == chance) return Integer.toString(chance.intValue()); - //TODO Better handling of fractions. Chance description need a complete overhaul in AT. - //This part does not output the input content of parseDouble(String s) in the case of fractions. - return chance.toString(); + if (chance.intValue() == chance) return Integer.toString(chance.intValue()); + //TODO Better handling of fractions. Chance description need a complete overhaul in AT. + //This part does not output the input content of parseDouble(String s) in the case of fractions. + return chance.toString(); } - } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 78d2b1d..37c0c0e 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -1,6 +1,13 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -10,55 +17,47 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; - import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; public class NPC extends JSONElement { - private static final long serialVersionUID = 1093728879485491933L; + private static final long serialVersionUID = 1093728879485491933L; - //Available from init state - //public String id = null; inherited. - public String name = null; - public String icon_id = null; - - //Available from parsed state - public Integer max_hp = null; - public Integer max_ap = null; - public Integer move_cost = null; - public Integer unique = null; - public MonsterClass monster_class = null; - public MovementType movement_type = null; - public Integer attack_damage_max = null; - public Integer attack_damage_min = null; - public String spawngroup_id = null; - public String faction_id = null; - public String dialogue_id = null; - public String droplist_id = null; - public Integer attack_cost = null; - public Integer attack_chance = null; - public Integer critical_skill = null; - public Double critical_multiplier = null; - public Integer block_chance = null; - public Integer damage_resistance = null; - public HitEffect hit_effect = null; - public HitReceivedEffect hit_received_effect = null; - public DeathEffect death_effect = null; - - //Available from linked state - public Dialogue dialogue = null; - public Droplist droplist = null; - - public enum MonsterClass { - humanoid, - insect, + //Available from init state + //public String id = null; inherited. + public String name = null; + public String icon_id = null; + + //Available from parsed state + public Integer max_hp = null; + public Integer max_ap = null; + public Integer move_cost = null; + public Integer unique = null; + public MonsterClass monster_class = null; + public MovementType movement_type = null; + public Integer attack_damage_max = null; + public Integer attack_damage_min = null; + public String spawngroup_id = null; + public String faction_id = null; + public String dialogue_id = null; + public String droplist_id = null; + public Integer attack_cost = null; + public Integer attack_chance = null; + public Integer critical_skill = null; + public Double critical_multiplier = null; + public Integer block_chance = null; + public Integer damage_resistance = null; + public HitEffect hit_effect = null; + public HitReceivedEffect hit_received_effect = null; + public DeathEffect death_effect = null; + + //Available from linked state + public Dialogue dialogue = null; + public Droplist droplist = null; + + public enum MonsterClass { + humanoid, + insect, demon, construct, animal, @@ -66,498 +65,516 @@ public class NPC extends JSONElement { undead, reptile, ghost - } - - public enum MovementType { - none, - helpOthers, + } + + public enum MovementType { + none, + helpOthers, protectSpawn, wholeMap - } + } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+name+" ("+id+")"; - } + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + name + " (" + id + ")"; + } - public static String getStaticDesc() { - return "NPCs"; - } + public static String getStaticDesc() { + return "NPCs"; + } - - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List npcs = (List) parser.parse(reader); - for (Object obj : npcs) { - Map npcJson = (Map)obj; - NPC npc = fromJson(npcJson); - npc.jsonFile = jsonFile; - npc.parent = category; - if (npc.getDataType() == GameSource.Type.created || npc.getDataType() == GameSource.Type.altered) { - npc.writable = true; - } - category.add(npc); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static NPC fromJson(String jsonString) throws ParseException { - Map npcJson = (Map) new JSONParser().parse(jsonString); - NPC npc = fromJson(npcJson); - npc.parse(npcJson); - return npc; - } - - @SuppressWarnings("rawtypes") - public static NPC fromJson(Map npcJson) { - NPC npc = new NPC(); - npc.icon_id = (String) npcJson.get("iconID"); - npc.id = (String) npcJson.get("id"); - npc.name = (String) npcJson.get("name"); - return npc; - } - - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map npcJson) { - this.max_hp = JSONElement.getInteger((Number) npcJson.get("maxHP")); - this.max_ap = JSONElement.getInteger((Number) npcJson.get("maxAP")); - this.move_cost = JSONElement.getInteger((Number) npcJson.get("moveCost")); - this.unique = JSONElement.getInteger((Number) npcJson.get("unique")); - if (npcJson.get("monsterClass") != null) this.monster_class = MonsterClass.valueOf((String) npcJson.get("monsterClass")); - if (npcJson.get("movementAggressionType") != null) this.movement_type = MovementType.valueOf((String) npcJson.get("movementAggressionType")); - if (npcJson.get("attackDamage") != null) { - this.attack_damage_min = JSONElement.getInteger((Number) (((Map)npcJson.get("attackDamage")).get("min"))); - this.attack_damage_max = JSONElement.getInteger((Number) (((Map)npcJson.get("attackDamage")).get("max"))); - } - this.spawngroup_id = (String) npcJson.get("spawnGroup"); - this.faction_id = (String) npcJson.get("faction"); - this.dialogue_id = (String) npcJson.get("phraseID"); - this.droplist_id = (String) npcJson.get("droplistID"); - this.attack_cost = JSONElement.getInteger((Number) npcJson.get("attackCost")); - this.attack_chance = JSONElement.getInteger((Number) npcJson.get("attackChance")); - this.critical_skill = JSONElement.getInteger((Number) npcJson.get("criticalSkill")); - //TODO correct game data, to unify format. + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List npcs = (List) parser.parse(reader); + for (Object obj : npcs) { + Map npcJson = (Map) obj; + NPC npc = fromJson(npcJson); + npc.jsonFile = jsonFile; + npc.parent = category; + if (npc.getDataType() == GameSource.Type.created || npc.getDataType() == GameSource.Type.altered) { + npc.writable = true; + } + category.add(npc); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static NPC fromJson(String jsonString) throws ParseException { + Map npcJson = (Map) new JSONParser().parse(jsonString); + NPC npc = fromJson(npcJson); + npc.parse(npcJson); + return npc; + } + + @SuppressWarnings("rawtypes") + public static NPC fromJson(Map npcJson) { + NPC npc = new NPC(); + npc.icon_id = (String) npcJson.get("iconID"); + npc.id = (String) npcJson.get("id"); + npc.name = (String) npcJson.get("name"); + return npc; + } + + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map npcJson) { + + this.max_hp = JSONElement.getInteger((Number) npcJson.get("maxHP")); + this.max_ap = JSONElement.getInteger((Number) npcJson.get("maxAP")); + this.move_cost = JSONElement.getInteger((Number) npcJson.get("moveCost")); + this.unique = JSONElement.getInteger((Number) npcJson.get("unique")); + if (npcJson.get("monsterClass") != null) + this.monster_class = MonsterClass.valueOf((String) npcJson.get("monsterClass")); + if (npcJson.get("movementAggressionType") != null) + this.movement_type = MovementType.valueOf((String) npcJson.get("movementAggressionType")); + if (npcJson.get("attackDamage") != null) { + this.attack_damage_min = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("min"))); + this.attack_damage_max = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("max"))); + } + this.spawngroup_id = (String) npcJson.get("spawnGroup"); + this.faction_id = (String) npcJson.get("faction"); + this.dialogue_id = (String) npcJson.get("phraseID"); + this.droplist_id = (String) npcJson.get("droplistID"); + this.attack_cost = JSONElement.getInteger((Number) npcJson.get("attackCost")); + this.attack_chance = JSONElement.getInteger((Number) npcJson.get("attackChance")); + this.critical_skill = JSONElement.getInteger((Number) npcJson.get("criticalSkill")); + //TODO correct game data, to unify format. // this.critical_multiplier = JSONElement.getDouble((Number) npcJson.get("criticalMultiplier")); - if (npcJson.get("criticalMultiplier") != null) this.critical_multiplier = JSONElement.getDouble(Double.parseDouble(npcJson.get("criticalMultiplier").toString())); + if (npcJson.get("criticalMultiplier") != null) + this.critical_multiplier = JSONElement.getDouble(Double.parseDouble(npcJson.get("criticalMultiplier").toString())); - this.block_chance = JSONElement.getInteger((Number) npcJson.get("blockChance")); - this.damage_resistance = JSONElement.getInteger((Number) npcJson.get("damageResistance")); - - Map hitEffect = (Map) npcJson.get("hitEffect"); - if (hitEffect != null) { - this.hit_effect = new HitEffect(); - if (hitEffect.get("increaseCurrentHP") != null) { - this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("max"))); - this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentHP")).get("min"))); - } - if (hitEffect.get("increaseCurrentAP") != null) { - this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("max"))); - this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)hitEffect.get("increaseCurrentAP")).get("min"))); - } - List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); - this.hit_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); - List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); - this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); - } + this.block_chance = JSONElement.getInteger((Number) npcJson.get("blockChance")); + this.damage_resistance = JSONElement.getInteger((Number) npcJson.get("damageResistance")); - Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); - if (hitReceivedEffect != null) { - this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); - } + Map hitEffect = (Map) npcJson.get("hitEffect"); + if (hitEffect != null) { + this.hit_effect = new HitEffect(); + if (hitEffect.get("increaseCurrentHP") != null) { + this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("max"))); + this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("min"))); + } + if (hitEffect.get("increaseCurrentAP") != null) { + this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("max"))); + this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("min"))); + } + List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); + this.hit_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); + List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); + this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); + } - Map deathEffect = (Map) npcJson.get("deathEffect"); - if (deathEffect != null) { - this.death_effect = new HitEffect(); - if (deathEffect.get("increaseCurrentHP") != null) { - this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("max"))); - this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentHP")).get("min"))); - } - if (deathEffect.get("increaseCurrentAP") != null) { - this.death_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentAP")).get("max"))); - this.death_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map)deathEffect.get("increaseCurrentAP")).get("min"))); - } - List conditionsSourceJson = (List) deathEffect.get("conditionsSource"); + Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); + if (hitReceivedEffect != null) { + this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); + } + + Map deathEffect = (Map) npcJson.get("deathEffect"); + if (deathEffect != null) { + this.death_effect = new HitEffect(); + if (deathEffect.get("increaseCurrentHP") != null) { + this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("max"))); + this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("min"))); + } + if (deathEffect.get("increaseCurrentAP") != null) { + this.death_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("max"))); + this.death_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("min"))); + } + List conditionsSourceJson = (List) deathEffect.get("conditionsSource"); this.death_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); - } - - } + } - @Override - public void link() { - if (!this.linkCheck()) return; - Project proj = getProject(); - if (proj == null) { - Notification.addError("Error linking item "+id+". No parent project found."); - return; - } - if (this.icon_id != null) { - String spritesheetId = this.icon_id.split(":")[0]; - proj.getSpritesheet(spritesheetId).addBacklink(this); - } - - if (this.dialogue_id != null) this.dialogue = proj.getDialogue(this.dialogue_id); - if (this.dialogue != null) this.dialogue.addBacklink(this); - - if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id); - if (this.droplist != null) this.droplist.addBacklink(this); - - if (this.hit_effect != null) { - linkConditions(this.hit_effect.conditions_source, proj, this); - linkConditions(this.hit_effect.conditions_target, proj, this); - } - if (this.hit_received_effect != null) { - linkConditions(this.hit_received_effect.conditions_source, proj, this); - linkConditions(this.hit_received_effect.conditions_target, proj, this); - } - if (this.death_effect != null) { - linkConditions(this.death_effect.conditions_source, proj, this); - } - this.state = State.linked; - } + } - @Override - public Image getIcon() { - return getProject().getIcon(icon_id); - } - - public Image getImage() { - return getProject().getImage(icon_id); - } - - @Override - public GameDataElement clone() { - NPC clone = new NPC(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.name = this.name; - clone.icon_id = this.icon_id; - clone.attack_chance = this.attack_chance; - clone.attack_cost = this.attack_cost; - clone.attack_damage_min = this.attack_damage_min; - clone.attack_damage_max = this.attack_damage_max; - clone.block_chance = this.block_chance; - clone.critical_multiplier = this.critical_multiplier; - clone.critical_skill = this.critical_skill; - clone.damage_resistance = this.damage_resistance; - clone.dialogue = this.dialogue; - if (clone.dialogue != null) { - clone.dialogue.addBacklink(clone); - } - clone.dialogue_id = this.dialogue_id; - clone.droplist = this.droplist; - if (clone.droplist != null) { - clone.droplist.addBacklink(clone); - } - clone.droplist_id = this.droplist_id; - clone.faction_id = this.faction_id; - if (this.hit_effect != null) { - clone.hit_effect = new HitEffect(); - copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); - } - if (this.hit_received_effect != null) { + @Override + public void link() { + if (!this.linkCheck()) return; + Project proj = getProject(); + if (proj == null) { + Notification.addError("Error linking item " + id + ". No parent project found."); + return; + } + if (this.icon_id != null) { + String spritesheetId = this.icon_id.split(":")[0]; + proj.getSpritesheet(spritesheetId).addBacklink(this); + } + + if (this.dialogue_id != null) this.dialogue = proj.getDialogue(this.dialogue_id); + if (this.dialogue != null) this.dialogue.addBacklink(this); + + if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id); + if (this.droplist != null) this.droplist.addBacklink(this); + + if (this.hit_effect != null) { + linkConditions(this.hit_effect.conditions_source, proj, this); + linkConditions(this.hit_effect.conditions_target, proj, this); + } + if (this.hit_received_effect != null) { + linkConditions(this.hit_received_effect.conditions_source, proj, this); + linkConditions(this.hit_received_effect.conditions_target, proj, this); + } + if (this.death_effect != null) { + linkConditions(this.death_effect.conditions_source, proj, this); + } + this.state = State.linked; + } + + @Override + public Image getIcon() { + return getProject().getIcon(icon_id); + } + + public Image getImage() { + return getProject().getImage(icon_id); + } + + @Override + public GameDataElement clone() { + NPC clone = new NPC(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.name = this.name; + clone.icon_id = this.icon_id; + clone.attack_chance = this.attack_chance; + clone.attack_cost = this.attack_cost; + clone.attack_damage_min = this.attack_damage_min; + clone.attack_damage_max = this.attack_damage_max; + clone.block_chance = this.block_chance; + clone.critical_multiplier = this.critical_multiplier; + clone.critical_skill = this.critical_skill; + clone.damage_resistance = this.damage_resistance; + clone.dialogue = this.dialogue; + if (clone.dialogue != null) { + clone.dialogue.addBacklink(clone); + } + clone.dialogue_id = this.dialogue_id; + clone.droplist = this.droplist; + if (clone.droplist != null) { + clone.droplist.addBacklink(clone); + } + clone.droplist_id = this.droplist_id; + clone.faction_id = this.faction_id; + if (this.hit_effect != null) { + clone.hit_effect = new HitEffect(); + copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); + } + if (this.hit_received_effect != null) { clone.hit_received_effect = new HitReceivedEffect(); - copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); - } - if (this.death_effect != null) { - clone.death_effect = new DeathEffect(); - copyDeathEffectValues(clone.death_effect, this.death_effect, clone); - } - clone.max_ap = this.max_ap; - clone.max_hp = this.max_hp; - clone.monster_class = this.monster_class; - clone.move_cost = this.move_cost; - clone.movement_type = this.movement_type; - clone.spawngroup_id = this.spawngroup_id; - clone.unique = this.unique; - return clone; - } + copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); + } + if (this.death_effect != null) { + clone.death_effect = new DeathEffect(); + copyDeathEffectValues(clone.death_effect, this.death_effect, clone); + } + clone.max_ap = this.max_ap; + clone.max_hp = this.max_hp; + clone.monster_class = this.monster_class; + clone.move_cost = this.move_cost; + clone.movement_type = this.movement_type; + clone.spawngroup_id = this.spawngroup_id; + clone.unique = this.unique; + return clone; + } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (dialogue == oldOne) { - oldOne.removeBacklink(this); - this.dialogue = (Dialogue) newOne; - if (newOne != null) newOne.addBacklink(this); - } else { - if (this.droplist == oldOne) { - oldOne.removeBacklink(this); - this.droplist = (Droplist) newOne; - if (newOne != null) newOne.addBacklink(this); - } else { - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect tce : this.hit_effect.conditions_source) { - if (tce.condition == oldOne) { - oldOne.removeBacklink(this); - tce.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect tce : this.hit_effect.conditions_target) { - if (tce.condition == oldOne) { - oldOne.removeBacklink(this); - tce.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - } - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map npcJson = new LinkedHashMap(); - npcJson.put("id", this.id); - if (this.name != null) npcJson.put("name", this.name); - if (this.icon_id != null) npcJson.put("iconID", this.icon_id); - if (this.max_hp != null) npcJson.put("maxHP", this.max_hp); - if (this.max_ap != null) npcJson.put("maxAP", this.max_ap); - if (this.move_cost != null) npcJson.put("moveCost", this.move_cost); - if (this.unique != null) npcJson.put("unique", this.unique); - if (this.monster_class != null) npcJson.put("monsterClass", this.monster_class.toString()); - if (this.movement_type != null) npcJson.put("movementAggressionType", this.movement_type.toString()); - if (this.attack_damage_min != null || this.attack_damage_max != null) { - Map adJson = new LinkedHashMap(); - npcJson.put("attackDamage", adJson); - if (this.attack_damage_min != null) adJson.put("min", this.attack_damage_min); - else adJson.put("min", 0); - if (this.attack_damage_max != null) adJson.put("max", this.attack_damage_max); - else adJson.put("max", 0); - } - if (this.spawngroup_id != null) npcJson.put("spawnGroup", this.spawngroup_id); - if (this.faction_id != null) npcJson.put("faction", this.faction_id); - if (this.dialogue != null) { - npcJson.put("phraseID", this.dialogue.id); - } else if (this.dialogue_id != null) { - npcJson.put("phraseID", this.dialogue_id); - } - if (this.droplist != null) { - npcJson.put("droplistID", this.droplist.id); - } else if (this.droplist_id != null) { - npcJson.put("droplistID", this.droplist_id); - } - if (this.attack_cost != null) npcJson.put("attackCost", this.attack_cost); - if (this.attack_chance != null) npcJson.put("attackChance", this.attack_chance); - if (this.critical_skill != null) npcJson.put("criticalSkill", this.critical_skill); - if (this.critical_multiplier != null) npcJson.put("criticalMultiplier", this.critical_multiplier); - if (this.block_chance != null) npcJson.put("blockChance", this.block_chance); - if (this.damage_resistance != null) npcJson.put("damageResistance", this.damage_resistance); - if (this.hit_effect != null) { - Map hitEffectJson = new LinkedHashMap(); - npcJson.put("hitEffect", hitEffectJson); - if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.hit_received_effect != null) { - Map hitReceivedEffectJson = new LinkedHashMap(); - npcJson.put("hitReceivedEffect", hitReceivedEffectJson); - if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min != null) hpJson.put("min", this.hit_received_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max != null) hpJson.put("max", this.hit_received_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min != null) apJson.put("min", this.hit_received_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max != null) apJson.put("max", this.hit_received_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min_target != null) hpJson.put("min", this.hit_received_effect.hp_boost_min_target); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max_target != null) hpJson.put("max", this.hit_received_effect.hp_boost_max_target); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min_target != null) apJson.put("min", this.hit_received_effect.ap_boost_min_target); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max_target != null) apJson.put("max", this.hit_received_effect.ap_boost_max_target); - else apJson.put("max", 0); - } - if (this.hit_received_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_received_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.death_effect != null) { - Map deathEffectJson = new LinkedHashMap(); - npcJson.put("deathEffect", deathEffectJson); - if (this.death_effect.hp_boost_min != null || this.death_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - deathEffectJson.put("increaseCurrentHP", hpJson); - if (this.death_effect.hp_boost_min != null) hpJson.put("min", this.death_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.death_effect.hp_boost_max != null) hpJson.put("max", this.death_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.death_effect.ap_boost_min != null || this.death_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - deathEffectJson.put("increaseCurrentAP", apJson); - if (this.death_effect.ap_boost_min != null) apJson.put("min", this.death_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.death_effect.ap_boost_max != null) apJson.put("max", this.death_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.death_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - deathEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.death_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - return npcJson; - } - + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (dialogue == oldOne) { + oldOne.removeBacklink(this); + this.dialogue = (Dialogue) newOne; + if (newOne != null) newOne.addBacklink(this); + } else { + if (this.droplist == oldOne) { + oldOne.removeBacklink(this); + this.droplist = (Droplist) newOne; + if (newOne != null) newOne.addBacklink(this); + } else { + if (this.hit_effect != null && this.hit_effect.conditions_source != null) { + for (TimedConditionEffect tce : this.hit_effect.conditions_source) { + if (tce.condition == oldOne) { + oldOne.removeBacklink(this); + tce.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + if (this.hit_effect != null && this.hit_effect.conditions_target != null) { + for (TimedConditionEffect tce : this.hit_effect.conditions_target) { + if (tce.condition == oldOne) { + oldOne.removeBacklink(this); + tce.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + } + } + } - @Override - public String getProjectFilename() { - return "monsterlist_"+getProject().name+".json"; - } - - public int getMonsterExperience() { - double EXP_FACTOR_DAMAGERESISTANCE = 9; - double EXP_FACTOR_SCALING = 0.7; + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map npcJson = new LinkedHashMap(); + npcJson.put("id", this.id); + if (this.name != null) npcJson.put("name", this.name); + if (this.icon_id != null) npcJson.put("iconID", this.icon_id); + if (this.max_hp != null) npcJson.put("maxHP", this.max_hp); + if (this.max_ap != null) npcJson.put("maxAP", this.max_ap); + if (this.move_cost != null) npcJson.put("moveCost", this.move_cost); + if (this.unique != null) npcJson.put("unique", this.unique); + if (this.monster_class != null) npcJson.put("monsterClass", this.monster_class.toString()); + if (this.movement_type != null) npcJson.put("movementAggressionType", this.movement_type.toString()); + if (this.attack_damage_min != null || this.attack_damage_max != null) { + Map adJson = new LinkedHashMap(); + npcJson.put("attackDamage", adJson); + if (this.attack_damage_min != null) adJson.put("min", this.attack_damage_min); + else adJson.put("min", 0); + if (this.attack_damage_max != null) adJson.put("max", this.attack_damage_max); + else adJson.put("max", 0); + } + if (this.spawngroup_id != null) npcJson.put("spawnGroup", this.spawngroup_id); + if (this.faction_id != null) npcJson.put("faction", this.faction_id); + if (this.dialogue != null) { + npcJson.put("phraseID", this.dialogue.id); + } else if (this.dialogue_id != null) { + npcJson.put("phraseID", this.dialogue_id); + } + if (this.droplist != null) { + npcJson.put("droplistID", this.droplist.id); + } else if (this.droplist_id != null) { + npcJson.put("droplistID", this.droplist_id); + } + if (this.attack_cost != null) npcJson.put("attackCost", this.attack_cost); + if (this.attack_chance != null) npcJson.put("attackChance", this.attack_chance); + if (this.critical_skill != null) npcJson.put("criticalSkill", this.critical_skill); + if (this.critical_multiplier != null) npcJson.put("criticalMultiplier", this.critical_multiplier); + if (this.block_chance != null) npcJson.put("blockChance", this.block_chance); + if (this.damage_resistance != null) npcJson.put("damageResistance", this.damage_resistance); + if (this.hit_effect != null) { + Map hitEffectJson = new LinkedHashMap(); + npcJson.put("hitEffect", hitEffectJson); + if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedConditionEffect condition : this.hit_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitEffectJson.put("conditionsTarget", conditionsTargetJson); + for (TimedConditionEffect condition : this.hit_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.hit_received_effect != null) { + Map hitReceivedEffectJson = new LinkedHashMap(); + npcJson.put("hitReceivedEffect", hitReceivedEffectJson); + if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min != null) + hpJson.put("min", this.hit_received_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max != null) + hpJson.put("max", this.hit_received_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min != null) + apJson.put("min", this.hit_received_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max != null) + apJson.put("max", this.hit_received_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min_target != null) + hpJson.put("min", this.hit_received_effect.hp_boost_min_target); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max_target != null) + hpJson.put("max", this.hit_received_effect.hp_boost_max_target); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min_target != null) + apJson.put("min", this.hit_received_effect.ap_boost_min_target); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max_target != null) + apJson.put("max", this.hit_received_effect.ap_boost_max_target); + else apJson.put("max", 0); + } + if (this.hit_received_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_received_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); + for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.death_effect != null) { + Map deathEffectJson = new LinkedHashMap(); + npcJson.put("deathEffect", deathEffectJson); + if (this.death_effect.hp_boost_min != null || this.death_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + deathEffectJson.put("increaseCurrentHP", hpJson); + if (this.death_effect.hp_boost_min != null) hpJson.put("min", this.death_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.death_effect.hp_boost_max != null) hpJson.put("max", this.death_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.death_effect.ap_boost_min != null || this.death_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + deathEffectJson.put("increaseCurrentAP", apJson); + if (this.death_effect.ap_boost_min != null) apJson.put("min", this.death_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.death_effect.ap_boost_max != null) apJson.put("max", this.death_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.death_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + deathEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedConditionEffect condition : this.death_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + return npcJson; + } - double attacksPerTurn = Math.floor((double)(max_ap != null ? max_ap : 10.0) / (double)(attack_cost != null ? attack_cost : 10.0)); - double avgDamagePotential = 0; - if (attack_damage_min != null || attack_damage_max != null) { - avgDamagePotential = ((double)(attack_damage_min != null ? attack_damage_min : 0) + (double)(attack_damage_max != null ? attack_damage_max : 0)) / 2.0; - } - double avgCrit = 0; - if (critical_skill != null && critical_multiplier != null) { - avgCrit = (double)(critical_skill / 100.0) * critical_multiplier; - } - double avgAttackHP = attacksPerTurn * ((double)(attack_chance != null ? attack_chance : 0) / 100.0) * avgDamagePotential * (1 + avgCrit); - double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double)(block_chance != null ? block_chance : 0) / 100.0))) + ( EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0)); - double attackConditionBonus = 0; - if (hit_effect != null && hit_effect.conditions_target != null && hit_effect.conditions_target.size() > 0) { - attackConditionBonus = 50; - } - double experience = (((avgAttackHP * 3) + avgDefenseHP) * EXP_FACTOR_SCALING) + attackConditionBonus; - return new Double(Math.ceil(experience)).intValue(); - }; + @Override + public String getProjectFilename() { + return "monsterlist_" + getProject().name + ".json"; + } + + public int getMonsterExperience() { + double EXP_FACTOR_DAMAGERESISTANCE = 9; + double EXP_FACTOR_SCALING = 0.7; + + double attacksPerTurn = Math.floor((double) (max_ap != null ? max_ap : 10.0) / (double) (attack_cost != null ? attack_cost : 10.0)); + double avgDamagePotential = 0; + if (attack_damage_min != null || attack_damage_max != null) { + avgDamagePotential = ((double) (attack_damage_min != null ? attack_damage_min : 0) + (double) (attack_damage_max != null ? attack_damage_max : 0)) / 2.0; + } + double avgCrit = 0; + if (critical_skill != null && critical_multiplier != null) { + avgCrit = (double) (critical_skill / 100.0) * critical_multiplier; + } + double avgAttackHP = attacksPerTurn * ((double) (attack_chance != null ? attack_chance : 0) / 100.0) * avgDamagePotential * (1 + avgCrit); + double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double) (block_chance != null ? block_chance : 0) / 100.0))) + (EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0)); + double attackConditionBonus = 0; + if (hit_effect != null && hit_effect.conditions_target != null && hit_effect.conditions_target.size() > 0) { + attackConditionBonus = 50; + } + double experience = (((avgAttackHP * 3) + avgDefenseHP) * EXP_FACTOR_SCALING) + attackConditionBonus; + + return new Double(Math.ceil(experience)).intValue(); + } + + ; + - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java index 1439344..176dc63 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java @@ -1,6 +1,13 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -10,179 +17,171 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; - public class Quest extends JSONElement { - private static final long serialVersionUID = 2004839647483250099L; - - //Available from init state - //public String id = null; inherited. - public String name = null; - - //Available in parsed state - public Integer visible_in_log = null; - public List stages = null; - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+name+" ("+id+")"; - } + private static final long serialVersionUID = 2004839647483250099L; - public static String getStaticDesc() { - return "Quests"; - } - + //Available from init state + //public String id = null; inherited. + public String name = null; - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List quests = (List) parser.parse(reader); - for (Object obj : quests) { - Map questJson = (Map)obj; - Quest quest = fromJson(questJson); - quest.jsonFile = jsonFile; - quest.parent = category; - if (quest.getDataType() == GameSource.Type.created || quest.getDataType() == GameSource.Type.altered) { - quest.writable = true; - } - category.add(quest); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static Quest fromJson(String jsonString) throws ParseException { - Map questJson = (Map) new JSONParser().parse(jsonString); - Quest quest = fromJson(questJson); - quest.parse(questJson); - return quest; - } - - @SuppressWarnings("rawtypes") - public static Quest fromJson(Map questJson) { - Quest quest = new Quest(); - quest.id = (String) questJson.get("id"); - quest.name = (String) questJson.get("name"); - //Quests have to be parsed to have their stages initialized. - quest.parse(questJson); - return quest; - } + //Available in parsed state + public Integer visible_in_log = null; + public List stages = null; - @SuppressWarnings("rawtypes") - @Override - public void parse(Map questJson) { - this.visible_in_log = JSONElement.getInteger((Number) questJson.get("showInLog")); - List questStagesJson = (List) questJson.get("stages"); - this.stages = new ArrayList(); - if (questStagesJson != null && !questStagesJson.isEmpty()) { - for (Object questStageJsonObj : questStagesJson) { - Map questStageJson = (Map)questStageJsonObj; - QuestStage questStage = new QuestStage(this); - questStage.parse(questStageJson); - this.stages.add(questStage); - } - } - this.state = State.parsed; - } - - @Override - public void link() { - if (!this.linkCheck()) return; - - for (QuestStage stage : stages) { - stage.link(); - } - //Nothing to link to :D - this.state = State.linked; - } + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + name + " (" + id + ")"; + } - @Override - public Image getIcon() { - return DefaultIcons.getQuestIcon(); - } - - public Image getImage() { - return DefaultIcons.getQuestImage(); - } - - @Override - public GameDataElement clone() { - Quest clone = new Quest(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.name = this.name; - clone.visible_in_log = this.visible_in_log; - if (this.stages != null) { - clone.stages = new ArrayList(); - for (QuestStage stage : this.stages){ - clone.stages.add((QuestStage) stage.clone(clone)); - } - } - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - //Nothing to link to. - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map questJson = new LinkedHashMap(); - questJson.put("id", this.id); - if (this.name != null) questJson.put("name", this.name); - if (this.visible_in_log != null) questJson.put("showInLog", this.visible_in_log); - if (this.stages != null) { - List stagesJson = new ArrayList(); - questJson.put("stages", stagesJson); - for (QuestStage stage : this.stages) { - stagesJson.add(stage.toJson()); - } - } - return questJson; - } - + public static String getStaticDesc() { + return "Quests"; + } - @Override - public String getProjectFilename() { - return "questlist_"+getProject().name+".json"; - } - public QuestStage getStage(Integer stageId) { - for (QuestStage stage : stages) { - if (stage.progress.equals(stageId)) { - return stage; - } - } - return null; - } - + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List quests = (List) parser.parse(reader); + for (Object obj : quests) { + Map questJson = (Map) obj; + Quest quest = fromJson(questJson); + quest.jsonFile = jsonFile; + quest.parent = category; + if (quest.getDataType() == GameSource.Type.created || quest.getDataType() == GameSource.Type.altered) { + quest.writable = true; + } + category.add(quest); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static Quest fromJson(String jsonString) throws ParseException { + Map questJson = (Map) new JSONParser().parse(jsonString); + Quest quest = fromJson(questJson); + quest.parse(questJson); + return quest; + } + + @SuppressWarnings("rawtypes") + public static Quest fromJson(Map questJson) { + Quest quest = new Quest(); + quest.id = (String) questJson.get("id"); + quest.name = (String) questJson.get("name"); + //Quests have to be parsed to have their stages initialized. + quest.parse(questJson); + return quest; + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map questJson) { + this.visible_in_log = JSONElement.getInteger((Number) questJson.get("showInLog")); + List questStagesJson = (List) questJson.get("stages"); + this.stages = new ArrayList(); + if (questStagesJson != null && !questStagesJson.isEmpty()) { + for (Object questStageJsonObj : questStagesJson) { + Map questStageJson = (Map) questStageJsonObj; + QuestStage questStage = new QuestStage(this); + questStage.parse(questStageJson); + this.stages.add(questStage); + } + } + this.state = State.parsed; + } + + @Override + public void link() { + if (!this.linkCheck()) return; + + for (QuestStage stage : stages) { + stage.link(); + } + //Nothing to link to :D + this.state = State.linked; + } + + @Override + public Image getIcon() { + return DefaultIcons.getQuestIcon(); + } + + public Image getImage() { + return DefaultIcons.getQuestImage(); + } + + @Override + public GameDataElement clone() { + Quest clone = new Quest(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.name = this.name; + clone.visible_in_log = this.visible_in_log; + if (this.stages != null) { + clone.stages = new ArrayList(); + for (QuestStage stage : this.stages) { + clone.stages.add((QuestStage) stage.clone(clone)); + } + } + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + //Nothing to link to. + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map questJson = new LinkedHashMap(); + questJson.put("id", this.id); + if (this.name != null) questJson.put("name", this.name); + if (this.visible_in_log != null) questJson.put("showInLog", this.visible_in_log); + if (this.stages != null) { + List stagesJson = new ArrayList(); + questJson.put("stages", stagesJson); + for (QuestStage stage : this.stages) { + stagesJson.add(stage.toJson()); + } + } + return questJson; + } + + + @Override + public String getProjectFilename() { + return "questlist_" + getProject().name + ".json"; + } + + public QuestStage getStage(Integer stageId) { + for (QuestStage stage : stages) { + if (stage.progress.equals(stageId)) { + return stage; + } + } + return null; + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java index 8076707..838a158 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java @@ -1,93 +1,93 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; -import java.awt.Image; -import java.util.LinkedHashMap; -import java.util.Map; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; +import java.util.LinkedHashMap; +import java.util.Map; + public class QuestStage extends JSONElement { - - private static final long serialVersionUID = 8313645819951513431L; - - public Integer progress = null; - public String log_text = null; - public Integer exp_reward = null; - public Integer finishes_quest = null; - - public QuestStage(Quest parent){ - this.parent = parent; - } - - public QuestStage clone(Quest cloneParent) { - QuestStage clone = new QuestStage(cloneParent); - clone.progress = progress != null ? new Integer(progress) : null; - clone.log_text = log_text != null ? new String(log_text) : null; - clone.exp_reward = exp_reward != null ? new Integer(exp_reward) : null; - clone.finishes_quest = finishes_quest != null ? new Integer(finishes_quest) : null; - clone.id = this.id; - return clone; - } - @SuppressWarnings("rawtypes") - @Override - public void parse(Map jsonObj) { - progress = JSONElement.getInteger((Number) jsonObj.get("progress")); - this.id = ((Quest)parent).id+":"+progress; - log_text = (String) jsonObj.get("logText"); - exp_reward = JSONElement.getInteger((Number) jsonObj.get("rewardExperience")); - finishes_quest = JSONElement.getInteger((Number) jsonObj.get("finishesQuest")); - state = State.parsed; - } + private static final long serialVersionUID = 8313645819951513431L; - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public Map toJson() { - Map stageJson = new LinkedHashMap(); - if (progress != null) stageJson.put("progress", progress); - if (log_text != null) stageJson.put("logText", log_text); - if (exp_reward != null) stageJson.put("rewardExperience", exp_reward); - if (finishes_quest != null) stageJson.put("finishesQuest", finishes_quest); - return stageJson; - } + public Integer progress = null; + public String log_text = null; + public Integer exp_reward = null; + public Integer finishes_quest = null; - @Override - public String getDesc() { - return progress+" - "+(exp_reward != null ? "["+exp_reward+"XP]" : "")+((finishes_quest != null) && (finishes_quest == 1) ? "[END]" : "")+log_text; - } + public QuestStage(Quest parent) { + this.parent = parent; + } - @Override - public void link() { - if (!this.linkCheck()) return; - - //Nothing to link to :D - this.state = State.linked; - } + public QuestStage clone(Quest cloneParent) { + QuestStage clone = new QuestStage(cloneParent); + clone.progress = progress != null ? new Integer(progress) : null; + clone.log_text = log_text != null ? new String(log_text) : null; + clone.exp_reward = exp_reward != null ? new Integer(exp_reward) : null; + clone.finishes_quest = finishes_quest != null ? new Integer(finishes_quest) : null; + clone.id = this.id; + return clone; + } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - // Nothing to link to. - } + @SuppressWarnings("rawtypes") + @Override + public void parse(Map jsonObj) { + progress = JSONElement.getInteger((Number) jsonObj.get("progress")); + this.id = ((Quest) parent).id + ":" + progress; + log_text = (String) jsonObj.get("logText"); + exp_reward = JSONElement.getInteger((Number) jsonObj.get("rewardExperience")); + finishes_quest = JSONElement.getInteger((Number) jsonObj.get("finishesQuest")); + state = State.parsed; + } - @Override - public String getProjectFilename() { - return ((Quest)parent).getProjectFilename(); - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map stageJson = new LinkedHashMap(); + if (progress != null) stageJson.put("progress", progress); + if (log_text != null) stageJson.put("logText", log_text); + if (exp_reward != null) stageJson.put("rewardExperience", exp_reward); + if (finishes_quest != null) stageJson.put("finishesQuest", finishes_quest); + return stageJson; + } + + @Override + public String getDesc() { + return progress + " - " + (exp_reward != null ? "[" + exp_reward + "XP]" : "") + ((finishes_quest != null) && (finishes_quest == 1) ? "[END]" : "") + log_text; + } + + @Override + public void link() { + if (!this.linkCheck()) return; + + //Nothing to link to :D + this.state = State.linked; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + // Nothing to link to. + } + + @Override + public String getProjectFilename() { + return ((Quest) parent).getProjectFilename(); + } + + @Override + public GameDataElement clone() { + return null; + } + + @Override + public Image getIcon() { + return DefaultIcons.getQuestIcon(); + } + + public Image getImage() { + return DefaultIcons.getQuestImage(); + } - @Override - public GameDataElement clone() { - return null; - } - - @Override - public Image getIcon() { - return DefaultIcons.getQuestIcon(); - } - - public Image getImage() { - return DefaultIcons.getQuestImage(); - } - } \ No newline at end of file diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java index ac93ac1..9a15578 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java @@ -1,258 +1,227 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Project; + import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Project; - public class Requirement extends JSONElement { - private static final long serialVersionUID = 7295593297142310955L; - - private static Map> COMPATIBLE_TYPES = new LinkedHashMap>(); - - static { - List questTypes = new ArrayList(); - questTypes.add(RequirementType.questProgress); - questTypes.add(RequirementType.questLatestProgress); - COMPATIBLE_TYPES.put(RequirementType.questProgress, questTypes); - COMPATIBLE_TYPES.put(RequirementType.questLatestProgress, questTypes); - - List countedItemTypes = new ArrayList(); - countedItemTypes.add(RequirementType.inventoryRemove); - countedItemTypes.add(RequirementType.inventoryKeep); - countedItemTypes.add(RequirementType.usedItem); - countedItemTypes.add(RequirementType.wear); - countedItemTypes.add(RequirementType.wearRemove); - COMPATIBLE_TYPES.put(RequirementType.inventoryRemove, countedItemTypes); - COMPATIBLE_TYPES.put(RequirementType.inventoryKeep, countedItemTypes); - COMPATIBLE_TYPES.put(RequirementType.usedItem, countedItemTypes); - COMPATIBLE_TYPES.put(RequirementType.wear, countedItemTypes); - COMPATIBLE_TYPES.put(RequirementType.wearRemove, countedItemTypes); - } - - //Available from parsed state - public RequirementType type = null; - public String required_obj_id = null; - public Integer required_value = null; - public Boolean negated = null; - - //Available from linked state - public GameDataElement required_obj = null; - - public enum RequirementType { - questProgress, - questLatestProgress, - inventoryRemove, - inventoryKeep, - wear, - skillLevel, - killedMonster, - timerElapsed, - usedItem, - spentGold, - consumedBonemeals, - hasActorCondition, - factionScore, - random, - factionScoreEquals, - wearRemove, - date, - dateEquals, - time, - timeEquals - } - - public enum SkillID { - weaponChance - ,weaponDmg - ,barter - ,dodge - ,barkSkin - ,moreCriticals - ,betterCriticals - ,speed // Raises max ap - ,coinfinder - ,moreExp - ,cleave // +10ap on kill - ,eater // +1hp per kill - ,fortitude // +N hp per levelup - ,evasion // increase successful flee chance & reduce chance of monster attack - ,regeneration // +N hp per round - ,lowerExploss - ,magicfinder - ,resistanceMental // lowers chance to get negative active conditions by monsters (Mental like Dazed) - ,resistancePhysical // lowers chance to get negative active conditions by monsters (Physical Capacity like Minor fatigue) - ,resistanceBlood // lowers chance to get negative active conditions by monsters (Blood Disorder like Weak Poison) - ,shadowBless - ,sporeImmunity - ,crit1 // lowers atk ability - ,crit2 // lowers def ability ,rejuvenation // Reduces magnitudes of conditions - ,rejuvenation // Reduces magnitudes of conditions - ,taunt // Causes AP loss of attackers that miss - ,concussion // AC loss for monsters with (AC-BC)>N - ,weaponProficiencyDagger - ,weaponProficiency1hsword - ,weaponProficiency2hsword - ,weaponProficiencyAxe - ,weaponProficiencyBlunt - ,weaponProficiencyUnarmed - ,weaponProficiencyPole - ,armorProficiencyShield - ,armorProficiencyUnarmored - ,armorProficiencyLight - ,armorProficiencyHeavy - ,fightstyleDualWield - ,fightstyle2hand - ,fightstyleWeaponShield - ,specializationDualWield - ,specialization2hand - ,specializationWeaponShield - } - - @Override - public String getDesc() { - String obj_id = ""; - if (required_obj_id != null) - { - obj_id = required_obj_id; - if (type != null && type == RequirementType.random){ - obj_id = " Chance " + obj_id + (required_obj_id.contains("/") ? "" : "%"); - } - else { - obj_id += ":"; - } - } - - return ((negated != null && negated) ? "NOT " : "") - +(type == null ? "" : type.toString()+":") - +obj_id - +(required_value == null ? "" : required_value.toString()); - } + private static final long serialVersionUID = 7295593297142310955L; - @Override - public void parse() { - throw new Error("Thou shalt not reach this method."); - } + private static Map> COMPATIBLE_TYPES = new LinkedHashMap>(); - @SuppressWarnings("rawtypes") - @Override - public Map toJson() { - throw new Error("Thou shalt not reach this method."); - } - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map jsonObj) { - throw new Error("Thou shalt not reach this method."); - } + static { + List questTypes = new ArrayList(); + questTypes.add(RequirementType.questProgress); + questTypes.add(RequirementType.questLatestProgress); + COMPATIBLE_TYPES.put(RequirementType.questProgress, questTypes); + COMPATIBLE_TYPES.put(RequirementType.questLatestProgress, questTypes); - @Override - public void link() { - if (!this.linkCheck()) return; - Project proj = getProject(); - if (proj == null) { - Notification.addError("Error linking requirement "+getDesc()+". No parent project found."); - return; - } - switch (type) { - case hasActorCondition: - this.required_obj = proj.getActorCondition(required_obj_id); - break; - case inventoryKeep: - case inventoryRemove: - case usedItem: - case wear: - case wearRemove: - this.required_obj = proj.getItem(required_obj_id); - break; - case killedMonster: - this.required_obj = proj.getNPC(required_obj_id); - break; - case questLatestProgress: - case questProgress: - this.required_obj = proj.getQuest(required_obj_id); - if (this.required_obj != null && this.required_value != null) { - QuestStage stage = ((Quest)this.required_obj).getStage(this.required_value); - if (stage != null) { - stage.addBacklink((GameDataElement) this.parent); - } - } - break; - case consumedBonemeals: - case skillLevel: - case spentGold: - case timerElapsed: - case factionScore: - case factionScoreEquals: - case random: - case date: - case dateEquals: - case time: - case timeEquals: - break; - } - if (this.required_obj != null) this.required_obj.addBacklink((GameDataElement) this.parent); - this.state = State.linked; - } - - @Override - public GameDataElement clone() { - return clone(null); - } - - public GameDataElement clone(GameDataElement parent) { - Requirement clone = new Requirement(); - clone.parent = parent; - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.required_obj_id = this.required_obj_id; - clone.required_value = this.required_value; - clone.negated = this.negated; - clone.required_obj = this.required_obj; - clone.type = this.type; - if (clone.required_obj != null && parent != null) { - clone.required_obj.addBacklink(parent); - } - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (this.required_obj == oldOne) { - oldOne.removeBacklink((GameDataElement) this.parent); - this.required_obj = newOne; - if (newOne != null) newOne.addBacklink((GameDataElement) this.parent); - } - if (oldOne instanceof QuestStage) { - if (this.required_obj != null && this.required_obj.equals(oldOne.parent) && this.required_value != null && this.required_value.equals(((QuestStage) oldOne).progress)) { - oldOne.removeBacklink((GameDataElement) this.parent); - if (newOne != null) newOne.addBacklink((GameDataElement) this.parent); - } - } - } - @Override - public String getProjectFilename() { - throw new Error("Thou shalt not reach this method."); - } - - public void changeType(RequirementType destType) { - if (COMPATIBLE_TYPES.get(type) == null || !COMPATIBLE_TYPES.get(type).contains(destType)) { - required_obj = null; - required_obj_id = null; - required_value = null; - } - - if(destType==RequirementType.random) - { - required_obj_id = "50/100"; - } - - type = destType; - } + List countedItemTypes = new ArrayList(); + countedItemTypes.add(RequirementType.inventoryRemove); + countedItemTypes.add(RequirementType.inventoryKeep); + countedItemTypes.add(RequirementType.usedItem); + countedItemTypes.add(RequirementType.wear); + countedItemTypes.add(RequirementType.wearRemove); + COMPATIBLE_TYPES.put(RequirementType.inventoryRemove, countedItemTypes); + COMPATIBLE_TYPES.put(RequirementType.inventoryKeep, countedItemTypes); + COMPATIBLE_TYPES.put(RequirementType.usedItem, countedItemTypes); + COMPATIBLE_TYPES.put(RequirementType.wear, countedItemTypes); + COMPATIBLE_TYPES.put(RequirementType.wearRemove, countedItemTypes); + } + + //Available from parsed state + public RequirementType type = null; + public String required_obj_id = null; + public Integer required_value = null; + public Boolean negated = null; + + //Available from linked state + public GameDataElement required_obj = null; + + public enum RequirementType { + questProgress, + questLatestProgress, + inventoryRemove, + inventoryKeep, + wear, + skillLevel, + killedMonster, + timerElapsed, + usedItem, + spentGold, + consumedBonemeals, + hasActorCondition, + factionScore, + random, + factionScoreEquals, + wearRemove, + date, + dateEquals, + time, + timeEquals + } + + public enum SkillID { + weaponChance, weaponDmg, barter, dodge, barkSkin, moreCriticals, betterCriticals, speed // Raises max ap + , coinfinder, moreExp, cleave // +10ap on kill + , eater // +1hp per kill + , fortitude // +N hp per levelup + , evasion // increase successful flee chance & reduce chance of monster attack + , regeneration // +N hp per round + , lowerExploss, magicfinder, resistanceMental // lowers chance to get negative active conditions by monsters (Mental like Dazed) + , resistancePhysical // lowers chance to get negative active conditions by monsters (Physical Capacity like Minor fatigue) + , resistanceBlood // lowers chance to get negative active conditions by monsters (Blood Disorder like Weak Poison) + , shadowBless, sporeImmunity, crit1 // lowers atk ability + , crit2 // lowers def ability ,rejuvenation // Reduces magnitudes of conditions + , rejuvenation // Reduces magnitudes of conditions + , taunt // Causes AP loss of attackers that miss + , concussion // AC loss for monsters with (AC-BC)>N + , weaponProficiencyDagger, weaponProficiency1hsword, weaponProficiency2hsword, weaponProficiencyAxe, weaponProficiencyBlunt, weaponProficiencyUnarmed, weaponProficiencyPole, armorProficiencyShield, armorProficiencyUnarmored, armorProficiencyLight, armorProficiencyHeavy, fightstyleDualWield, fightstyle2hand, fightstyleWeaponShield, specializationDualWield, specialization2hand, specializationWeaponShield + } + + @Override + public String getDesc() { + String obj_id = ""; + if (required_obj_id != null) { + obj_id = required_obj_id; + if (type != null && type == RequirementType.random) { + obj_id = " Chance " + obj_id + (required_obj_id.contains("/") ? "" : "%"); + } else { + obj_id += ":"; + } + } + + return ((negated != null && negated) ? "NOT " : "") + + (type == null ? "" : type.toString() + ":") + + obj_id + + (required_value == null ? "" : required_value.toString()); + } + + @Override + public void parse() { + throw new Error("Thou shalt not reach this method."); + } + + @SuppressWarnings("rawtypes") + @Override + public Map toJson() { + throw new Error("Thou shalt not reach this method."); + } + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map jsonObj) { + throw new Error("Thou shalt not reach this method."); + } + + @Override + public void link() { + if (!this.linkCheck()) return; + Project proj = getProject(); + if (proj == null) { + Notification.addError("Error linking requirement " + getDesc() + ". No parent project found."); + return; + } + switch (type) { + case hasActorCondition: + this.required_obj = proj.getActorCondition(required_obj_id); + break; + case inventoryKeep: + case inventoryRemove: + case usedItem: + case wear: + case wearRemove: + this.required_obj = proj.getItem(required_obj_id); + break; + case killedMonster: + this.required_obj = proj.getNPC(required_obj_id); + break; + case questLatestProgress: + case questProgress: + this.required_obj = proj.getQuest(required_obj_id); + if (this.required_obj != null && this.required_value != null) { + QuestStage stage = ((Quest) this.required_obj).getStage(this.required_value); + if (stage != null) { + stage.addBacklink((GameDataElement) this.parent); + } + } + break; + case consumedBonemeals: + case skillLevel: + case spentGold: + case timerElapsed: + case factionScore: + case factionScoreEquals: + case random: + case date: + case dateEquals: + case time: + case timeEquals: + break; + } + if (this.required_obj != null) this.required_obj.addBacklink((GameDataElement) this.parent); + this.state = State.linked; + } + + @Override + public GameDataElement clone() { + return clone(null); + } + + public GameDataElement clone(GameDataElement parent) { + Requirement clone = new Requirement(); + clone.parent = parent; + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.required_obj_id = this.required_obj_id; + clone.required_value = this.required_value; + clone.negated = this.negated; + clone.required_obj = this.required_obj; + clone.type = this.type; + if (clone.required_obj != null && parent != null) { + clone.required_obj.addBacklink(parent); + } + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (this.required_obj == oldOne) { + oldOne.removeBacklink((GameDataElement) this.parent); + this.required_obj = newOne; + if (newOne != null) newOne.addBacklink((GameDataElement) this.parent); + } + if (oldOne instanceof QuestStage) { + if (this.required_obj != null && this.required_obj.equals(oldOne.parent) && this.required_value != null && this.required_value.equals(((QuestStage) oldOne).progress)) { + oldOne.removeBacklink((GameDataElement) this.parent); + if (newOne != null) newOne.addBacklink((GameDataElement) this.parent); + } + } + } + + @Override + public String getProjectFilename() { + throw new Error("Thou shalt not reach this method."); + } + + public void changeType(RequirementType destType) { + if (COMPATIBLE_TYPES.get(type) == null || !COMPATIBLE_TYPES.get(type).contains(destType)) { + required_obj = null; + required_obj_id = null; + required_value = null; + } + + if (destType == RequirementType.random) { + required_obj_id = "50/100"; + } + + type = destType; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/ContainerArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/ContainerArea.java index a5e94f5..85b60c2 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/ContainerArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/ContainerArea.java @@ -1,45 +1,46 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; + public class ContainerArea extends MapObject { - public Droplist droplist = null; - - public ContainerArea(tiled.core.MapObject obj) {} - - @Override - public void link() { - droplist = parentMap.getProject().getDroplist(name); - if (droplist != null) { - droplist.addBacklink(parentMap); - } - } - - @Override - public Image getIcon() { - if (droplist != null) return DefaultIcons.getContainerIcon(); - else return DefaultIcons.getNullifyIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (oldOne == droplist) { - oldOne.removeBacklink(parentMap); - droplist = (Droplist) newOne; - if (newOne != null) newOne.addBacklink(parentMap); - } - } - - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - if (droplist != null) { - tmxObject.setName(droplist.id); - } - } + public Droplist droplist = null; + + public ContainerArea(tiled.core.MapObject obj) { + } + + @Override + public void link() { + droplist = parentMap.getProject().getDroplist(name); + if (droplist != null) { + droplist.addBacklink(parentMap); + } + } + + @Override + public Image getIcon() { + if (droplist != null) return DefaultIcons.getContainerIcon(); + else return DefaultIcons.getNullifyIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (oldOne == droplist) { + oldOne.removeBacklink(parentMap); + droplist = (Droplist) newOne; + if (newOne != null) newOne.addBacklink(parentMap); + } + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + if (droplist != null) { + tmxObject.setName(droplist.id); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java index c5669fd..f19525a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java @@ -1,116 +1,116 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; + public class KeyArea extends MapObject { - public String dialogue_id; - public Dialogue dialogue = null; - public Requirement requirement; - public boolean oldSchoolRequirement; - - public KeyArea(tiled.core.MapObject obj) { - dialogue_id = obj.getProperties().getProperty("phrase"); - String requireType = obj.getProperties().getProperty("requireType"); - String requireId = obj.getProperties().getProperty("requireId"); - String requireValue = obj.getProperties().getProperty("requireValue"); - String requireNegation = obj.getProperties().getProperty("requireNegation"); - oldSchoolRequirement = false; - if (requireType == null) { - String[] fields = obj.getName().split(":"); - if (fields.length == 2) { - requireType = Requirement.RequirementType.questProgress.toString(); - requireValue = fields[1]; - requireId = fields[0]; - oldSchoolRequirement = true; - } else if (fields.length == 3) { - requireValue = fields[2]; - requireType = fields[0]; - requireId = fields[1]; - oldSchoolRequirement = true; - } - } - requirement = new Requirement(); - if (requireType != null) requirement.type = Requirement.RequirementType.valueOf(requireType); - requirement.required_obj_id = requireId; - if (requireValue != null) requirement.required_value = Integer.parseInt(requireValue); - if (requireNegation != null) requirement.negated = Boolean.parseBoolean(requireNegation); - requirement.state = GameDataElement.State.parsed; - - } - - @Override - public void link() { - if (dialogue_id != null) dialogue = parentMap.getProject().getDialogue(dialogue_id); - if (dialogue != null) { - dialogue.addBacklink(parentMap); - } - requirement.parent = parentMap; - requirement.link(); - } - - @Override - public Image getIcon() { - if (dialogue != null && requirement != null) return DefaultIcons.getKeyIcon(); - return DefaultIcons.getNullifyIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (oldOne == dialogue) { - oldOne.removeBacklink(parentMap); - dialogue = (Dialogue) newOne; - if (newOne != null) newOne.addBacklink(parentMap); - } - requirement.elementChanged(oldOne, newOne); - } - - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - if (dialogue != null) { - tmxObject.getProperties().setProperty("phrase", dialogue.id); - } else if (dialogue_id != null) { - tmxObject.getProperties().setProperty("phrase", dialogue_id); - } - if (requirement != null) { - if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { - tmxObject.setName(requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value))); - } else { - if (requirement.type != null) { - tmxObject.getProperties().setProperty("requireType", requirement.type.toString()); - } - if (requirement.required_obj != null) { - tmxObject.getProperties().setProperty("requireId", requirement.required_obj.id); - } else if (requirement.required_obj_id != null) { - tmxObject.getProperties().setProperty("requireId", requirement.required_obj_id); - } - if (requirement.required_value != null) { - tmxObject.getProperties().setProperty("requireValue", requirement.required_value.toString()); - } - if (requirement.negated != null) { - tmxObject.getProperties().setProperty("requireNegation", Boolean.toString(requirement.negated)); - } - } - } - } + public String dialogue_id; + public Dialogue dialogue = null; + public Requirement requirement; + public boolean oldSchoolRequirement; - public void updateNameFromRequirementChange() { - if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { - name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); - } else if (oldSchoolRequirement) { - int i = 0; - String futureName = requirement.type.toString() + "#" + Integer.toString(i); - while (parentMap.getMapObject(futureName) != null) { - i++; - futureName = requirement.type.toString() + "#" + Integer.toString(i); - } - this.name = futureName; - } - } + public KeyArea(tiled.core.MapObject obj) { + dialogue_id = obj.getProperties().getProperty("phrase"); + String requireType = obj.getProperties().getProperty("requireType"); + String requireId = obj.getProperties().getProperty("requireId"); + String requireValue = obj.getProperties().getProperty("requireValue"); + String requireNegation = obj.getProperties().getProperty("requireNegation"); + oldSchoolRequirement = false; + if (requireType == null) { + String[] fields = obj.getName().split(":"); + if (fields.length == 2) { + requireType = Requirement.RequirementType.questProgress.toString(); + requireValue = fields[1]; + requireId = fields[0]; + oldSchoolRequirement = true; + } else if (fields.length == 3) { + requireValue = fields[2]; + requireType = fields[0]; + requireId = fields[1]; + oldSchoolRequirement = true; + } + } + requirement = new Requirement(); + if (requireType != null) requirement.type = Requirement.RequirementType.valueOf(requireType); + requirement.required_obj_id = requireId; + if (requireValue != null) requirement.required_value = Integer.parseInt(requireValue); + if (requireNegation != null) requirement.negated = Boolean.parseBoolean(requireNegation); + requirement.state = GameDataElement.State.parsed; + + } + + @Override + public void link() { + if (dialogue_id != null) dialogue = parentMap.getProject().getDialogue(dialogue_id); + if (dialogue != null) { + dialogue.addBacklink(parentMap); + } + requirement.parent = parentMap; + requirement.link(); + } + + @Override + public Image getIcon() { + if (dialogue != null && requirement != null) return DefaultIcons.getKeyIcon(); + return DefaultIcons.getNullifyIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (oldOne == dialogue) { + oldOne.removeBacklink(parentMap); + dialogue = (Dialogue) newOne; + if (newOne != null) newOne.addBacklink(parentMap); + } + requirement.elementChanged(oldOne, newOne); + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + if (dialogue != null) { + tmxObject.getProperties().setProperty("phrase", dialogue.id); + } else if (dialogue_id != null) { + tmxObject.getProperties().setProperty("phrase", dialogue_id); + } + if (requirement != null) { + if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { + tmxObject.setName(requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value))); + } else { + if (requirement.type != null) { + tmxObject.getProperties().setProperty("requireType", requirement.type.toString()); + } + if (requirement.required_obj != null) { + tmxObject.getProperties().setProperty("requireId", requirement.required_obj.id); + } else if (requirement.required_obj_id != null) { + tmxObject.getProperties().setProperty("requireId", requirement.required_obj_id); + } + if (requirement.required_value != null) { + tmxObject.getProperties().setProperty("requireValue", requirement.required_value.toString()); + } + if (requirement.negated != null) { + tmxObject.getProperties().setProperty("requireNegation", Boolean.toString(requirement.negated)); + } + } + } + } + + public void updateNameFromRequirementChange() { + if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { + name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); + } else if (oldSchoolRequirement) { + int i = 0; + String futureName = requirement.type.toString() + "#" + Integer.toString(i); + while (parentMap.getMapObject(futureName) != null) { + i++; + futureName = requirement.type.toString() + "#" + Integer.toString(i); + } + this.name = futureName; + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java b/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java index 75b579d..0077c01 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/MapChange.java @@ -1,58 +1,57 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; public class MapChange extends MapObject { - public String map_id; - public TMXMap map = null; - public String place_id; - - public MapChange(tiled.core.MapObject obj) { - this.map_id = obj.getProperties().getProperty("map"); - this.place_id = obj.getProperties().getProperty("place"); - } + public String map_id; + public TMXMap map = null; + public String place_id; - @Override - public void link() { - if (map_id != null) this.map = parentMap.getProject().getMap(map_id); - if (map != null) { - map.addBacklink(parentMap); - } - //TODO reinstate this if data validation system ever exist. + public MapChange(tiled.core.MapObject obj) { + this.map_id = obj.getProperties().getProperty("map"); + this.place_id = obj.getProperties().getProperty("place"); + } + + @Override + public void link() { + if (map_id != null) this.map = parentMap.getProject().getMap(map_id); + if (map != null) { + map.addBacklink(parentMap); + } + //TODO reinstate this if data validation system ever exist. // else Notification.addWarn("Incomplete mapchange area \""+name+"\" in map \""+parentMap.id+"\". This is OK if it's an arrival only (no exit through this point)."); - } - - @Override - public Image getIcon() { - if (name != null) return DefaultIcons.getTiledIconIcon(); - else return DefaultIcons.getNullifyIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (oldOne == map) { - oldOne.removeBacklink(parentMap); - map = (TMXMap) newOne; - if (newOne != null) newOne.addBacklink(parentMap); - } - } - - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - if (map != null) { - tmxObject.getProperties().setProperty("map", map.id); - } else if (map_id != null) { - tmxObject.getProperties().setProperty("map", map_id); - } - if (place_id != null) { - tmxObject.getProperties().setProperty("place", place_id); - } - } - + } + + @Override + public Image getIcon() { + if (name != null) return DefaultIcons.getTiledIconIcon(); + else return DefaultIcons.getNullifyIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (oldOne == map) { + oldOne.removeBacklink(parentMap); + map = (TMXMap) newOne; + if (newOne != null) newOne.addBacklink(parentMap); + } + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + if (map != null) { + tmxObject.getProperties().setProperty("map", map.id); + } else if (map_id != null) { + tmxObject.getProperties().setProperty("map", map_id); + } + if (place_id != null) { + tmxObject.getProperties().setProperty("place", place_id); + } + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/MapObject.java b/src/com/gpl/rpg/atcontentstudio/model/maps/MapObject.java index 7aaf6ba..01371be 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/MapObject.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/MapObject.java @@ -1,171 +1,171 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; - import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import java.awt.*; + public abstract class MapObject { - public int x, y, w, h; - public String name; - - public TMXMap parentMap; - - public Types type; - - protected static enum Types { - mapchange, - spawn, - rest, - key, - replace, - script, - container, - sign - } - - - public static MapObject buildObject(tiled.core.MapObject obj, TMXMap parentMap) { - MapObject result = null; - if (obj.getType() != null && !obj.getType().equals("") && Types.valueOf(obj.getType()) != null) { - switch (Types.valueOf(obj.getType())) { - case key: - result = new KeyArea(obj); - result.type = Types.key; - break; - case mapchange: - result = new MapChange(obj); - result.type = Types.mapchange; - break; - case replace: - result = new ReplaceArea(obj); - result.type = Types.replace; - break; - case rest: - result = new RestArea(obj); - result.type = Types.rest; - break; - case script: - result = new ScriptArea(obj); - result.type = Types.script; - break; - case sign: - result = new SignArea(obj); - result.type = Types.sign; - break; - case spawn: - result = new SpawnArea(obj); - result.type = Types.spawn; - break; - case container: - result = new ContainerArea(obj); - result.type = Types.container; - break; - } - } else { - Notification.addWarn("Unknown map object type: "+obj.getType()+"with name "+obj.getName()+" in map "+parentMap.id); - } - if (result != null) { - result.x = obj.getX(); - result.y = obj.getY(); - result.w = obj.getWidth(); - result.h = obj.getHeight(); - result.name = obj.getName(); - result.parentMap = parentMap; - } - return result; - } - - public abstract void link(); + public int x, y, w, h; + public String name; - public abstract Image getIcon(); + public TMXMap parentMap; - public abstract void elementChanged(GameDataElement oldOne, GameDataElement newOne); + public Types type; - public tiled.core.MapObject toTmxObject() { - tiled.core.MapObject tmxObject = new tiled.core.MapObject(x, y, w, h); - tmxObject.setName(name); - tmxObject.setType(type.toString()); - savePropertiesInTmxObject(tmxObject); - return tmxObject; - } - - public abstract void savePropertiesInTmxObject(tiled.core.MapObject tmxObject); - - public static MapObject newMapchange(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Mapchange"); - MapObject result = new MapChange(obj); - result.type = Types.mapchange; - initObj(result, obj, parentMap); - return result; - } + protected static enum Types { + mapchange, + spawn, + rest, + key, + replace, + script, + container, + sign + } - public static MapObject newSpawnArea(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Spawnarea"); - MapObject result = new SpawnArea(obj); - result.type = Types.spawn; - initObj(result, obj, parentMap); - return result; - } - public static MapObject newRest(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Rest"); - MapObject result = new RestArea(obj); - result.type = Types.rest; - initObj(result, obj, parentMap); - return result; - } + public static MapObject buildObject(tiled.core.MapObject obj, TMXMap parentMap) { + MapObject result = null; + if (obj.getType() != null && !obj.getType().equals("") && Types.valueOf(obj.getType()) != null) { + switch (Types.valueOf(obj.getType())) { + case key: + result = new KeyArea(obj); + result.type = Types.key; + break; + case mapchange: + result = new MapChange(obj); + result.type = Types.mapchange; + break; + case replace: + result = new ReplaceArea(obj); + result.type = Types.replace; + break; + case rest: + result = new RestArea(obj); + result.type = Types.rest; + break; + case script: + result = new ScriptArea(obj); + result.type = Types.script; + break; + case sign: + result = new SignArea(obj); + result.type = Types.sign; + break; + case spawn: + result = new SpawnArea(obj); + result.type = Types.spawn; + break; + case container: + result = new ContainerArea(obj); + result.type = Types.container; + break; + } + } else { + Notification.addWarn("Unknown map object type: " + obj.getType() + "with name " + obj.getName() + " in map " + parentMap.id); + } + if (result != null) { + result.x = obj.getX(); + result.y = obj.getY(); + result.w = obj.getWidth(); + result.h = obj.getHeight(); + result.name = obj.getName(); + result.parentMap = parentMap; + } + return result; + } - public static MapObject newKey(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Key"); - MapObject result = new KeyArea(obj); - result.type = Types.key; - initObj(result, obj, parentMap); - return result; - } + public abstract void link(); - public static MapObject newReplace(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Replace"); - MapObject result = new ReplaceArea(obj); - result.type = Types.replace; - initObj(result, obj, parentMap); - return result; - } + public abstract Image getIcon(); - public static MapObject newScript(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Script"); - MapObject result = new ScriptArea(obj); - result.type = Types.script; - initObj(result, obj, parentMap); - return result; - } + public abstract void elementChanged(GameDataElement oldOne, GameDataElement newOne); + + public tiled.core.MapObject toTmxObject() { + tiled.core.MapObject tmxObject = new tiled.core.MapObject(x, y, w, h); + tmxObject.setName(name); + tmxObject.setType(type.toString()); + savePropertiesInTmxObject(tmxObject); + return tmxObject; + } + + public abstract void savePropertiesInTmxObject(tiled.core.MapObject tmxObject); + + public static MapObject newMapchange(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Mapchange"); + MapObject result = new MapChange(obj); + result.type = Types.mapchange; + initObj(result, obj, parentMap); + return result; + } + + public static MapObject newSpawnArea(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Spawnarea"); + MapObject result = new SpawnArea(obj); + result.type = Types.spawn; + initObj(result, obj, parentMap); + return result; + } + + public static MapObject newRest(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Rest"); + MapObject result = new RestArea(obj); + result.type = Types.rest; + initObj(result, obj, parentMap); + return result; + } + + public static MapObject newKey(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Key"); + MapObject result = new KeyArea(obj); + result.type = Types.key; + initObj(result, obj, parentMap); + return result; + } + + public static MapObject newReplace(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Replace"); + MapObject result = new ReplaceArea(obj); + result.type = Types.replace; + initObj(result, obj, parentMap); + return result; + } + + public static MapObject newScript(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Script"); + MapObject result = new ScriptArea(obj); + result.type = Types.script; + initObj(result, obj, parentMap); + return result; + } + + public static MapObject newContainer(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Container"); + MapObject result = new ContainerArea(obj); + result.type = Types.container; + initObj(result, obj, parentMap); + return result; + } + + public static MapObject newSign(tiled.core.MapObject obj, TMXMap parentMap) { + if (obj.getName() == null) obj.setName("Sign"); + MapObject result = new SignArea(obj); + result.type = Types.sign; + initObj(result, obj, parentMap); + return result; + } + + private static MapObject initObj(MapObject result, tiled.core.MapObject obj, TMXMap parentMap) { + result.x = obj.getX(); + result.y = obj.getY(); + result.w = obj.getWidth(); + result.h = obj.getHeight(); + result.name = obj.getName(); + result.parentMap = parentMap; + return result; + } - public static MapObject newContainer(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Container"); - MapObject result = new ContainerArea(obj); - result.type = Types.container; - initObj(result, obj, parentMap); - return result; - } - public static MapObject newSign(tiled.core.MapObject obj, TMXMap parentMap) { - if (obj.getName() == null) obj.setName("Sign"); - MapObject result = new SignArea(obj); - result.type = Types.sign; - initObj(result, obj, parentMap); - return result; - } - - private static MapObject initObj(MapObject result, tiled.core.MapObject obj, TMXMap parentMap) { - result.x = obj.getX(); - result.y = obj.getY(); - result.w = obj.getWidth(); - result.h = obj.getHeight(); - result.name = obj.getName(); - result.parentMap = parentMap; - return result; - } - - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/MapObjectGroup.java b/src/com/gpl/rpg/atcontentstudio/model/maps/MapObjectGroup.java index c2f2383..05a189f 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/MapObjectGroup.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/MapObjectGroup.java @@ -1,60 +1,60 @@ package com.gpl.rpg.atcontentstudio.model.maps; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; + import java.util.ArrayList; import java.util.List; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; - public class MapObjectGroup { - - public tiled.core.ObjectGroup tmxGroup; - public TMXMap parentMap; - public String name; - public boolean visible; - public List mapObjects = new ArrayList(); - public Boolean active; - - public MapObjectGroup(tiled.core.ObjectGroup layer, TMXMap map) { - this.tmxGroup = layer; - this.name = layer.getName(); - this.visible = layer.isVisible(); - this.parentMap = map; - if (layer.getProperties().get("active") != null) { - active = new Boolean(((String) layer.getProperties().get("active"))); - } else { - active = true; - } - for (tiled.core.MapObject obj : layer.getObjectsList()) { - mapObjects.add(MapObject.buildObject(obj, map)); - } - } - public void link() { - for (MapObject obj : mapObjects) { - obj.link(); - } - } + public tiled.core.ObjectGroup tmxGroup; + public TMXMap parentMap; + public String name; + public boolean visible; + public List mapObjects = new ArrayList(); + public Boolean active; - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - for (MapObject object : mapObjects) { - object.elementChanged(oldOne, newOne); - } - } + public MapObjectGroup(tiled.core.ObjectGroup layer, TMXMap map) { + this.tmxGroup = layer; + this.name = layer.getName(); + this.visible = layer.isVisible(); + this.parentMap = map; + if (layer.getProperties().get("active") != null) { + active = new Boolean(((String) layer.getProperties().get("active"))); + } else { + active = true; + } + for (tiled.core.MapObject obj : layer.getObjectsList()) { + mapObjects.add(MapObject.buildObject(obj, map)); + } + } - public void pushBackToTiledProperties() { - if (tmxGroup != null) { - tmxGroup.clear(); - } else { - tmxGroup = new tiled.core.ObjectGroup(); - } - tmxGroup.setVisible(visible); - tmxGroup.setName(name); - if (!active) { - tmxGroup.getProperties().put("active", Boolean.toString(active)); - } - for (MapObject object : mapObjects) { - tmxGroup.addObject(object.toTmxObject()); - } - } + public void link() { + for (MapObject obj : mapObjects) { + obj.link(); + } + } + + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + for (MapObject object : mapObjects) { + object.elementChanged(oldOne, newOne); + } + } + + public void pushBackToTiledProperties() { + if (tmxGroup != null) { + tmxGroup.clear(); + } else { + tmxGroup = new tiled.core.ObjectGroup(); + } + tmxGroup.setVisible(visible); + tmxGroup.setName(name); + if (!active) { + tmxGroup.getProperties().put("active", Boolean.toString(active)); + } + for (MapObject object : mapObjects) { + tmxGroup.addObject(object.toTmxObject()); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java index b14d41d..4438c69 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java @@ -1,132 +1,133 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; -import java.util.ArrayList; -import java.util.List; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; + public class ReplaceArea extends MapObject { - public Requirement requirement; - public boolean oldSchoolRequirement = false; - - public List replacements = null; + public Requirement requirement; + public boolean oldSchoolRequirement = false; - public ReplaceArea(tiled.core.MapObject obj) { - String requireType = obj.getProperties().getProperty("requireType"); - String requireId = obj.getProperties().getProperty("requireId"); - String requireValue = obj.getProperties().getProperty("requireValue"); - String requireNegation = obj.getProperties().getProperty("requireNegation"); - if (requireType == null) { - String[] fields = obj.getName().split(":"); - if (fields.length == 2) { - requireType = Requirement.RequirementType.questProgress.toString(); - requireValue = fields[1]; - requireId = fields[0]; - oldSchoolRequirement = true; - } /*else if (fields.length == 3) { + public List replacements = null; + + public ReplaceArea(tiled.core.MapObject obj) { + String requireType = obj.getProperties().getProperty("requireType"); + String requireId = obj.getProperties().getProperty("requireId"); + String requireValue = obj.getProperties().getProperty("requireValue"); + String requireNegation = obj.getProperties().getProperty("requireNegation"); + if (requireType == null) { + String[] fields = obj.getName().split(":"); + if (fields.length == 2) { + requireType = Requirement.RequirementType.questProgress.toString(); + requireValue = fields[1]; + requireId = fields[0]; + oldSchoolRequirement = true; + } /*else if (fields.length == 3) { requireValue = fields[2]; requireType = fields[0]; requireId = fields[1]; }*/ - } - requirement = new Requirement(); - if (requireType != null) requirement.type = Requirement.RequirementType.valueOf(requireType); - requirement.required_obj_id = requireId; - if (requireValue != null) requirement.required_value = Integer.parseInt(requireValue); - if (requireNegation != null) requirement.negated = Boolean.parseBoolean(requireNegation); - requirement.state = GameDataElement.State.parsed; - - - for (Object s : obj.getProperties().keySet()) { - if (!TMXMap.isPaintedLayerName(s.toString())) continue; - if (replacements == null) replacements = new ArrayList(); - replacements.add(new Replacement(s.toString(), obj.getProperties().getProperty(s.toString()))); - } - - } + } + requirement = new Requirement(); + if (requireType != null) requirement.type = Requirement.RequirementType.valueOf(requireType); + requirement.required_obj_id = requireId; + if (requireValue != null) requirement.required_value = Integer.parseInt(requireValue); + if (requireNegation != null) requirement.negated = Boolean.parseBoolean(requireNegation); + requirement.state = GameDataElement.State.parsed; - @Override - public void link() { - requirement.parent = parentMap; - requirement.link(); - } - - @Override - public Image getIcon() { - return DefaultIcons.getReplaceIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - requirement.elementChanged(oldOne, newOne); - } - public ReplaceArea.Replacement createReplacement(String source, String target) { - Replacement repl = new Replacement(source, target); - return repl; - } + for (Object s : obj.getProperties().keySet()) { + if (!TMXMap.isPaintedLayerName(s.toString())) continue; + if (replacements == null) replacements = new ArrayList(); + replacements.add(new Replacement(s.toString(), obj.getProperties().getProperty(s.toString()))); + } - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - if (replacements != null) { - for(Replacement r : replacements) - tmxObject.getProperties().setProperty(r.sourceLayer, r.targetLayer); - } - if (requirement != null) { - if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { - tmxObject.setName(requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value))); - } else { - if (requirement.type != null) { - tmxObject.getProperties().setProperty("requireType", requirement.type.toString()); - } - if (requirement.required_obj != null) { - tmxObject.getProperties().setProperty("requireId", requirement.required_obj.id); - } else if (requirement.required_obj_id != null) { - tmxObject.getProperties().setProperty("requireId", requirement.required_obj_id); - } - if (requirement.required_value != null) { - tmxObject.getProperties().setProperty("requireValue", requirement.required_value.toString()); - } - if (requirement.negated != null) { - tmxObject.getProperties().setProperty("requireNegation", Boolean.toString(requirement.negated)); - } - } - } - } + } - //Don't use yet ! - public void updateNameFromRequirementChange() { - if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { - name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id+":"+((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); - } else if (oldSchoolRequirement) { - int i = 0; - String futureName = requirement.type.toString() + "#" + Integer.toString(i); - while (parentMap.getMapObject(futureName) != null) { - i++; - futureName = requirement.type.toString() + "#" + Integer.toString(i); - } - this.name = futureName; - } - } - - public class Replacement { - public String sourceLayer, targetLayer; - public Replacement(String source, String target) { - this.sourceLayer = source; - this.targetLayer = target; - } - } + @Override + public void link() { + requirement.parent = parentMap; + requirement.link(); + } - public boolean hasReplacementFor(String name) { - if (name == null) return false; - for (Replacement repl : replacements) { - if (name.equalsIgnoreCase(repl.sourceLayer)) return true; - } - return false; - } + @Override + public Image getIcon() { + return DefaultIcons.getReplaceIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + requirement.elementChanged(oldOne, newOne); + } + + public ReplaceArea.Replacement createReplacement(String source, String target) { + Replacement repl = new Replacement(source, target); + return repl; + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + if (replacements != null) { + for (Replacement r : replacements) + tmxObject.getProperties().setProperty(r.sourceLayer, r.targetLayer); + } + if (requirement != null) { + if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { + tmxObject.setName(requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value))); + } else { + if (requirement.type != null) { + tmxObject.getProperties().setProperty("requireType", requirement.type.toString()); + } + if (requirement.required_obj != null) { + tmxObject.getProperties().setProperty("requireId", requirement.required_obj.id); + } else if (requirement.required_obj_id != null) { + tmxObject.getProperties().setProperty("requireId", requirement.required_obj_id); + } + if (requirement.required_value != null) { + tmxObject.getProperties().setProperty("requireValue", requirement.required_value.toString()); + } + if (requirement.negated != null) { + tmxObject.getProperties().setProperty("requireNegation", Boolean.toString(requirement.negated)); + } + } + } + } + + //Don't use yet ! + public void updateNameFromRequirementChange() { + if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { + name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); + } else if (oldSchoolRequirement) { + int i = 0; + String futureName = requirement.type.toString() + "#" + Integer.toString(i); + while (parentMap.getMapObject(futureName) != null) { + i++; + futureName = requirement.type.toString() + "#" + Integer.toString(i); + } + this.name = futureName; + } + } + + public class Replacement { + public String sourceLayer, targetLayer; + + public Replacement(String source, String target) { + this.sourceLayer = source; + this.targetLayer = target; + } + } + + public boolean hasReplacementFor(String name) { + if (name == null) return false; + for (Replacement repl : replacements) { + if (name.equalsIgnoreCase(repl.sourceLayer)) return true; + } + return false; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/RestArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/RestArea.java index 14f8f26..f5b453c 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/RestArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/RestArea.java @@ -1,31 +1,33 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; + public class RestArea extends MapObject { - public RestArea(tiled.core.MapObject obj) {} + public RestArea(tiled.core.MapObject obj) { + } + + @Override + public void link() { + } + + @Override + public Image getIcon() { + return DefaultIcons.getRestIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + + } - @Override - public void link() {} - - @Override - public Image getIcon() { - return DefaultIcons.getRestIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - - } - - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/ScriptArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/ScriptArea.java index 50bb2a2..3f862a2 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/ScriptArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/ScriptArea.java @@ -1,61 +1,61 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -public class ScriptArea extends MapObject { - - public Dialogue dialogue = null; - public EvaluationTrigger trigger_type = null; - - public enum EvaluationTrigger { - enter, - step, - round, - always - } +import java.awt.*; - public ScriptArea(tiled.core.MapObject obj) { - String triggerTypeId = obj.getProperties().getProperty("when"); - if (triggerTypeId != null) { - trigger_type = EvaluationTrigger.valueOf(triggerTypeId); - } - } - - @Override - public void link() { - if (name != null) dialogue = parentMap.getProject().getDialogue(name); - if (dialogue != null) { - dialogue.addBacklink(parentMap); - } - } - - @Override - public Image getIcon() { - if (dialogue != null) return DefaultIcons.getScriptIcon(); - else return DefaultIcons.getNullifyIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (oldOne == dialogue) { - oldOne.removeBacklink(parentMap); - dialogue = (Dialogue) newOne; - if (newOne != null) newOne.addBacklink(parentMap); - } - } - - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - if (dialogue != null) { - tmxObject.setName(dialogue.id); - } - if (trigger_type != null) { - tmxObject.getProperties().setProperty("when", trigger_type.toString()); - } - } +public class ScriptArea extends MapObject { + + public Dialogue dialogue = null; + public EvaluationTrigger trigger_type = null; + + public enum EvaluationTrigger { + enter, + step, + round, + always + } + + public ScriptArea(tiled.core.MapObject obj) { + String triggerTypeId = obj.getProperties().getProperty("when"); + if (triggerTypeId != null) { + trigger_type = EvaluationTrigger.valueOf(triggerTypeId); + } + } + + @Override + public void link() { + if (name != null) dialogue = parentMap.getProject().getDialogue(name); + if (dialogue != null) { + dialogue.addBacklink(parentMap); + } + } + + @Override + public Image getIcon() { + if (dialogue != null) return DefaultIcons.getScriptIcon(); + else return DefaultIcons.getNullifyIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (oldOne == dialogue) { + oldOne.removeBacklink(parentMap); + dialogue = (Dialogue) newOne; + if (newOne != null) newOne.addBacklink(parentMap); + } + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + if (dialogue != null) { + tmxObject.setName(dialogue.id); + } + if (trigger_type != null) { + tmxObject.getProperties().setProperty("when", trigger_type.toString()); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/SignArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/SignArea.java index d968a30..33be944 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/SignArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/SignArea.java @@ -1,47 +1,47 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; + public class SignArea extends MapObject { - public Dialogue dialogue = null; - - public SignArea(tiled.core.MapObject obj) { - - } + public Dialogue dialogue = null; + + public SignArea(tiled.core.MapObject obj) { + + } + + @Override + public void link() { + if (name != null) dialogue = parentMap.getProject().getDialogue(name); + if (dialogue != null) { + dialogue.addBacklink(parentMap); + } + } + + @Override + public Image getIcon() { + if (dialogue != null) return DefaultIcons.getSignIcon(); + else return DefaultIcons.getNullifyIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (oldOne == dialogue) { + oldOne.removeBacklink(parentMap); + dialogue = (Dialogue) newOne; + if (newOne != null) newOne.addBacklink(parentMap); + } + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + if (dialogue != null) { + tmxObject.setName(dialogue.id); + } + } - @Override - public void link() { - if (name != null) dialogue = parentMap.getProject().getDialogue(name); - if (dialogue != null) { - dialogue.addBacklink(parentMap); - } - } - - @Override - public Image getIcon() { - if (dialogue != null) return DefaultIcons.getSignIcon(); - else return DefaultIcons.getNullifyIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (oldOne == dialogue) { - oldOne.removeBacklink(parentMap); - dialogue = (Dialogue) newOne; - if (newOne != null) newOne.addBacklink(parentMap); - } - } - - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - if (dialogue != null) { - tmxObject.setName(dialogue.id); - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/SpawnArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/SpawnArea.java index 600d9f4..e90450b 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/SpawnArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/SpawnArea.java @@ -1,95 +1,95 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; -import java.util.ArrayList; -import java.util.List; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; + public class SpawnArea extends MapObject { - public int quantity = 1; - public int respawnSpeed = 10; - public boolean active = true; - public boolean ignoreAreas = false; - public String spawngroup_id; - public List spawnGroup = new ArrayList(); - - public SpawnArea(tiled.core.MapObject obj) { - if (obj.getProperties().getProperty("quantity") != null) { - this.quantity = Integer.parseInt(obj.getProperties().getProperty("quantity")); - } - if (obj.getProperties().getProperty("respawnspeed") != null) { - this.respawnSpeed = Integer.parseInt(obj.getProperties().getProperty("respawnspeed")); - } - if (obj.getProperties().getProperty("active") != null) { - this.active = Boolean.parseBoolean(obj.getProperties().getProperty("active")); - } - if (obj.getProperties().getProperty("ignoreAreas") != null) { - this.ignoreAreas = Boolean.parseBoolean(obj.getProperties().getProperty("ignoreAreas")); - } - if (obj.getProperties().getProperty("spawngroup") != null) { - this.spawngroup_id = obj.getProperties().getProperty("spawngroup"); - } else if (obj.getName() != null ){ - this.spawngroup_id = obj.getName(); - } - } + public int quantity = 1; + public int respawnSpeed = 10; + public boolean active = true; + public boolean ignoreAreas = false; + public String spawngroup_id; + public List spawnGroup = new ArrayList(); - @Override - public void link() { - if (spawngroup_id != null) { - spawnGroup = parentMap.getProject().getSpawnGroup(spawngroup_id); - } else { - spawnGroup = new ArrayList(); - } - if (spawnGroup != null) { - for (NPC npc : spawnGroup) { - npc.addBacklink(parentMap); - } - } - } - - @Override - public Image getIcon() { - if (spawnGroup != null && !spawnGroup.isEmpty()) { - return spawnGroup.get(0).getIcon(); - } - return DefaultIcons.getNullifyIcon(); - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - int replacedIndex = -1; - for (NPC npc : spawnGroup) { - if (npc == oldOne) { - replacedIndex = spawnGroup.indexOf(npc); - } - } - if (replacedIndex >= 0) { - oldOne.removeBacklink(parentMap); - spawnGroup.set(replacedIndex, (NPC) newOne); - if (newOne != null) newOne.addBacklink(parentMap); - } - } - - @Override - public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { - if (spawngroup_id != null) { - tmxObject.getProperties().setProperty("spawngroup", spawngroup_id); - } - if (quantity != 1) { - tmxObject.getProperties().setProperty("quantity", Integer.toString(quantity)); - } - if (respawnSpeed != 10) { - tmxObject.getProperties().setProperty("respawnspeed", Integer.toString(respawnSpeed)); - } - if (!this.active) { - tmxObject.getProperties().setProperty("active", Boolean.toString(active)); - } - if (this.ignoreAreas) { - tmxObject.getProperties().setProperty("ignoreAreas", Boolean.toString(ignoreAreas)); - } - } + public SpawnArea(tiled.core.MapObject obj) { + if (obj.getProperties().getProperty("quantity") != null) { + this.quantity = Integer.parseInt(obj.getProperties().getProperty("quantity")); + } + if (obj.getProperties().getProperty("respawnspeed") != null) { + this.respawnSpeed = Integer.parseInt(obj.getProperties().getProperty("respawnspeed")); + } + if (obj.getProperties().getProperty("active") != null) { + this.active = Boolean.parseBoolean(obj.getProperties().getProperty("active")); + } + if (obj.getProperties().getProperty("ignoreAreas") != null) { + this.ignoreAreas = Boolean.parseBoolean(obj.getProperties().getProperty("ignoreAreas")); + } + if (obj.getProperties().getProperty("spawngroup") != null) { + this.spawngroup_id = obj.getProperties().getProperty("spawngroup"); + } else if (obj.getName() != null) { + this.spawngroup_id = obj.getName(); + } + } + + @Override + public void link() { + if (spawngroup_id != null) { + spawnGroup = parentMap.getProject().getSpawnGroup(spawngroup_id); + } else { + spawnGroup = new ArrayList(); + } + if (spawnGroup != null) { + for (NPC npc : spawnGroup) { + npc.addBacklink(parentMap); + } + } + } + + @Override + public Image getIcon() { + if (spawnGroup != null && !spawnGroup.isEmpty()) { + return spawnGroup.get(0).getIcon(); + } + return DefaultIcons.getNullifyIcon(); + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + int replacedIndex = -1; + for (NPC npc : spawnGroup) { + if (npc == oldOne) { + replacedIndex = spawnGroup.indexOf(npc); + } + } + if (replacedIndex >= 0) { + oldOne.removeBacklink(parentMap); + spawnGroup.set(replacedIndex, (NPC) newOne); + if (newOne != null) newOne.addBacklink(parentMap); + } + } + + @Override + public void savePropertiesInTmxObject(tiled.core.MapObject tmxObject) { + if (spawngroup_id != null) { + tmxObject.getProperties().setProperty("spawngroup", spawngroup_id); + } + if (quantity != 1) { + tmxObject.getProperties().setProperty("quantity", Integer.toString(quantity)); + } + if (respawnSpeed != 10) { + tmxObject.getProperties().setProperty("respawnspeed", Integer.toString(respawnSpeed)); + } + if (!this.active) { + tmxObject.getProperties().setProperty("active", Boolean.toString(active)); + } + if (this.ignoreAreas) { + tmxObject.getProperties().setProperty("ignoreAreas", Boolean.toString(ignoreAreas)); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java index 8691bf1..ea89ed8 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMap.java @@ -1,478 +1,476 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringReader; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.tree.TreeNode; - -import tiled.io.TMXMapReader; -import tiled.io.TMXMapWriter; - import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.*; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import tiled.io.TMXMapReader; +import tiled.io.TMXMapWriter; + +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.*; +import java.util.List; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; public class TMXMap extends GameDataElement { - private static final long serialVersionUID = 1609502879500898837L; - - public static final String GROUND_LAYER_NAME = "Ground"; - public static final String OBJECTS_LAYER_NAME = "Objects"; - public static final String ABOVE_LAYER_NAME = "Above"; - public static final String TOP_LAYER_NAME = "Top"; - public static final String WALKABLE_LAYER_NAME = "Walkable"; - - public enum ColorFilter { - none, - black20, - black40, - black60, - black80, - invert, - bw, - redtint, - greentint, - bluetint - } - - public File tmxFile; - public tiled.core.Map tmxMap = null; - public Set usedSpritesheets = null; - public List groups = null; - - public ProjectTreeNode parent; - public Integer outside = null; - public ColorFilter colorFilter = null; + private static final long serialVersionUID = 1609502879500898837L; - public boolean changedOnDisk = false; - public int dismissNextChangeNotif = 0; + public static final String GROUND_LAYER_NAME = "Ground"; + public static final String OBJECTS_LAYER_NAME = "Objects"; + public static final String ABOVE_LAYER_NAME = "Above"; + public static final String TOP_LAYER_NAME = "Top"; + public static final String WALKABLE_LAYER_NAME = "Walkable"; - public TMXMap(TMXMapSet parent, File f) { - this.parent = parent; - this.tmxFile = f; - String name = f.getName(); - id = name.substring(0, name.length() - 4); - } - - public void parse() { - if (this.state == GameDataElement.State.init) { - if (tmxMap != null) return; - usedSpritesheets = new HashSet(); - try { - tmxMap = new TMXMapReader().readMap(tmxFile.getAbsolutePath(), this); - if (tmxMap.getProperties().get("outdoors") != null) { - outside = new Integer(((String) tmxMap.getProperties().get("outdoors"))); - } - if (tmxMap.getProperties().get("colorfilter") != null) { - colorFilter = ColorFilter.valueOf(((String) tmxMap.getProperties().get("colorfilter"))); - } - } catch (FileNotFoundException e) { - Notification.addError("Impossible to load TMX map file "+tmxFile.getAbsolutePath()); - } catch (Exception e) { - Notification.addError("Error while loading TMX map file "+tmxFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } - for (tiled.core.MapLayer layer : tmxMap.getLayers()) { - if (layer instanceof tiled.core.ObjectGroup) { - if (groups == null) { - groups = new ArrayList(); - } - MapObjectGroup group = new MapObjectGroup((tiled.core.ObjectGroup) layer, this); - groups.add(group); - } - } - for (Spritesheet s : usedSpritesheets) { - s.addBacklink(this); - } - state = State.parsed; - } - } - - public void create() { - if (tmxMap != null) return; - tmxMap = new tiled.core.Map(30, 30); - } - - public TMXMap clone() { - TMXMap clone = new TMXMap((TMXMapSet) this.parent, this.tmxFile); - try { - clone.usedSpritesheets = new HashSet(); - clone.tmxMap = new TMXMapReader().readMap(new StringReader(this.toXml()), clone); - if (clone.tmxMap.getProperties().get("outdoors") != null) { - clone.outside = new Integer(((String) clone.tmxMap.getProperties().get("outdoors"))); - } - if (clone.tmxMap.getProperties().get("colorfilter") != null) { - clone.colorFilter = ColorFilter.valueOf(((String) tmxMap.getProperties().get("colorfilter"))); - } - for (tiled.core.MapLayer layer : clone.tmxMap.getLayers()) { - if (layer instanceof tiled.core.ObjectGroup) { - if (clone.groups == null) { - clone.groups = new ArrayList(); - } - MapObjectGroup group = new MapObjectGroup((tiled.core.ObjectGroup) layer, this); - group.link(); - clone.groups.add(group); - } - } - for (Spritesheet s : usedSpritesheets) { - s.addBacklink(clone); - } - } catch (Exception e) { - Notification.addError("Error while cloning map "+this.id+" : "+e.getMessage()); - e.printStackTrace(); - } - - return clone; - } - - @Override - public Enumeration children() { - return null; - } + public enum ColorFilter { + none, + black20, + black40, + black60, + black80, + invert, + bw, + redtint, + greentint, + bluetint + } - @Override - public boolean getAllowsChildren() { - return false; - } + public File tmxFile; + public tiled.core.Map tmxMap = null; + public Set usedSpritesheets = null; + public List groups = null; - @Override - public TreeNode getChildAt(int arg0) { - return null; - } + public ProjectTreeNode parent; + public Integer outside = null; + public ColorFilter colorFilter = null; - @Override - public int getChildCount() { - return 0; - } + public boolean changedOnDisk = false; + public int dismissNextChangeNotif = 0; - @Override - public int getIndex(TreeNode arg0) { - return 0; - } + public TMXMap(TMXMapSet parent, File f) { + this.parent = parent; + this.tmxFile = f; + String name = f.getName(); + id = name.substring(0, name.length() - 4); + } - @Override - public TreeNode getParent() { - return parent; - } + public void parse() { + if (this.state == GameDataElement.State.init) { + if (tmxMap != null) return; + usedSpritesheets = new HashSet(); + try { + tmxMap = new TMXMapReader().readMap(tmxFile.getAbsolutePath(), this); + if (tmxMap.getProperties().get("outdoors") != null) { + outside = new Integer(((String) tmxMap.getProperties().get("outdoors"))); + } + if (tmxMap.getProperties().get("colorfilter") != null) { + colorFilter = ColorFilter.valueOf(((String) tmxMap.getProperties().get("colorfilter"))); + } + } catch (FileNotFoundException e) { + Notification.addError("Impossible to load TMX map file " + tmxFile.getAbsolutePath()); + } catch (Exception e) { + Notification.addError("Error while loading TMX map file " + tmxFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } + for (tiled.core.MapLayer layer : tmxMap.getLayers()) { + if (layer instanceof tiled.core.ObjectGroup) { + if (groups == null) { + groups = new ArrayList(); + } + MapObjectGroup group = new MapObjectGroup((tiled.core.ObjectGroup) layer, this); + groups.add(group); + } + } + for (Spritesheet s : usedSpritesheets) { + s.addBacklink(this); + } + state = State.parsed; + } + } - @Override - public boolean isLeaf() { - return true; - } + public void create() { + if (tmxMap != null) return; + tmxMap = new tiled.core.Map(30, 30); + } - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } + public TMXMap clone() { + TMXMap clone = new TMXMap((TMXMapSet) this.parent, this.tmxFile); + try { + clone.usedSpritesheets = new HashSet(); + clone.tmxMap = new TMXMapReader().readMap(new StringReader(this.toXml()), clone); + if (clone.tmxMap.getProperties().get("outdoors") != null) { + clone.outside = new Integer(((String) clone.tmxMap.getProperties().get("outdoors"))); + } + if (clone.tmxMap.getProperties().get("colorfilter") != null) { + clone.colorFilter = ColorFilter.valueOf(((String) tmxMap.getProperties().get("colorfilter"))); + } + for (tiled.core.MapLayer layer : clone.tmxMap.getLayers()) { + if (layer instanceof tiled.core.ObjectGroup) { + if (clone.groups == null) { + clone.groups = new ArrayList(); + } + MapObjectGroup group = new MapObjectGroup((tiled.core.ObjectGroup) layer, this); + group.link(); + clone.groups.add(group); + } + } + for (Spritesheet s : usedSpritesheets) { + s.addBacklink(clone); + } + } catch (Exception e) { + Notification.addError("Error while cloning map " + this.id + " : " + e.getMessage()); + e.printStackTrace(); + } - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } + return clone; + } - @Override - public void childrenRemoved(List path) { - path.add(0,this); - parent.childrenRemoved(path); - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+id; - } - - @Override - public Project getProject() { - return parent.getProject(); - } + @Override + public Enumeration children() { + return null; + } - @Override - public Image getIcon() { - return DefaultIcons.getTiledIconIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getTiledIconIcon(); - } - @Override - public Image getClosedIcon() {return null;} - @Override - public Image getOpenIcon() {return null;} - - @Override - public GameDataSet getDataSet() { - return null; - } - - @Override - public Type getDataType() { - return parent.getDataType(); - } + @Override + public boolean getAllowsChildren() { + return false; + } - public String toXml() { - if (outside != null && outside == 1) { - tmxMap.getProperties().put("outdoors", Integer.toString(outside)); - } else { - tmxMap.getProperties().remove("outdoors"); - } - if (colorFilter != null) { - tmxMap.getProperties().put("colorfilter", colorFilter.toString()); - } else { - tmxMap.getProperties().remove("colorfilter"); - } - - for (MapObjectGroup group : groups) { - group.pushBackToTiledProperties(); - if (!tmxMap.containsLayer(group.tmxGroup)) { - tmxMap.addLayer(group.tmxGroup); - } - } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - TMXMapWriter writer = new TMXMapWriter(); - writer.settings.layerCompressionMethod = TMXMapWriter.Settings.LAYER_COMPRESSION_METHOD_ZLIB; - if (getDataType() == GameSource.Type.source) { - writer.writeMap(tmxMap, baos, tmxFile.getAbsolutePath()); - } else { - writer.writeMap(tmxMap, baos, ((TMXMapSet)this.parent).mapFolder.getAbsolutePath()+File.separator+"placeholder.tmx"); - } - } catch (Exception e) { - Notification.addError("Error while converting map "+getDesc()+" to XML: "+e.getMessage()); - e.printStackTrace(); - } - return baos.toString(); - } - - @Override - public boolean isEmpty() { - return false; - } + @Override + public TreeNode getChildAt(int arg0) { + return null; + } - public void save() { - if (writable) { - String xml = toXml(); - try { - //TODO: check in fileutils, to test the workspace's filesystem once at startup, and figure out how many of these can occur, instead of hard-coded '2' - dismissNextChangeNotif += 2; - FileWriter w = new FileWriter(tmxFile); - w.write(xml); - w.close(); - this.state = State.saved; - changedOnDisk = false; - Notification.addSuccess("TMX file "+tmxFile.getAbsolutePath()+" saved."); - } catch (IOException e) { - Notification.addError("Error while writing TMX file "+tmxFile.getAbsolutePath()+" : "+e.getMessage()); - e.printStackTrace(); - } - } - } - - @Override - public List attemptSave() { - //TODO check cases where map should be moved from altered/created to created/altered.... - save(); - return null; - } + @Override + public int getChildCount() { + return 0; + } - public void delete() { - if (writable) { - if (tmxFile.exists()) { - if (tmxFile.delete()) { - Notification.addSuccess("TMX file "+tmxFile.getAbsolutePath()+" deleted."); - } else { - Notification.addError("Error while deleting TMX file "+tmxFile.getAbsolutePath()); - } - } - ((TMXMapSet)parent).tmxMaps.remove(this); - //TODO clear blacklinks ? - } - } + @Override + public int getIndex(TreeNode arg0) { + return 0; + } - @Override - public void link() { - if (this.state == GameDataElement.State.init) { - parse(); - } - if (this.state == GameDataElement.State.parsed) { - if (groups != null) { - for (MapObjectGroup group : groups) { - group.link(); - } - } - } - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - for (MapObjectGroup group : groups) { - group.elementChanged(oldOne, newOne); - } - } + @Override + public boolean isLeaf() { + return true; + } - @Override - public String getProjectFilename() { - return tmxFile.getName(); - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } - public void addLayer(tiled.core.MapLayer layer) { - tmxMap.addLayer(layer); - if (layer instanceof tiled.core.ObjectGroup) { - groups.add(new MapObjectGroup((tiled.core.ObjectGroup) layer, this)); - } - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } - public void removeLayer(tiled.core.MapLayer layer) { - tmxMap.removeLayer(tmxMap.getLayerIndex(layer)); - if (layer instanceof tiled.core.ObjectGroup) { - MapObjectGroup toRemove = null; - for (MapObjectGroup group : groups) { - if (group.tmxGroup == layer) { - toRemove = group; - } - } - if (toRemove != null) { - groups.remove(toRemove); - } - } - } + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } - public MapObjectGroup getGroup(tiled.core.ObjectGroup selectedLayer) { - for (MapObjectGroup group : groups) { - if (group.tmxGroup == selectedLayer) { - return group; - } - } - return null; - } + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + id; + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + @Override + public Image getIcon() { + return DefaultIcons.getTiledIconIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getTiledIconIcon(); + } + + @Override + public Image getClosedIcon() { + return null; + } + + @Override + public Image getOpenIcon() { + return null; + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return parent.getDataType(); + } + + public String toXml() { + if (outside != null && outside == 1) { + tmxMap.getProperties().put("outdoors", Integer.toString(outside)); + } else { + tmxMap.getProperties().remove("outdoors"); + } + if (colorFilter != null) { + tmxMap.getProperties().put("colorfilter", colorFilter.toString()); + } else { + tmxMap.getProperties().remove("colorfilter"); + } + + for (MapObjectGroup group : groups) { + group.pushBackToTiledProperties(); + if (!tmxMap.containsLayer(group.tmxGroup)) { + tmxMap.addLayer(group.tmxGroup); + } + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + TMXMapWriter writer = new TMXMapWriter(); + writer.settings.layerCompressionMethod = TMXMapWriter.Settings.LAYER_COMPRESSION_METHOD_ZLIB; + if (getDataType() == GameSource.Type.source) { + writer.writeMap(tmxMap, baos, tmxFile.getAbsolutePath()); + } else { + writer.writeMap(tmxMap, baos, ((TMXMapSet) this.parent).mapFolder.getAbsolutePath() + File.separator + "placeholder.tmx"); + } + } catch (Exception e) { + Notification.addError("Error while converting map " + getDesc() + " to XML: " + e.getMessage()); + e.printStackTrace(); + } + return baos.toString(); + } + + @Override + public boolean isEmpty() { + return false; + } + + public void save() { + if (writable) { + String xml = toXml(); + try { + //TODO: check in fileutils, to test the workspace's filesystem once at startup, and figure out how many of these can occur, instead of hard-coded '2' + dismissNextChangeNotif += 2; + FileWriter w = new FileWriter(tmxFile); + w.write(xml); + w.close(); + this.state = State.saved; + changedOnDisk = false; + Notification.addSuccess("TMX file " + tmxFile.getAbsolutePath() + " saved."); + } catch (IOException e) { + Notification.addError("Error while writing TMX file " + tmxFile.getAbsolutePath() + " : " + e.getMessage()); + e.printStackTrace(); + } + } + } + + @Override + public List attemptSave() { + //TODO check cases where map should be moved from altered/created to created/altered.... + save(); + return null; + } + + public void delete() { + if (writable) { + if (tmxFile.exists()) { + if (tmxFile.delete()) { + Notification.addSuccess("TMX file " + tmxFile.getAbsolutePath() + " deleted."); + } else { + Notification.addError("Error while deleting TMX file " + tmxFile.getAbsolutePath()); + } + } + ((TMXMapSet) parent).tmxMaps.remove(this); + //TODO clear blacklinks ? + } + } + + @Override + public void link() { + if (this.state == GameDataElement.State.init) { + parse(); + } + if (this.state == GameDataElement.State.parsed) { + if (groups != null) { + for (MapObjectGroup group : groups) { + group.link(); + } + } + } + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + for (MapObjectGroup group : groups) { + group.elementChanged(oldOne, newOne); + } + } + + @Override + public String getProjectFilename() { + return tmxFile.getName(); + } + + public void addLayer(tiled.core.MapLayer layer) { + tmxMap.addLayer(layer); + if (layer instanceof tiled.core.ObjectGroup) { + groups.add(new MapObjectGroup((tiled.core.ObjectGroup) layer, this)); + } + } + + public void removeLayer(tiled.core.MapLayer layer) { + tmxMap.removeLayer(tmxMap.getLayerIndex(layer)); + if (layer instanceof tiled.core.ObjectGroup) { + MapObjectGroup toRemove = null; + for (MapObjectGroup group : groups) { + if (group.tmxGroup == layer) { + toRemove = group; + } + } + if (toRemove != null) { + groups.remove(toRemove); + } + } + } + + public MapObjectGroup getGroup(tiled.core.ObjectGroup selectedLayer) { + for (MapObjectGroup group : groups) { + if (group.tmxGroup == selectedLayer) { + return group; + } + } + return null; + } + + public List getMapchangesNames() { + List result = new ArrayList(); + result.add(null); + for (MapObjectGroup group : groups) { + for (MapObject obj : group.mapObjects) { + if (obj.type == MapObject.Types.mapchange) { + result.add(obj.name); + } + } + } + return result; + } + + public MapObject getMapObject(String name) { + MapObject result = null; + for (MapObjectGroup group : groups) { + for (MapObject obj : group.mapObjects) { + if (obj.name.equals(name)) { + result = obj; + break; + } + } + } + return result; + } + + public static boolean isPaintedLayerName(String name) { + return GROUND_LAYER_NAME.equalsIgnoreCase(name) || + OBJECTS_LAYER_NAME.equalsIgnoreCase(name) || + ABOVE_LAYER_NAME.equalsIgnoreCase(name) || + TOP_LAYER_NAME.equalsIgnoreCase(name) || + WALKABLE_LAYER_NAME.equalsIgnoreCase(name); + } + + + public void reload() { + tmxMap = null; + for (Spritesheet s : usedSpritesheets) { + s.elementChanged(this, null); + } + usedSpritesheets.clear(); + for (MapObjectGroup g : groups) { + for (MapObject o : g.mapObjects) { + if (o instanceof ContainerArea) { + if (((ContainerArea) o).droplist != null) ((ContainerArea) o).droplist.elementChanged(this, null); + } else if (o instanceof KeyArea) { + if (((KeyArea) o).dialogue != null) ((KeyArea) o).dialogue.elementChanged(this, null); + if (((KeyArea) o).requirement != null && ((KeyArea) o).requirement.required_obj != null) + ((KeyArea) o).requirement.required_obj.elementChanged(this, null); + } else if (o instanceof MapChange) { + if (((MapChange) o).map != null) ((MapChange) o).map.elementChanged(this, null); + } else if (o instanceof ReplaceArea) { + if (((ReplaceArea) o).requirement != null && ((ReplaceArea) o).requirement.required_obj != null) + ((ReplaceArea) o).requirement.required_obj.elementChanged(this, null); + } else if (o instanceof RestArea) { + } else if (o instanceof ScriptArea) { + if (((ScriptArea) o).dialogue != null) ((ScriptArea) o).dialogue.elementChanged(this, null); + } else if (o instanceof SignArea) { + if (((SignArea) o).dialogue != null) ((SignArea) o).dialogue.elementChanged(this, null); + } else if (o instanceof SpawnArea) { + if (((SpawnArea) o).spawnGroup != null) { + for (NPC n : ((SpawnArea) o).spawnGroup) { + n.elementChanged(this, null); + } + } + } + } + } + groups.clear(); + outside = null; + colorFilter = null; + + state = GameDataElement.State.init; + this.link(); + + changedOnDisk = false; + for (MapChangedOnDiskListener l : listeners) { + l.mapReloaded(); + } + } + + public void mapChangedOnDisk() { + if (dismissNextChangeNotif > 0) { + dismissNextChangeNotif--; + } else { + changedOnDisk = true; + for (MapChangedOnDiskListener l : listeners) { + l.mapChanged(); + } + } + } + + public interface MapChangedOnDiskListener { + public void mapChanged(); + + public void mapReloaded(); + } + + private List listeners = new CopyOnWriteArrayList(); + + public void addMapChangedOnDiskListener(MapChangedOnDiskListener l) { + listeners.add(l); + } + + public void removeMapChangedOnDiskListener(MapChangedOnDiskListener l) { + listeners.remove(l); + } - public List getMapchangesNames() { - List result = new ArrayList(); - result.add(null); - for (MapObjectGroup group : groups) { - for (MapObject obj : group.mapObjects) { - if (obj.type == MapObject.Types.mapchange) { - result.add(obj.name); - } - } - } - return result; - } - - public MapObject getMapObject(String name) { - MapObject result = null; - for (MapObjectGroup group : groups) { - for (MapObject obj : group.mapObjects) { - if (obj.name.equals(name)) { - result = obj; - break; - } - } - } - return result; - } - - public static boolean isPaintedLayerName(String name) { - return GROUND_LAYER_NAME.equalsIgnoreCase(name) || - OBJECTS_LAYER_NAME.equalsIgnoreCase(name) || - ABOVE_LAYER_NAME.equalsIgnoreCase(name) || - TOP_LAYER_NAME.equalsIgnoreCase(name) || - WALKABLE_LAYER_NAME.equalsIgnoreCase(name); - } - - public void reload() { - tmxMap = null; - for (Spritesheet s : usedSpritesheets) { - s.elementChanged(this, null); - } - usedSpritesheets.clear(); - for (MapObjectGroup g : groups) { - for (MapObject o : g.mapObjects) { - if (o instanceof ContainerArea) { - if (((ContainerArea)o).droplist != null) ((ContainerArea)o).droplist.elementChanged(this, null); - } else if (o instanceof KeyArea) { - if (((KeyArea)o).dialogue != null) ((KeyArea)o).dialogue.elementChanged(this, null); - if (((KeyArea)o).requirement != null && ((KeyArea)o).requirement.required_obj != null) ((KeyArea)o).requirement.required_obj.elementChanged(this, null); - } else if (o instanceof MapChange) { - if (((MapChange)o).map != null) ((MapChange)o).map.elementChanged(this, null); - } else if (o instanceof ReplaceArea) { - if (((ReplaceArea)o).requirement != null && ((ReplaceArea)o).requirement.required_obj != null) ((ReplaceArea)o).requirement.required_obj.elementChanged(this, null); - } else if (o instanceof RestArea) { - } else if (o instanceof ScriptArea) { - if (((ScriptArea)o).dialogue != null) ((ScriptArea)o).dialogue.elementChanged(this, null); - } else if (o instanceof SignArea) { - if (((SignArea)o).dialogue != null) ((SignArea)o).dialogue.elementChanged(this, null); - } else if (o instanceof SpawnArea) { - if (((SpawnArea)o).spawnGroup != null) { - for (NPC n : ((SpawnArea)o).spawnGroup) { - n.elementChanged(this, null); - } - } - } - } - } - groups.clear(); - outside = null; - colorFilter = null; - - state = GameDataElement.State.init; - this.link(); - - changedOnDisk = false; - for (MapChangedOnDiskListener l : listeners) { - l.mapReloaded(); - } - } - - public void mapChangedOnDisk() { - if (dismissNextChangeNotif > 0) { - dismissNextChangeNotif--; - } else { - changedOnDisk = true; - for (MapChangedOnDiskListener l : listeners) { - l.mapChanged(); - } - } - } - - public interface MapChangedOnDiskListener { - public void mapChanged(); - public void mapReloaded(); - } - - private List listeners = new CopyOnWriteArrayList(); - - public void addMapChangedOnDiskListener(MapChangedOnDiskListener l) { - listeners.add(l); - } - - public void removeMapChangedOnDiskListener(MapChangedOnDiskListener l) { - listeners.remove(l); - } - - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java index 23e244b..a71e298 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java @@ -1,24 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; -import java.io.File; -import java.io.IOException; -import java.nio.file.FileSystems; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardWatchEventKinds; -import java.nio.file.WatchEvent; -import java.nio.file.WatchKey; -import java.nio.file.WatchService; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; @@ -29,246 +10,273 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.utils.FileUtils; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.nio.file.*; +import java.util.List; +import java.util.*; +import java.util.concurrent.TimeUnit; + public class TMXMapSet implements ProjectTreeNode { - public static final String DEFAULT_REL_PATH_IN_SOURCE = "res"+File.separator+"xml"+File.separator; - public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps"+File.separator; - public static final String DEFAULT_REL_PATH_TO_DRAWABLE = ".."+File.separator+"drawable"+File.separator; + public static final String DEFAULT_REL_PATH_IN_SOURCE = "res" + File.separator + "xml" + File.separator; + public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps" + File.separator; + public static final String DEFAULT_REL_PATH_TO_DRAWABLE = ".." + File.separator + "drawable" + File.separator; - public static final String GAME_MAPS_ARRAY_NAME = "loadresource_maps"; - public static final String DEBUG_SUFFIX = "_debug"; - public static final String RESOURCE_PREFIX = "@xml/"; - public static final String FILENAME_SUFFIX = ".tmx"; - - public File mapFolder = null; - public List tmxMaps; - - public ProjectTreeNode parent; - - public TMXMapSet(GameSource source) { - this.parent = source; - if (source.type == GameSource.Type.source) { - this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); - } - else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { - this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); - if (!this.mapFolder.exists()) { - this.mapFolder.mkdirs(); - } - FileUtils.makeSymlink(getProject().baseContent.gameSprites.drawableFolder, new File(mapFolder.getAbsolutePath()+File.separator+DEFAULT_REL_PATH_TO_DRAWABLE)); - } - this.tmxMaps = new ArrayList(); - - if (source.type == GameSource.Type.source && (source.parent.sourceSetToUse == ResourceSet.debugData || source.parent.sourceSetToUse == ResourceSet.gameData)) { - String suffix = (source.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : ""; - - if (source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME+suffix) != null) { - for (String resource : source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME+suffix)) { - File f = new File(mapFolder, resource.replaceAll(RESOURCE_PREFIX, "")+FILENAME_SUFFIX); - if (f.exists()) { - TMXMap map = new TMXMap(this, f); - tmxMaps.add(map); - } else { - Notification.addWarn("Unable to locate resource "+resource+" in the game source for project "+getProject().name); - } - } - } - - } else if (this.mapFolder != null) { - for (File f : this.mapFolder.listFiles()) { - if (f.getName().endsWith(".tmx") || f.getName().endsWith(".TMX")) { - TMXMap map = new TMXMap(this, f); - if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { - map.writable = true; - } - tmxMaps.add(map); - } - } - } - Collections.sort(tmxMaps, new Comparator() { - @Override - public int compare(TMXMap o1, TMXMap o2) { - return o1.id.compareTo(o2.id); - } - }); - if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { - final Path folderPath = Paths.get(mapFolder.getAbsolutePath()); - Thread watcher = new Thread("Map folder watcher for "+getProject().name+"/"+source.type) { - public void run() { - WatchService watchService; + public static final String GAME_MAPS_ARRAY_NAME = "loadresource_maps"; + public static final String DEBUG_SUFFIX = "_debug"; + public static final String RESOURCE_PREFIX = "@xml/"; + public static final String FILENAME_SUFFIX = ".tmx"; - while(getProject().open) { - try { - watchService = FileSystems.getDefault().newWatchService(); - /*WatchKey watchKey = */folderPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE); - WatchKey wk; - validService: while(getProject().open) { - wk = watchService.poll(10, TimeUnit.SECONDS); - if (wk != null) { - for (WatchEvent event : wk.pollEvents()) { - Path changed = (Path) event.context(); - String name = changed.getFileName().toString(); - String id = name.substring(0, name.length() - 4); - TMXMap map = getMap(id); - if (map != null) { - map.mapChangedOnDisk(); - } - } - if(!wk.reset()) { - watchService.close(); - break validService; - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }; - }; - watcher.start(); - } - } - - @Override - public Enumeration children() { - return Collections.enumeration(tmxMaps); - } - @Override - public boolean getAllowsChildren() { - return true; - } - @Override - public TreeNode getChildAt(int arg0) { - return tmxMaps.get(arg0); - } - @Override - public int getChildCount() { - return tmxMaps.size(); - } - @Override - public int getIndex(TreeNode arg0) { - return tmxMaps.indexOf(arg0); - } - @Override - public TreeNode getParent() { - return parent; - } - @Override - public boolean isLeaf() { - return false; - } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.getChildCount() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (TMXMap map : tmxMaps) { - map.notifyCreated(); - } - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+"TMX Maps"; - } - - @Override - public Project getProject() { - return parent.getProject(); - } - + public File mapFolder = null; + public List tmxMaps; - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - return DefaultIcons.getTmxClosedIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getTmxClosedIcon(); - } - @Override - public Image getOpenIcon() { - return DefaultIcons.getTmxOpenIcon(); - } - - @Override - public GameDataSet getDataSet() { - return null; - } - - @Override - public Type getDataType() { - return parent.getDataType(); - } - - @Override - public boolean isEmpty() { - return tmxMaps.isEmpty(); - } + public ProjectTreeNode parent; - public TMXMap getMap(String id) { - if (tmxMaps == null) return null; - for (TMXMap map : tmxMaps) { - if (id.equals(map.id)){ - return map; - } - } - return null; - } + public TMXMapSet(GameSource source) { + this.parent = source; + if (source.type == GameSource.Type.source) { + this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); + } else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { + this.mapFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); + if (!this.mapFolder.exists()) { + this.mapFolder.mkdirs(); + } + FileUtils.makeSymlink(getProject().baseContent.gameSprites.drawableFolder, new File(mapFolder.getAbsolutePath() + File.separator + DEFAULT_REL_PATH_TO_DRAWABLE)); + } + this.tmxMaps = new ArrayList(); - public void addMap(TMXMap node) { - ProjectTreeNode higherEmptyParent = this; - while (higherEmptyParent != null) { - if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); - else break; - } - if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; - tmxMaps.add(node); - if (node.tmxFile != null) { - //Altered node. - node.tmxFile = new File(this.mapFolder, node.tmxFile.getName()); - } else { - //Created node. - node.tmxFile = new File(this.mapFolder, node.id+".tmx"); - } - node.parent = this; - if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); - else node.notifyCreated(); - } + if (source.type == GameSource.Type.source && (source.parent.sourceSetToUse == ResourceSet.debugData || source.parent.sourceSetToUse == ResourceSet.gameData)) { + String suffix = (source.parent.sourceSetToUse == ResourceSet.debugData) ? DEBUG_SUFFIX : ""; + + if (source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME + suffix) != null) { + for (String resource : source.referencedSourceFiles.get(GAME_MAPS_ARRAY_NAME + suffix)) { + File f = new File(mapFolder, resource.replaceAll(RESOURCE_PREFIX, "") + FILENAME_SUFFIX); + if (f.exists()) { + TMXMap map = new TMXMap(this, f); + tmxMaps.add(map); + } else { + Notification.addWarn("Unable to locate resource " + resource + " in the game source for project " + getProject().name); + } + } + } + + } else if (this.mapFolder != null) { + for (File f : this.mapFolder.listFiles()) { + if (f.getName().endsWith(".tmx") || f.getName().endsWith(".TMX")) { + TMXMap map = new TMXMap(this, f); + if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { + map.writable = true; + } + tmxMaps.add(map); + } + } + } + Collections.sort(tmxMaps, new Comparator() { + @Override + public int compare(TMXMap o1, TMXMap o2) { + return o1.id.compareTo(o2.id); + } + }); + if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { + final Path folderPath = Paths.get(mapFolder.getAbsolutePath()); + Thread watcher = new Thread("Map folder watcher for " + getProject().name + "/" + source.type) { + public void run() { + WatchService watchService; + + while (getProject().open) { + try { + watchService = FileSystems.getDefault().newWatchService(); + /*WatchKey watchKey = */ + folderPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE); + WatchKey wk; + validService: + while (getProject().open) { + wk = watchService.poll(10, TimeUnit.SECONDS); + if (wk != null) { + for (WatchEvent event : wk.pollEvents()) { + Path changed = (Path) event.context(); + String name = changed.getFileName().toString(); + String id = name.substring(0, name.length() - 4); + TMXMap map = getMap(id); + if (map != null) { + map.mapChangedOnDisk(); + } + } + if (!wk.reset()) { + watchService.close(); + break validService; + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + ; + }; + watcher.start(); + } + } + + @Override + public Enumeration children() { + return Collections.enumeration(tmxMaps); + } + + @Override + public boolean getAllowsChildren() { + return true; + } + + @Override + public TreeNode getChildAt(int arg0) { + return tmxMaps.get(arg0); + } + + @Override + public int getChildCount() { + return tmxMaps.size(); + } + + @Override + public int getIndex(TreeNode arg0) { + return tmxMaps.indexOf(arg0); + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.getChildCount() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (TMXMap map : tmxMaps) { + map.notifyCreated(); + } + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + "TMX Maps"; + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + return DefaultIcons.getTmxClosedIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getTmxClosedIcon(); + } + + @Override + public Image getOpenIcon() { + return DefaultIcons.getTmxOpenIcon(); + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return parent.getDataType(); + } + + @Override + public boolean isEmpty() { + return tmxMaps.isEmpty(); + } + + public TMXMap getMap(String id) { + if (tmxMaps == null) return null; + for (TMXMap map : tmxMaps) { + if (id.equals(map.id)) { + return map; + } + } + return null; + } + + public void addMap(TMXMap node) { + ProjectTreeNode higherEmptyParent = this; + while (higherEmptyParent != null) { + if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty()) + higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent(); + else break; + } + if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; + tmxMaps.add(node); + if (node.tmxFile != null) { + //Altered node. + node.tmxFile = new File(this.mapFolder, node.tmxFile.getName()); + } else { + //Created node. + node.tmxFile = new File(this.mapFolder, node.id + ".tmx"); + } + node.parent = this; + if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); + else node.notifyCreated(); + } + + public TMXMap get(int index) { + return tmxMaps.get(index); + } + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : tmxMaps) { + if (node.needsSaving()) return true; + } + return false; + } - public TMXMap get(int index) { - return tmxMaps.get(index); - } - - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : tmxMaps) { - if (node.needsSaving()) return true; - } - return false; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/Worldmap.java b/src/com/gpl/rpg/atcontentstudio/model/maps/Worldmap.java index c8b4489..2eec9fc 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/Worldmap.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/Worldmap.java @@ -1,40 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; -import java.awt.Point; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.tree.TreeNode; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; @@ -42,250 +7,272 @@ import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.swing.tree.TreeNode; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.awt.*; +import java.io.*; +import java.util.List; +import java.util.*; public class Worldmap extends ArrayList implements ProjectTreeNode { - private static final long serialVersionUID = 4590409256594556179L; + private static final long serialVersionUID = 4590409256594556179L; - public static final String DEFAULT_REL_PATH_IN_SOURCE = "res/xml/worldmap.xml"; - public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps"+File.separator+"worldmap.xml"; - - public File worldmapFile; - public GameSource parent; - - public Map> segments = new LinkedHashMap>(); + public static final String DEFAULT_REL_PATH_IN_SOURCE = "res/xml/worldmap.xml"; + public static final String DEFAULT_REL_PATH_IN_PROJECT = "maps" + File.separator + "worldmap.xml"; - public Worldmap(GameSource gameSource) { - this.parent = gameSource; - if (getDataType() == Type.source) { - worldmapFile = new File(parent.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); - } else { - worldmapFile = new File(parent.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); - } - if (worldmapFile.exists()) { - loadFromFile(worldmapFile); - } - if (getDataType() == Type.source) { - for (WorldmapSegment segment : this) { - segment.writable = false; - } - } else { - for (WorldmapSegment segment : this) { - segment.writable = true; - } - } - } + public File worldmapFile; + public GameSource parent; - private void loadFromFile(File file) { - if (!file.exists()) return; - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - Document doc; - try { - factory.setIgnoringComments(true); - factory.setIgnoringElementContentWhitespace(true); - factory.setExpandEntityReferences(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource insrc = new InputSource(new FileInputStream(file)); - insrc.setSystemId("http://worldmap/"); - insrc.setEncoding("UTF-8"); - doc = builder.parse(insrc); - - Element root = (Element) doc.getElementsByTagName("worldmap").item(0); - if (root != null) { - NodeList segmentsList = root.getElementsByTagName("segment"); - if (segmentsList != null) { - for (int i = 0; i < segmentsList.getLength(); i++) { - Element segmentNode = (Element) segmentsList.item(i); - String name = segmentNode.getAttribute("id"); - add(new WorldmapSegment(this, name, segmentNode)); - } - } - } - } catch (SAXException e) { - e.printStackTrace(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public Map> segments = new LinkedHashMap>(); - @Override - public Enumeration children() { - return Collections.enumeration(this); - } + public Worldmap(GameSource gameSource) { + this.parent = gameSource; + if (getDataType() == Type.source) { + worldmapFile = new File(parent.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); + } else { + worldmapFile = new File(parent.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); + } + if (worldmapFile.exists()) { + loadFromFile(worldmapFile); + } + if (getDataType() == Type.source) { + for (WorldmapSegment segment : this) { + segment.writable = false; + } + } else { + for (WorldmapSegment segment : this) { + segment.writable = true; + } + } + } - @Override - public boolean getAllowsChildren() { - return true; - } + private void loadFromFile(File file) { + if (!file.exists()) return; + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + Document doc; + try { + factory.setIgnoringComments(true); + factory.setIgnoringElementContentWhitespace(true); + factory.setExpandEntityReferences(false); + DocumentBuilder builder = factory.newDocumentBuilder(); + InputSource insrc = new InputSource(new FileInputStream(file)); + insrc.setSystemId("http://worldmap/"); + insrc.setEncoding("UTF-8"); + doc = builder.parse(insrc); - @Override - public TreeNode getChildAt(int arg0) { - return get(arg0); - } + Element root = (Element) doc.getElementsByTagName("worldmap").item(0); + if (root != null) { + NodeList segmentsList = root.getElementsByTagName("segment"); + if (segmentsList != null) { + for (int i = 0; i < segmentsList.getLength(); i++) { + Element segmentNode = (Element) segmentsList.item(i); + String name = segmentNode.getAttribute("id"); + add(new WorldmapSegment(this, name, segmentNode)); + } + } + } + } catch (SAXException e) { + e.printStackTrace(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - @Override - public int getChildCount() { - return size(); - } + @Override + public Enumeration children() { + return Collections.enumeration(this); + } - @Override - public int getIndex(TreeNode arg0) { - return indexOf(arg0); - } + @Override + public boolean getAllowsChildren() { + return true; + } - @Override - public TreeNode getParent() { - return parent; - } + @Override + public TreeNode getChildAt(int arg0) { + return get(arg0); + } - @Override - public boolean isLeaf() { - return false; - } + @Override + public int getChildCount() { + return size(); + } - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } + @Override + public int getIndex(TreeNode arg0) { + return indexOf(arg0); + } - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.getChildCount() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } + @Override + public boolean isLeaf() { + return false; + } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+"Worldmap"; - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } - - @Override - public Project getProject() { - return parent.getProject(); - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } - @Override - public Image getIcon() { - return DefaultIcons.getMapClosedIcon(); - } - @Override - public Image getLeafIcon() { - return null; - } - @Override - public Image getClosedIcon() { - return DefaultIcons.getMapClosedIcon(); - } - @Override - public Image getOpenIcon() { - return DefaultIcons.getMapOpenIcon(); - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } - @Override - public GameDataSet getDataSet() { - return null; - } + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.getChildCount() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } - @Override - public Type getDataType() { - return parent.getDataType(); - } + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + "Worldmap"; + } - public void save() { - - try { - Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - doc.setXmlVersion("1.0"); - Element root = doc.createElement("worldmap"); - doc.appendChild(root); + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } - for (WorldmapSegment segment : this) { - root.appendChild(segment.toXmlElement(doc)); - segment.state = GameDataElement.State.saved; - } + @Override + public Project getProject() { + return parent.getProject(); + } - saveDocToFile(doc, worldmapFile); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @Override + public Image getIcon() { + return DefaultIcons.getMapClosedIcon(); + } - public WorldmapSegment getWorldmapSegment(String id) { - for (WorldmapSegment s : this) { - if (s.id.equals(id)) { - return s; - } - } - return null; - } + @Override + public Image getLeafIcon() { + return null; + } - public void addSegment(WorldmapSegment node) { - ProjectTreeNode higherEmptyParent = this; - while (higherEmptyParent != null) { - if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); - else break; - } - if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; - add(node); - node.parent = this; - if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); - else node.notifyCreated(); - } + @Override + public Image getClosedIcon() { + return DefaultIcons.getMapClosedIcon(); + } - - public static void saveDocToFile(Document doc, File f) { - try { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - Result output = new StreamResult(new FileOutputStream(f)); - Source input = new DOMSource(doc); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); - transformer.transform(input, output); - } catch (TransformerConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TransformerFactoryConfigurationError e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (TransformerException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @Override + public Image getOpenIcon() { + return DefaultIcons.getMapOpenIcon(); + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return parent.getDataType(); + } + + public void save() { + + try { + Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + doc.setXmlVersion("1.0"); + Element root = doc.createElement("worldmap"); + doc.appendChild(root); + + for (WorldmapSegment segment : this) { + root.appendChild(segment.toXmlElement(doc)); + segment.state = GameDataElement.State.saved; + } + + saveDocToFile(doc, worldmapFile); + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public WorldmapSegment getWorldmapSegment(String id) { + for (WorldmapSegment s : this) { + if (s.id.equals(id)) { + return s; + } + } + return null; + } + + public void addSegment(WorldmapSegment node) { + ProjectTreeNode higherEmptyParent = this; + while (higherEmptyParent != null) { + if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty()) + higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent(); + else break; + } + if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; + add(node); + node.parent = this; + if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); + else node.notifyCreated(); + } + + + public static void saveDocToFile(Document doc, File f) { + try { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + Result output = new StreamResult(new FileOutputStream(f)); + Source input = new DOMSource(doc); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); + transformer.transform(input, output); + } catch (TransformerConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (TransformerFactoryConfigurationError e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (TransformerException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : this) { + if (node.needsSaving()) return true; + } + return false; + } - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : this) { - if (node.needsSaving()) return true; - } - return false; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/WorldmapSegment.java b/src/com/gpl/rpg/atcontentstudio/model/maps/WorldmapSegment.java index d8daeae..dee6741 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/WorldmapSegment.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/WorldmapSegment.java @@ -1,240 +1,233 @@ package com.gpl.rpg.atcontentstudio.model.maps; -import java.awt.Image; -import java.awt.Point; -import java.io.ByteArrayOutputStream; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Result; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NodeList; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.*; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.awt.*; +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; public class WorldmapSegment extends GameDataElement { - private static final long serialVersionUID = 2658610076889592723L; - - public static final String TEMP_LABEL_KEY = "ATCS_INTERNAL_TEMPORARY_KEY_FOR_LABEL"; - - public int segmentX; - public int segmentY; - public Map mapLocations = new LinkedHashMap(); - public Map> labelledMaps = new LinkedHashMap>(); - public Map labels = new LinkedHashMap(); - public Element xmlNode; - - public WorldmapSegment(Worldmap parent, String name, Element xmlNode) { - this.parent = parent; - this.id = name; - this.xmlNode = xmlNode; - } - - @Override - public GameDataSet getDataSet() { - return parent.getDataSet(); - } + private static final long serialVersionUID = 2658610076889592723L; - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+id; - } + public static final String TEMP_LABEL_KEY = "ATCS_INTERNAL_TEMPORARY_KEY_FOR_LABEL"; - @Override - public void parse() { - segmentX = Integer.parseInt(xmlNode.getAttribute("x")); - segmentY = Integer.parseInt(xmlNode.getAttribute("y")); - NodeList mapsList = xmlNode.getElementsByTagName("map"); - for (int j = 0; j < mapsList.getLength(); j++) { - Element mapNode = (Element) mapsList.item(j); - mapLocations.put(mapNode.getAttribute("id"), new Point(Integer.parseInt(mapNode.getAttribute("x")) - segmentX, Integer.parseInt(mapNode.getAttribute("y")) - segmentY)); - String area; - if ((area = mapNode.getAttribute("area")) != null && !"".equals(area)) { - if (labelledMaps.get(area) == null) { - labelledMaps.put(area, new ArrayList()); - } - labelledMaps.get(area).add(mapNode.getAttribute("id")); - } - } - NodeList namedAreasNodeList = xmlNode.getElementsByTagName("namedarea"); - for (int j = 0; j < namedAreasNodeList.getLength(); j++) { - Element namedAreaNode = (Element) namedAreasNodeList.item(j); - labels.put(namedAreaNode.getAttribute("id"), new NamedArea(namedAreaNode.getAttribute("id"), namedAreaNode.getAttribute("name"), namedAreaNode.getAttribute("type"))); - } - this.state = State.parsed; - } + public int segmentX; + public int segmentY; + public Map mapLocations = new LinkedHashMap(); + public Map> labelledMaps = new LinkedHashMap>(); + public Map labels = new LinkedHashMap(); + public Element xmlNode; - @Override - public void link() { - if (this.state == State.init) { - this.parse(); - } else if (this.state == State.linked) { - return; - } - for (String mapName : mapLocations.keySet()) { - if (getProject().getMap(mapName) != null) { - getProject().getMap(mapName).addBacklink(this); - } - } - } + public WorldmapSegment(Worldmap parent, String name, Element xmlNode) { + this.parent = parent; + this.id = name; + this.xmlNode = xmlNode; + } - @Override - public WorldmapSegment clone() { - WorldmapSegment clone = new WorldmapSegment((Worldmap)parent, id, (Element) xmlNode.cloneNode(true)); - - return clone; - } + @Override + public GameDataSet getDataSet() { + return parent.getDataSet(); + } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - boolean modified = false; - if (newOne == null && writable) { - //A referenced map may have been deleted. - if (mapLocations.containsKey(oldOne.id)) { - mapLocations.remove(oldOne.id); - modified = true; - } - List deprecatedLabels = new ArrayList(); - for (String label : labelledMaps.keySet()) { - if (labelledMaps.get(label).contains(oldOne.id)) { - labelledMaps.get(label).remove(oldOne.id); - modified = true; - if (labelledMaps.get(label).isEmpty()) { - deprecatedLabels.add(label); - } - } - } - for (String label : deprecatedLabels) { - labelledMaps.remove(label); - labels.remove(label); - } - } - - oldOne.removeBacklink(this); - if(newOne != null) newOne.addBacklink(this); - - if (modified) { - this.state = GameDataElement.State.modified; - childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(this); - } - } + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + id; + } - @Override - public String getProjectFilename() { - return "worldmap.xml"; - } + @Override + public void parse() { + segmentX = Integer.parseInt(xmlNode.getAttribute("x")); + segmentY = Integer.parseInt(xmlNode.getAttribute("y")); + NodeList mapsList = xmlNode.getElementsByTagName("map"); + for (int j = 0; j < mapsList.getLength(); j++) { + Element mapNode = (Element) mapsList.item(j); + mapLocations.put(mapNode.getAttribute("id"), new Point(Integer.parseInt(mapNode.getAttribute("x")) - segmentX, Integer.parseInt(mapNode.getAttribute("y")) - segmentY)); + String area; + if ((area = mapNode.getAttribute("area")) != null && !"".equals(area)) { + if (labelledMaps.get(area) == null) { + labelledMaps.put(area, new ArrayList()); + } + labelledMaps.get(area).add(mapNode.getAttribute("id")); + } + } + NodeList namedAreasNodeList = xmlNode.getElementsByTagName("namedarea"); + for (int j = 0; j < namedAreasNodeList.getLength(); j++) { + Element namedAreaNode = (Element) namedAreasNodeList.item(j); + labels.put(namedAreaNode.getAttribute("id"), new NamedArea(namedAreaNode.getAttribute("id"), namedAreaNode.getAttribute("name"), namedAreaNode.getAttribute("type"))); + } + this.state = State.parsed; + } - @Override - public void save() { - ((Worldmap)parent).save(); - } - - public String toXml() { - Document doc; - try { - doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - doc.setXmlVersion("1.0"); - Element root = doc.createElement("worldmap"); - doc.appendChild(root); - root.appendChild(this.toXmlElement(doc)); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Result output = new StreamResult(baos); - Source input = new DOMSource(doc); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); - transformer.transform(input, output); - return baos.toString(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } catch (TransformerException e) { - e.printStackTrace(); - } - return null; - - } - - public Element toXmlElement(Document doc) { - Element element = doc.createElement("segment"); - element.setAttribute("id", id); - element.setAttribute("x", Integer.toString(segmentX)); - element.setAttribute("y", Integer.toString(segmentY)); - - for (String s : mapLocations.keySet()) { - Element map = doc.createElement("map"); - map.setAttribute("id", s); - map.setAttribute("x", Integer.toString(mapLocations.get(s).x + segmentX)); - map.setAttribute("y", Integer.toString(mapLocations.get(s).y + segmentY)); - for (String label : labelledMaps.keySet()) { - if (TEMP_LABEL_KEY.equals(label)) continue; - if (labelledMaps.get(label).contains(s)) { - map.setAttribute("area", label); - } - } - element.appendChild(map); - } - - for (String key : labels.keySet()) { - if (TEMP_LABEL_KEY.equals(key)) continue; - NamedArea area = labels.get(key); - Element namedArea = doc.createElement("namedarea"); - namedArea.setAttribute("id", area.id); - namedArea.setAttribute("name", area.name); - namedArea.setAttribute("type", area.type); - element.appendChild(namedArea); - } - - return element; - } - + @Override + public void link() { + if (this.state == State.init) { + this.parse(); + } else if (this.state == State.linked) { + return; + } + for (String mapName : mapLocations.keySet()) { + if (getProject().getMap(mapName) != null) { + getProject().getMap(mapName).addBacklink(this); + } + } + } - @Override - public List attemptSave() { - // TODO Auto-generated method stub - save(); - return null; - } + @Override + public WorldmapSegment clone() { + WorldmapSegment clone = new WorldmapSegment((Worldmap) parent, id, (Element) xmlNode.cloneNode(true)); + + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + boolean modified = false; + if (newOne == null && writable) { + //A referenced map may have been deleted. + if (mapLocations.containsKey(oldOne.id)) { + mapLocations.remove(oldOne.id); + modified = true; + } + List deprecatedLabels = new ArrayList(); + for (String label : labelledMaps.keySet()) { + if (labelledMaps.get(label).contains(oldOne.id)) { + labelledMaps.get(label).remove(oldOne.id); + modified = true; + if (labelledMaps.get(label).isEmpty()) { + deprecatedLabels.add(label); + } + } + } + for (String label : deprecatedLabels) { + labelledMaps.remove(label); + labels.remove(label); + } + } + + oldOne.removeBacklink(this); + if (newOne != null) newOne.addBacklink(this); + + if (modified) { + this.state = GameDataElement.State.modified; + childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(this); + } + } + + @Override + public String getProjectFilename() { + return "worldmap.xml"; + } + + @Override + public void save() { + ((Worldmap) parent).save(); + } + + public String toXml() { + Document doc; + try { + doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + doc.setXmlVersion("1.0"); + Element root = doc.createElement("worldmap"); + doc.appendChild(root); + root.appendChild(this.toXmlElement(doc)); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + Result output = new StreamResult(baos); + Source input = new DOMSource(doc); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); + transformer.transform(input, output); + return baos.toString(); + } catch (ParserConfigurationException e) { + e.printStackTrace(); + } catch (TransformerException e) { + e.printStackTrace(); + } + return null; + + } + + public Element toXmlElement(Document doc) { + Element element = doc.createElement("segment"); + element.setAttribute("id", id); + element.setAttribute("x", Integer.toString(segmentX)); + element.setAttribute("y", Integer.toString(segmentY)); + + for (String s : mapLocations.keySet()) { + Element map = doc.createElement("map"); + map.setAttribute("id", s); + map.setAttribute("x", Integer.toString(mapLocations.get(s).x + segmentX)); + map.setAttribute("y", Integer.toString(mapLocations.get(s).y + segmentY)); + for (String label : labelledMaps.keySet()) { + if (TEMP_LABEL_KEY.equals(label)) continue; + if (labelledMaps.get(label).contains(s)) { + map.setAttribute("area", label); + } + } + element.appendChild(map); + } + + for (String key : labels.keySet()) { + if (TEMP_LABEL_KEY.equals(key)) continue; + NamedArea area = labels.get(key); + Element namedArea = doc.createElement("namedarea"); + namedArea.setAttribute("id", area.id); + namedArea.setAttribute("name", area.name); + namedArea.setAttribute("type", area.type); + element.appendChild(namedArea); + } + + return element; + } + + + @Override + public List attemptSave() { + // TODO Auto-generated method stub + save(); + return null; + } + + public static class NamedArea { + public String id; + public String name; + public String type; + + public NamedArea(String id, String name, String type) { + this.id = id; + this.name = name; + this.type = type; + } + } + + @Override + public Image getIcon() { + return DefaultIcons.getUIMapIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getUIMapIcon(); + } - public static class NamedArea { - public String id; - public String name; - public String type; - - public NamedArea(String id, String name, String type) { - this.id = id; - this.name = name; - this.type = type; - } - } - - @Override - public Image getIcon() { - return DefaultIcons.getUIMapIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getUIMapIcon(); - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGame.java b/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGame.java index 4cc3ef5..271314f 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGame.java +++ b/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGame.java @@ -1,14 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.saves; -import java.awt.Image; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.andorstrainer.io.SavedGameIO; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; @@ -18,160 +9,177 @@ import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + public class SavedGame extends GameDataElement { - - private static final long serialVersionUID = -6443495534761084990L; - - public File savedFile; - transient public com.gpl.rpg.andorstrainer.model.SavedGame loadedSave = null; - transient public SavedGamesSet parent; - - public SavedGame(SavedGamesSet parent, File f) throws IOException { - savedFile = f; - refreshTransients(parent); - } - - public void refreshTransients(SavedGamesSet parent) throws IOException { - this.parent = parent; - this.loadedSave = SavedGameIO.loadFile(savedFile); - if (this.loadedSave == null) { - throw new IOException("Unable to load save: "+savedFile.getAbsolutePath()); - } - } - - @Override - public Enumeration children() { - return null; - } - @Override - public boolean getAllowsChildren() { - return false; - } + private static final long serialVersionUID = -6443495534761084990L; - @Override - public TreeNode getChildAt(int arg0) { - return null; - } + public File savedFile; + transient public com.gpl.rpg.andorstrainer.model.SavedGame loadedSave = null; + transient public SavedGamesSet parent; - @Override - public int getChildCount() { - return 0; - } + public SavedGame(SavedGamesSet parent, File f) throws IOException { + savedFile = f; + refreshTransients(parent); + } - @Override - public int getIndex(TreeNode arg0) { - return 0; - } + public void refreshTransients(SavedGamesSet parent) throws IOException { + this.parent = parent; + this.loadedSave = SavedGameIO.loadFile(savedFile); + if (this.loadedSave == null) { + throw new IOException("Unable to load save: " + savedFile.getAbsolutePath()); + } + } - @Override - public TreeNode getParent() { - return parent; - } + @Override + public Enumeration children() { + return null; + } - @Override - public boolean isLeaf() { - return true; - } + @Override + public boolean getAllowsChildren() { + return false; + } - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } + @Override + public TreeNode getChildAt(int arg0) { + return null; + } - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } + @Override + public int getChildCount() { + return 0; + } - @Override - public void childrenRemoved(List path) { - path.add(0,this); - parent.childrenRemoved(path); - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+loadedSave.displayInfo; - } + @Override + public int getIndex(TreeNode arg0) { + return 0; + } - @Override - public Project getProject() { - return parent.getProject(); - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public Image getIcon() { - return DefaultIcons.getHeroIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getHeroIcon(); - } - @Override - public Image getClosedIcon() {return null;} - @Override - public Image getOpenIcon() {return null;} - - @Override - public GameDataSet getDataSet() { - return null; - } + @Override + public boolean isLeaf() { + return true; + } - @Override - public Type getDataType() { - return null; - } - - @Override - public boolean isEmpty() { - return false; - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } - @Override - public void parse() { - // TODO Auto-generated method stub - - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } - @Override - public void link() { - // TODO Auto-generated method stub - - } + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } - @Override - public GameDataElement clone() { - // TODO Auto-generated method stub - return null; - } + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - // TODO Auto-generated method stub - - } + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + loadedSave.displayInfo; + } - @Override - public String getProjectFilename() { - // TODO Auto-generated method stub - return null; - } + @Override + public Project getProject() { + return parent.getProject(); + } - @Override - public void save() { - // TODO Auto-generated method stub - - } - - @Override - public List attemptSave() { - // TODO Auto-generated method stub - return null; - } + @Override + public Image getIcon() { + return DefaultIcons.getHeroIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getHeroIcon(); + } + + @Override + public Image getClosedIcon() { + return null; + } + + @Override + public Image getOpenIcon() { + return null; + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return null; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public void parse() { + // TODO Auto-generated method stub + + } + + @Override + public void link() { + // TODO Auto-generated method stub + + } + + @Override + public GameDataElement clone() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + // TODO Auto-generated method stub + + } + + @Override + public String getProjectFilename() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void save() { + // TODO Auto-generated method stub + + } + + @Override + public List attemptSave() { + // TODO Auto-generated method stub + return null; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGamesSet.java b/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGamesSet.java index 7e241a2..2964304 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGamesSet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/saves/SavedGamesSet.java @@ -1,16 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.saves; -import java.awt.Image; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.Vector; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.Project; @@ -18,163 +7,182 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Vector; + public class SavedGamesSet implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = -6565834239789184087L; + private static final long serialVersionUID = -6565834239789184087L; - public Vector saves; //For simulations. + public Vector saves; //For simulations. - public Project parent; - - public SavedGamesSet(Project parent) { - this.parent = parent; - saves = new Vector(); - } - - public void refreshTransients() { - for (SavedGame save : saves) { - try { - save.refreshTransients(this); - } catch (IOException e) { - Notification.addError(e.getMessage()); - } - } - } - - public void addSave(File f) { - try { - ProjectTreeNode higherEmptyParent = this; - while (higherEmptyParent != null) { - if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); - else break; - } - if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; - SavedGame node = new SavedGame(this, f); - saves.add(node); - if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); - else node.notifyCreated(); - } catch (IOException e) { - Notification.addError(e.getMessage()); - } - } - - public SavedGame getSave(File f) { - for (SavedGame save : saves) { - if (save.savedFile.equals(f)) return save; - } - return null; - } - - @Override - public Enumeration children() { - return saves.elements(); - } + public Project parent; - @Override - public boolean getAllowsChildren() { - return true; - } + public SavedGamesSet(Project parent) { + this.parent = parent; + saves = new Vector(); + } - @Override - public TreeNode getChildAt(int arg0) { - return saves.elementAt(arg0); - } + public void refreshTransients() { + for (SavedGame save : saves) { + try { + save.refreshTransients(this); + } catch (IOException e) { + Notification.addError(e.getMessage()); + } + } + } - @Override - public int getChildCount() { - return saves.size(); - } + public void addSave(File f) { + try { + ProjectTreeNode higherEmptyParent = this; + while (higherEmptyParent != null) { + if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty()) + higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent(); + else break; + } + if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; + SavedGame node = new SavedGame(this, f); + saves.add(node); + if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); + else node.notifyCreated(); + } catch (IOException e) { + Notification.addError(e.getMessage()); + } + } - @Override - public int getIndex(TreeNode arg0) { - return saves.indexOf(arg0); - } + public SavedGame getSave(File f) { + for (SavedGame save : saves) { + if (save.savedFile.equals(f)) return save; + } + return null; + } - @Override - public TreeNode getParent() { - return parent; - } + @Override + public Enumeration children() { + return saves.elements(); + } - @Override - public boolean isLeaf() { - return false; - } + @Override + public boolean getAllowsChildren() { + return true; + } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.getChildCount() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (SavedGame s : saves) { - s.notifyCreated(); - } - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+"Saved games"; - } + @Override + public TreeNode getChildAt(int arg0) { + return saves.elementAt(arg0); + } - @Override - public Project getProject() { - return parent.getProject(); - } - + @Override + public int getChildCount() { + return saves.size(); + } - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - return DefaultIcons.getSavClosedIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getSavClosedIcon(); - } - @Override - public Image getOpenIcon() { - return DefaultIcons.getSavOpenIcon(); - } - + @Override + public int getIndex(TreeNode arg0) { + return saves.indexOf(arg0); + } - @Override - public GameDataSet getDataSet() { - return null; - } - @Override - public Type getDataType() { - return null; - } - - @Override - public boolean isEmpty() { - return saves.isEmpty(); - } - + @Override + public TreeNode getParent() { + return parent; + } - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : saves) { - if (node.needsSaving()) return true; - } - return false; - } + @Override + public boolean isLeaf() { + return false; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.getChildCount() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (SavedGame s : saves) { + s.notifyCreated(); + } + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + "Saved games"; + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + return DefaultIcons.getSavClosedIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getSavClosedIcon(); + } + + @Override + public Image getOpenIcon() { + return DefaultIcons.getSavOpenIcon(); + } + + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return null; + } + + @Override + public boolean isEmpty() { + return saves.isEmpty(); + } + + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : saves) { + if (node.needsSaving()) return true; + } + return false; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/sprites/SpriteSheetSet.java b/src/com/gpl/rpg/atcontentstudio/model/sprites/SpriteSheetSet.java index a361e49..1ed4f78 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/sprites/SpriteSheetSet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/sprites/SpriteSheetSet.java @@ -1,14 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.sprites; -import java.awt.Image; -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; - -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.GameSource.Type; import com.gpl.rpg.atcontentstudio.model.Project; @@ -16,147 +7,170 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + public class SpriteSheetSet implements ProjectTreeNode { - public static final String DEFAULT_REL_PATH_IN_SOURCE = "res"+File.separator+"drawable"+File.separator; - public static final String DEFAULT_REL_PATH_IN_PROJECT = "spritesheets"+File.separator; - - public File drawableFolder = null; - - public transient List spritesheets; + public static final String DEFAULT_REL_PATH_IN_SOURCE = "res" + File.separator + "drawable" + File.separator; + public static final String DEFAULT_REL_PATH_IN_PROJECT = "spritesheets" + File.separator; - public GameSource parent; - - public SpriteSheetSet(GameSource source) { - this.parent = source; - if (source.type == GameSource.Type.source) this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); - else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { - this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); - if (!this.drawableFolder.exists()) { - this.drawableFolder.mkdirs(); - } - } - spritesheets = new ArrayList(); - if (this.drawableFolder != null) { - for (File f : this.drawableFolder.listFiles()) { - if (f.getName().endsWith(".png") || f.getName().endsWith(".PNG")) { - spritesheets.add(new Spritesheet(this, f)); - } - } - } - } - - @Override - public Enumeration children() { - return Collections.enumeration(spritesheets); - } - @Override - public boolean getAllowsChildren() { - return true; - } - @Override - public TreeNode getChildAt(int arg0) { - return spritesheets.get(arg0); - } - @Override - public int getChildCount() { - return spritesheets.size(); - } - @Override - public int getIndex(TreeNode arg0) { - return spritesheets.indexOf(arg0); - } - @Override - public TreeNode getParent() { - return parent; - } - @Override - public boolean isLeaf() { - return false; - } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - if (path.size() == 1 && this.getChildCount() == 1) { - childrenRemoved(new ArrayList()); - } else { - path.add(0, this); - parent.childrenRemoved(path); - } - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - for (Spritesheet s : spritesheets) { - s.notifyCreated(); - } - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+"Spritesheets"; - } + public File drawableFolder = null; - @Override - public Project getProject() { - return parent.getProject(); - } - - @Override - public Image getIcon() { - return getOpenIcon(); - } - @Override - public Image getClosedIcon() { - return DefaultIcons.getSpriteClosedIcon(); - } - @Override - public Image getLeafIcon() { - return DefaultIcons.getSpriteClosedIcon(); - } - @Override - public Image getOpenIcon() { - return DefaultIcons.getSpriteOpenIcon(); - } + public transient List spritesheets; - @Override - public GameDataSet getDataSet() { - return null; - } - - @Override - public Type getDataType() { - return parent.getDataType(); - } - - @Override - public boolean isEmpty() { - return spritesheets.isEmpty(); - } + public GameSource parent; - public Spritesheet getSpritesheet(String id) { - if (spritesheets == null) return null; - for (Spritesheet sheet : spritesheets) { - if (id.equals(sheet.id)){ - return sheet; - } - } - return null; - } - - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : spritesheets) { - if (node.needsSaving()) return true; - } - return false; - } + public SpriteSheetSet(GameSource source) { + this.parent = source; + if (source.type == GameSource.Type.source) + this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_SOURCE); + else if (source.type == GameSource.Type.created | source.type == GameSource.Type.altered) { + this.drawableFolder = new File(source.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); + if (!this.drawableFolder.exists()) { + this.drawableFolder.mkdirs(); + } + } + spritesheets = new ArrayList(); + if (this.drawableFolder != null) { + for (File f : this.drawableFolder.listFiles()) { + if (f.getName().endsWith(".png") || f.getName().endsWith(".PNG")) { + spritesheets.add(new Spritesheet(this, f)); + } + } + } + } + + @Override + public Enumeration children() { + return Collections.enumeration(spritesheets); + } + + @Override + public boolean getAllowsChildren() { + return true; + } + + @Override + public TreeNode getChildAt(int arg0) { + return spritesheets.get(arg0); + } + + @Override + public int getChildCount() { + return spritesheets.size(); + } + + @Override + public int getIndex(TreeNode arg0) { + return spritesheets.indexOf(arg0); + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + if (path.size() == 1 && this.getChildCount() == 1) { + childrenRemoved(new ArrayList()); + } else { + path.add(0, this); + parent.childrenRemoved(path); + } + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + for (Spritesheet s : spritesheets) { + s.notifyCreated(); + } + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + "Spritesheets"; + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + @Override + public Image getIcon() { + return getOpenIcon(); + } + + @Override + public Image getClosedIcon() { + return DefaultIcons.getSpriteClosedIcon(); + } + + @Override + public Image getLeafIcon() { + return DefaultIcons.getSpriteClosedIcon(); + } + + @Override + public Image getOpenIcon() { + return DefaultIcons.getSpriteOpenIcon(); + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return parent.getDataType(); + } + + @Override + public boolean isEmpty() { + return spritesheets.isEmpty(); + } + + public Spritesheet getSpritesheet(String id) { + if (spritesheets == null) return null; + for (Spritesheet sheet : spritesheets) { + if (id.equals(sheet.id)) { + return sheet; + } + } + return null; + } + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : spritesheets) { + if (node.needsSaving()) return true; + } + return false; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java b/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java index 4ddb231..dc1e72e 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java @@ -1,19 +1,5 @@ package com.gpl.rpg.atcontentstudio.model.sprites; -import java.awt.Graphics; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.imageio.ImageIO; -import javax.swing.tree.TreeNode; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; @@ -23,250 +9,283 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; +import javax.imageio.ImageIO; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.*; + public class Spritesheet extends GameDataElement { - - private static final long serialVersionUID = -5981708088278528586L; - - public SpriteSheetSet parent; - public File spritesheetFile; - public int spriteWidth = 32; - public int spriteHeight = 32; - public String id; - public Category category = Category.none; - public boolean animated = false; - public enum Category { - none, - monster, - item, - actorcondition - }; - - //Lazy initialization. - public BufferedImage spritesheet = null; - public Map cache_full_size = new LinkedHashMap(); - public Map cache_icon = new LinkedHashMap(); - - public Spritesheet(SpriteSheetSet parent, File f) { - this.spritesheetFile = f; - this.id = f.getName().substring(0, f.getName().lastIndexOf(".")); - this.parent = parent; - - String cat = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".category"); - if (cat != null) { - this.category = Category.valueOf(cat); - } - String sizex = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".sizex"); - if (sizex != null) { - this.spriteWidth = Integer.parseInt(sizex); - } - String sizey = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".sizey"); - if (sizey != null) { - this.spriteHeight = Integer.parseInt(sizey); - } - String anim = getProject().getSpritesheetsProperty("atcs.spritesheet."+this.id+".animate"); - if (anim != null) { - this.animated = Boolean.parseBoolean(anim); - } - } - - @Override - public Enumeration children() { - return null; - } - @Override - public boolean getAllowsChildren() { - return false; - } - @Override - public TreeNode getChildAt(int arg0) { - return null; - } - @Override - public int getChildCount() { - return 0; - } - @Override - public int getIndex(TreeNode arg0) { - return 0; - } - @Override - public TreeNode getParent() { - return parent; - } - @Override - public boolean isLeaf() { - return true; - } - @Override - public void childrenAdded(List path) { - path.add(0, this); - parent.childrenAdded(path); - } - @Override - public void childrenChanged(List path) { - path.add(0, this); - parent.childrenChanged(path); - } - @Override - public void childrenRemoved(List path) { - path.add(0, this); - parent.childrenRemoved(path); - } - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+spritesheetFile.getName(); - } + private static final long serialVersionUID = -5981708088278528586L; - @Override - public Project getProject() { - return parent.getProject(); - } - - public int getSpriteCount() { - if (spritesheet == null) { - try { - spritesheet = ImageIO.read(spritesheetFile); - } catch (IOException e) { - Notification.addError("Error loading image "+spritesheetFile.getAbsolutePath()+" : "+e.getMessage()); - e.printStackTrace(); - return 0; - } - } - return (int) (Math.ceil(((double)spritesheet.getWidth()) / ((double)spriteWidth)) * Math.ceil(((double)spritesheet.getHeight()) / ((double)spriteHeight))); - } - - public BufferedImage getImage(int index) { - if (spritesheet == null) { - try { - spritesheet = ImageIO.read(spritesheetFile); - } catch (IOException e) { - Notification.addError("Error loading image "+spritesheetFile.getAbsolutePath()+" : "+e.getMessage()); - e.printStackTrace(); - return null; - } - } - if (cache_full_size.get(index) != null) { - return cache_full_size.get(index); - } - BufferedImage result = new BufferedImage(spriteWidth, spriteHeight, BufferedImage.TYPE_INT_ARGB); - Graphics g = result.getGraphics(); - int sx1, sy1; - sx1 = (index * spriteWidth) % spritesheet.getWidth(); - sy1 = spriteHeight * ((index * spriteWidth) / spritesheet.getWidth()); - if (sx1 + spriteWidth > spritesheet.getWidth() || sy1 + spriteHeight > spritesheet.getHeight()) { - g.finalize(); - return null; - } - g.drawImage(spritesheet, 0, 0, spriteWidth, spriteHeight, sx1, sy1, sx1 + spriteWidth, sy1 + spriteHeight, null); - result.flush(); - g.finalize(); - cache_full_size.put(index, result); - return result; - } - - public Image getIcon(int index) { - if (cache_icon.get(index) != null) { - return cache_icon.get(index); - } - Image result = getImage(index); - if (result == null) return null; - result = result.getScaledInstance((int)(16*ATContentStudio.SCALING), (int)(16*ATContentStudio.SCALING), Image.SCALE_SMOOTH); - cache_icon.put(index, result); - return result; - } - - public void clearCache() { - cache_full_size.clear(); - cache_icon.clear(); - } - + public SpriteSheetSet parent; + public File spritesheetFile; + public int spriteWidth = 32; + public int spriteHeight = 32; + public String id; + public Category category = Category.none; + public boolean animated = false; - @Override - public Image getIcon() { - return getIcon(0); - } - @Override - public Image getLeafIcon() { - return getIcon(); - } - @Override - public Image getClosedIcon() {return null;} - @Override - public Image getOpenIcon() {return null;} + public enum Category { + none, + monster, + item, + actorcondition + } + + ; + + //Lazy initialization. + public BufferedImage spritesheet = null; + public Map cache_full_size = new LinkedHashMap(); + public Map cache_icon = new LinkedHashMap(); + + public Spritesheet(SpriteSheetSet parent, File f) { + this.spritesheetFile = f; + this.id = f.getName().substring(0, f.getName().lastIndexOf(".")); + this.parent = parent; + + String cat = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".category"); + if (cat != null) { + this.category = Category.valueOf(cat); + } + String sizex = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizex"); + if (sizex != null) { + this.spriteWidth = Integer.parseInt(sizex); + } + String sizey = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizey"); + if (sizey != null) { + this.spriteHeight = Integer.parseInt(sizey); + } + String anim = getProject().getSpritesheetsProperty("atcs.spritesheet." + this.id + ".animate"); + if (anim != null) { + this.animated = Boolean.parseBoolean(anim); + } + } + + @Override + public Enumeration children() { + return null; + } + + @Override + public boolean getAllowsChildren() { + return false; + } + + @Override + public TreeNode getChildAt(int arg0) { + return null; + } + + @Override + public int getChildCount() { + return 0; + } + + @Override + public int getIndex(TreeNode arg0) { + return 0; + } + + @Override + public TreeNode getParent() { + return parent; + } + + @Override + public boolean isLeaf() { + return true; + } + + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } + + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } + + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } + + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + spritesheetFile.getName(); + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + public int getSpriteCount() { + if (spritesheet == null) { + try { + spritesheet = ImageIO.read(spritesheetFile); + } catch (IOException e) { + Notification.addError("Error loading image " + spritesheetFile.getAbsolutePath() + " : " + e.getMessage()); + e.printStackTrace(); + return 0; + } + } + return (int) (Math.ceil(((double) spritesheet.getWidth()) / ((double) spriteWidth)) * Math.ceil(((double) spritesheet.getHeight()) / ((double) spriteHeight))); + } + + public BufferedImage getImage(int index) { + if (spritesheet == null) { + try { + spritesheet = ImageIO.read(spritesheetFile); + } catch (IOException e) { + Notification.addError("Error loading image " + spritesheetFile.getAbsolutePath() + " : " + e.getMessage()); + e.printStackTrace(); + return null; + } + } + if (cache_full_size.get(index) != null) { + return cache_full_size.get(index); + } + BufferedImage result = new BufferedImage(spriteWidth, spriteHeight, BufferedImage.TYPE_INT_ARGB); + Graphics g = result.getGraphics(); + int sx1, sy1; + sx1 = (index * spriteWidth) % spritesheet.getWidth(); + sy1 = spriteHeight * ((index * spriteWidth) / spritesheet.getWidth()); + if (sx1 + spriteWidth > spritesheet.getWidth() || sy1 + spriteHeight > spritesheet.getHeight()) { + g.finalize(); + return null; + } + g.drawImage(spritesheet, 0, 0, spriteWidth, spriteHeight, sx1, sy1, sx1 + spriteWidth, sy1 + spriteHeight, null); + result.flush(); + g.finalize(); + cache_full_size.put(index, result); + return result; + } + + public Image getIcon(int index) { + if (cache_icon.get(index) != null) { + return cache_icon.get(index); + } + Image result = getImage(index); + if (result == null) return null; + result = result.getScaledInstance((int) (16 * ATContentStudio.SCALING), (int) (16 * ATContentStudio.SCALING), Image.SCALE_SMOOTH); + cache_icon.put(index, result); + return result; + } + + public void clearCache() { + cache_full_size.clear(); + cache_icon.clear(); + } - @Override - public GameDataSet getDataSet() { - return null; - } - - @Override - public Type getDataType() { - return parent.getDataType(); - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public void parse() { - if(this.state == GameDataElement.State.init){ - this.state = GameDataElement.State.parsed; - } - } + @Override + public Image getIcon() { + return getIcon(0); + } - @Override - public void link() { - if (this.state == GameDataElement.State.init) { - this.parse(); - } - if(this.state == GameDataElement.State.parsed) { - this.state = GameDataElement.State.linked; - } - } + @Override + public Image getLeafIcon() { + return getIcon(); + } - @Override - public GameDataElement clone() { - Spritesheet clone = new Spritesheet((SpriteSheetSet) getParent(), new File(spritesheetFile.getAbsolutePath())); - clone.id = this.id; - clone.animated = this.animated; - clone.category = this.category; - clone.spriteWidth = this.spriteWidth; - clone.spriteHeight = this.spriteHeight; - return clone; - } + @Override + public Image getClosedIcon() { + return null; + } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - //nothing linked. - } + @Override + public Image getOpenIcon() { + return null; + } - @Override - public String getProjectFilename() { - return spritesheetFile.getName(); - } - @Override - public void save() { - if (this.category != null) getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".category", this.category.toString()); - if (this.spriteWidth != 32) getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".sizex", Integer.toString(this.spriteWidth)); - if (this.spriteHeight != 32) getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".sizey", Integer.toString(this.spriteHeight)); - if (this.animated)getProject().setSpritesheetsProperty("atcs.spritesheet."+this.id+".animate", Boolean.toString(this.animated)); - getProject().save(); - - this.state = GameDataElement.State.saved; - } - - @Override - public List attemptSave() { - save(); - return null; - } + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public Type getDataType() { + return parent.getDataType(); + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public void parse() { + if (this.state == GameDataElement.State.init) { + this.state = GameDataElement.State.parsed; + } + } + + @Override + public void link() { + if (this.state == GameDataElement.State.init) { + this.parse(); + } + if (this.state == GameDataElement.State.parsed) { + this.state = GameDataElement.State.linked; + } + } + + @Override + public GameDataElement clone() { + Spritesheet clone = new Spritesheet((SpriteSheetSet) getParent(), new File(spritesheetFile.getAbsolutePath())); + clone.id = this.id; + clone.animated = this.animated; + clone.category = this.category; + clone.spriteWidth = this.spriteWidth; + clone.spriteHeight = this.spriteHeight; + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + //nothing linked. + } + + @Override + public String getProjectFilename() { + return spritesheetFile.getName(); + } + + @Override + public void save() { + if (this.category != null) + getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".category", this.category.toString()); + if (this.spriteWidth != 32) + getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizex", Integer.toString(this.spriteWidth)); + if (this.spriteHeight != 32) + getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".sizey", Integer.toString(this.spriteHeight)); + if (this.animated) + getProject().setSpritesheetsProperty("atcs.spritesheet." + this.id + ".animate", Boolean.toString(this.animated)); + getProject().save(); + + this.state = GameDataElement.State.saved; + } + + @Override + public List attemptSave() { + save(); + return null; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PoPotWriter.java b/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PoPotWriter.java index faee965..a4c533c 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PoPotWriter.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PoPotWriter.java @@ -1,11 +1,6 @@ package com.gpl.rpg.atcontentstudio.model.tools.i18n; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; +import java.io.*; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.LinkedList; @@ -14,76 +9,76 @@ import java.util.Map; public class PoPotWriter { - Map> stringsResources = new LinkedHashMap>(); - Map translations = new LinkedHashMap(); - File f; - - public static void writePoFile(Map> stringsResources, Map translations, File destination) { - try { - Writer fw = new OutputStreamWriter(new FileOutputStream(destination), StandardCharsets.UTF_8); - if (translations.get("") != null) { - fw.write(translations.get("")); - writeEndOfEntry(fw); - } - if (translations.get("translator-credits") != null) { - List refs = new LinkedList(); - refs.add("[none]"); - writeReferences(fw, refs); - writeMsgId(fw, "translator-credits"); - writeMsgStr(fw, translations.get("translator-credits")); - writeEndOfEntry(fw); - } - for (String msg : stringsResources.keySet()) { - writeReferences(fw, stringsResources.get(msg)); - writeMsgId(fw, msg); - writeMsgStr(fw, translations.get(msg)); - writeEndOfEntry(fw); - } - fw.flush(); - fw.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static void writePotFile(Map> stringsResources, File destination) { - try { - FileWriter fw = new FileWriter(destination); - for (String msg : stringsResources.keySet()) { - writeReferences(fw, stringsResources.get(msg)); - writeMsgId(fw, msg); - writeMsgStr(fw, ""); - writeEndOfEntry(fw); - } - fw.flush(); - fw.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static void writeReferences(Writer w, List references) throws IOException { - for (String ref : references) { - w.write("#: "); - w.write(ref); - w.write("\n"); - } - } - - private static void writeMsgId(Writer w, String msg) throws IOException { - w.write("msgid \""); - w.write(msg); - w.write("\"\n"); - } - - private static void writeMsgStr(Writer w, String translation) throws IOException { - w.write("msgstr \""); - w.write(translation == null ? "" : translation); - w.write("\"\n"); - } - - private static void writeEndOfEntry(Writer w) throws IOException { - w.write("\n"); - } - + Map> stringsResources = new LinkedHashMap>(); + Map translations = new LinkedHashMap(); + File f; + + public static void writePoFile(Map> stringsResources, Map translations, File destination) { + try { + Writer fw = new OutputStreamWriter(new FileOutputStream(destination), StandardCharsets.UTF_8); + if (translations.get("") != null) { + fw.write(translations.get("")); + writeEndOfEntry(fw); + } + if (translations.get("translator-credits") != null) { + List refs = new LinkedList(); + refs.add("[none]"); + writeReferences(fw, refs); + writeMsgId(fw, "translator-credits"); + writeMsgStr(fw, translations.get("translator-credits")); + writeEndOfEntry(fw); + } + for (String msg : stringsResources.keySet()) { + writeReferences(fw, stringsResources.get(msg)); + writeMsgId(fw, msg); + writeMsgStr(fw, translations.get(msg)); + writeEndOfEntry(fw); + } + fw.flush(); + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void writePotFile(Map> stringsResources, File destination) { + try { + FileWriter fw = new FileWriter(destination); + for (String msg : stringsResources.keySet()) { + writeReferences(fw, stringsResources.get(msg)); + writeMsgId(fw, msg); + writeMsgStr(fw, ""); + writeEndOfEntry(fw); + } + fw.flush(); + fw.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private static void writeReferences(Writer w, List references) throws IOException { + for (String ref : references) { + w.write("#: "); + w.write(ref); + w.write("\n"); + } + } + + private static void writeMsgId(Writer w, String msg) throws IOException { + w.write("msgid \""); + w.write(msg); + w.write("\"\n"); + } + + private static void writeMsgStr(Writer w, String translation) throws IOException { + w.write("msgstr \""); + w.write(translation == null ? "" : translation); + w.write("\"\n"); + } + + private static void writeEndOfEntry(Writer w) throws IOException { + w.write("\n"); + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotComparator.java b/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotComparator.java index 916b3aa..2943a78 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotComparator.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotComparator.java @@ -1,310 +1,304 @@ package com.gpl.rpg.atcontentstudio.model.tools.i18n; -import java.io.File; -import java.io.FileFilter; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import javax.swing.JOptionPane; - import com.gpl.rpg.atcontentstudio.model.Project; - import net.launchpad.tobal.poparser.POEntry; import net.launchpad.tobal.poparser.POFile; import net.launchpad.tobal.poparser.POParser; +import javax.swing.*; +import java.io.File; +import java.io.FileFilter; +import java.util.*; + /** - * * @author Kevin - * + *

* To use this, paste the following script in the beanshell console of ATCS. * Don't forget to change the project number to suit your needs. - * -import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotGenerator; -import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotComparator; - -proj = Workspace.activeWorkspace.projects.get(7); -PotGenerator.generatePotFileForProject(proj); -comp = new PotComparator(proj); -comp.compare(); -comp.updatePoFiles(proj); - * - * + *

+ * * + * import com.gpl.rpg.atcontentstudio.model.Workspace; + * import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotGenerator; + * import com.gpl.rpg.atcontentstudio.model.tools.i18n.PotComparator; + * + * proj = Workspace.activeWorkspace.projects.get(7); + * PotGenerator.generatePotFileForProject(proj); + * comp = new PotComparator(proj); + * comp.compare(); + * comp.updatePoFiles(proj); + * */ public class PotComparator { - Map> stringsResourcesNew = new LinkedHashMap>(); - Map resourcesStringsNew = new LinkedHashMap(); - - Map> stringsResourcesOld = new LinkedHashMap>(); - Map resourcesStringsOld = new LinkedHashMap(); + Map> stringsResourcesNew = new LinkedHashMap>(); + Map resourcesStringsNew = new LinkedHashMap(); - Map msgIdToReplace = new LinkedHashMap(); - List msgIdToReview = new LinkedList(); - List msgIdOutdated = new LinkedList(); - - - public PotComparator(Project proj) { - POParser parser = new POParser(); + Map> stringsResourcesOld = new LinkedHashMap>(); + Map resourcesStringsOld = new LinkedHashMap(); - POFile newPot = parser.parseFile(new File(proj.alteredContent.baseFolder.getAbsolutePath()+File.separator+"english.pot")); - if (newPot == null) { - System.err.println("Cannot locate new english.pot file at "+proj.alteredContent.baseFolder.getAbsolutePath()+File.separator); - } - extractFromPoFile(newPot, stringsResourcesNew, resourcesStringsNew); - - POFile oldPot = parser.parseFile(new File(proj.baseContent.baseFolder.getAbsolutePath()+File.separator+"assets"+File.separator+"translation"+File.separator+"english.pot")); - if (oldPot == null) { - System.err.println("Cannot locate old english.pot file at "+proj.baseContent.baseFolder.getAbsolutePath()+File.separator+"assets"+File.separator+"translations"+File.separator); - } - extractFromPoFile(oldPot, stringsResourcesOld, resourcesStringsOld); - } - - - private void extractFromPoFile(POFile po, Map> stringsResources, Map resourcesStrings) { - for (POEntry entry : po.getEntryArray()) { - Vector resources = entry.getStringsByType(POEntry.StringType.REFERENCE); - Vector msgids = entry.getStringsByType(POEntry.StringType.MSGID); - if (resources == null || resources.size() == 0 || msgids == null || msgids.size() == 0) continue; - String msgid = msgids.get(0); - if (msgids.size() > 1) { - for (int i = 1; i < msgids.size(); i++) { - msgid += msgids.get(i); - } - } - if (msgid.contains("\\n")) { - msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\""); - msgid = "\"\n\""+msgid; - } - for (String resLine : resources) { - String[] resArray = resLine.split(" "); - for (String res : resArray) { - resourcesStrings.put(res, msgid); - if (stringsResources.get(msgid) == null) { - stringsResources.put(msgid, new LinkedList()); - } - stringsResources.get(msgid).add(res); - } - } - } - } - - public void compare() { - for (String oldRes : resourcesStringsOld.keySet()) { - String newString = resourcesStringsNew.get(oldRes); - String oldString = resourcesStringsOld.get(oldRes); - if (newString != null) { - if (!newString.equals(oldString)) { - List allOldResources = stringsResourcesOld.get(oldString); - List allNewResources = stringsResourcesNew.get(oldString); - StringBuffer sb = new StringBuffer(); - sb.append("---------------------------------------------\n"); - sb.append("--- TYPO CHECK ------------------------------\n"); - sb.append("---------------------------------------------\n"); - sb.append("String at: "+oldRes+"\n"); - if (allOldResources.size() > 1) { - sb.append("Also present at:\n"); - for (String res : allOldResources) { - if (!res.equals(oldRes)) { - sb.append("- "+res+"\n"); - } - } - } - if (allNewResources != null) { - sb.append("Still present at: \n"); - for (String res : allNewResources) { - sb.append("- "+res+"\n"); - } - } - sb.append("Was : \""+oldString+"\"\n"); - sb.append("Now : \""+newString+"\"\n"); - System.out.println(sb.toString()); - showTypoDialog(oldString, newString, sb.toString()); - } - } else { - List allOldResources = stringsResourcesOld.get(oldString); - List allNewResources = stringsResourcesNew.get(oldString); - if (allOldResources.size() >= 1) { - System.out.println("---------------------------------------------"); - System.out.println("--- REMOVED RESOURCE ------------------------"); - System.out.println("---------------------------------------------"); - System.out.println("String at: "+oldRes); - if (allOldResources.size() > 1) { - System.out.println("And also at:"); - for (String res : allOldResources) { - if (!res.equals(oldRes)) { - System.out.println("- "+res); - } - } - } - System.out.println("Was: \""+oldString+"\""); - if (allNewResources == null) { - System.out.println("Absent from new."); - } else { - System.out.println("Still present at: "); - for (String res : allNewResources) { - System.out.println("- "+res); - } + Map msgIdToReplace = new LinkedHashMap(); + List msgIdToReview = new LinkedList(); + List msgIdOutdated = new LinkedList(); - } - } - } - } - removedStrings: for (String oldString : stringsResourcesOld.keySet()) { - if (stringsResourcesNew.get(oldString) == null) { - List allOldResources = stringsResourcesOld.get(oldString); - if (allOldResources.size() >= 1) { - if (allOldResources.size() > 0) { - for (String res : allOldResources) { - String newString = resourcesStringsNew.get(res); - if (newString != null) { - continue removedStrings; - } - } - } - System.out.println("---------------------------------------------"); - System.out.println("--- REMOVED STRING --------------------------"); - System.out.println("---------------------------------------------"); - System.out.println("String: \""+oldString+"\""); - if (allOldResources.size() > 0) { - System.out.println("Was at:"); - for (String res : allOldResources) { - System.out.println("- "+res); - } - } - System.out.println("This string is absent from the new file, and its attached resources are missing too."); - } - } - } - } - - private void showTypoDialog(String oldMsg, String newMsg, String checkReport) { - String typo = "Typo"; - String review = "Review"; - String outdated = "Outdated"; - String none = "None"; - Object[] options = new Object[] {typo, review, outdated, none}; - - int result = JOptionPane.showOptionDialog(null, checkReport, "Choose action", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, typo); - - if (result < 0 || result >= options.length) { - System.out.println("No decision"); - return; - } - System.out.println("Decision: "+options[result]); - - if (options[result] != none) { - msgIdToReplace.put(oldMsg, newMsg); - if (options[result] == review) { - msgIdToReview.add(newMsg); - } else if (options[result] == outdated) { - msgIdOutdated.add(newMsg); - } - } - - } - - - public void updatePoFiles(Project proj) { - File poFolder = new File(proj.baseContent.baseFolder.getAbsolutePath()+File.separator+"assets"+File.separator+"translation"); - File[] poFiles = poFolder.listFiles(new FileFilter() { - @Override - public boolean accept(File arg0) { - return arg0.isFile() && arg0.getName().endsWith(".po"); - } - }); - - for (File f : poFiles) { - updatePoFile(proj, f); - } - } - - private void updatePoFile(Project proj, File f) { - POParser parser = new POParser(); - POFile poFile = parser.parseFile(f); - - Map translations = new LinkedHashMap(); - - //Collect existing translations - if (poFile.getHeader() != null) { - Vector msgstrs = poFile.getHeader().getStringsByType(POEntry.StringType.HEADER); - String header = ""; - if (!msgstrs.isEmpty()) { - if (msgstrs.size() == 1) { - header = msgstrs.get(0); - } else { - for (String msgstr : msgstrs) { - header += msgstr; - header += "\n"; - } - } - } - translations.put("", header); - } - - for (POEntry entry : poFile.getEntryArray()) { - Vector msgids = entry.getStringsByType(POEntry.StringType.MSGID); - Vector msgstrs = entry.getStringsByType(POEntry.StringType.MSGSTR); - if (msgids == null || msgids.size() == 0) continue; - String msgid = msgids.get(0); - if (msgids.size() > 1) { - for (int i = 1; i < msgids.size(); i++) { - msgid += msgids.get(i); - } - } - if (msgid.contains("\\n")) { - msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\""); - msgid = "\"\n\""+msgid; - } - String translation = ""; - if (!msgstrs.isEmpty()) { - if (msgstrs.size() == 1) { - translation = msgstrs.get(0); - } else { - for (String msgstr : msgstrs) { - translation += msgstr; - } - } - if (translation.contains("\\n")) { - translation = translation.replaceAll("\\\\n", "\\\\n\"\n\""); - translation = "\"\n\""+translation; - } - } - translations.put(msgid, translation); - } - - //Patch data - for (String oldId : msgIdToReplace.keySet()) { - String newId = msgIdToReplace.get(oldId); - if (translations.containsKey(oldId)) { - String trans = translations.get(oldId); - translations.remove(oldId); - translations.put(newId, trans); - } - } - - for (String msgid : msgIdToReview) { - if (translations.containsKey(msgid)) { - String trans = translations.get(msgid); - if (trans != null && trans.length() >= 1) translations.put(msgid, "[REVIEW]"+trans); - } - } + public PotComparator(Project proj) { + POParser parser = new POParser(); + + POFile newPot = parser.parseFile(new File(proj.alteredContent.baseFolder.getAbsolutePath() + File.separator + "english.pot")); + if (newPot == null) { + System.err.println("Cannot locate new english.pot file at " + proj.alteredContent.baseFolder.getAbsolutePath() + File.separator); + } + extractFromPoFile(newPot, stringsResourcesNew, resourcesStringsNew); + + POFile oldPot = parser.parseFile(new File(proj.baseContent.baseFolder.getAbsolutePath() + File.separator + "assets" + File.separator + "translation" + File.separator + "english.pot")); + if (oldPot == null) { + System.err.println("Cannot locate old english.pot file at " + proj.baseContent.baseFolder.getAbsolutePath() + File.separator + "assets" + File.separator + "translations" + File.separator); + } + extractFromPoFile(oldPot, stringsResourcesOld, resourcesStringsOld); + } + + + private void extractFromPoFile(POFile po, Map> stringsResources, Map resourcesStrings) { + for (POEntry entry : po.getEntryArray()) { + Vector resources = entry.getStringsByType(POEntry.StringType.REFERENCE); + Vector msgids = entry.getStringsByType(POEntry.StringType.MSGID); + if (resources == null || resources.size() == 0 || msgids == null || msgids.size() == 0) continue; + String msgid = msgids.get(0); + if (msgids.size() > 1) { + for (int i = 1; i < msgids.size(); i++) { + msgid += msgids.get(i); + } + } + if (msgid.contains("\\n")) { + msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\""); + msgid = "\"\n\"" + msgid; + } + for (String resLine : resources) { + String[] resArray = resLine.split(" "); + for (String res : resArray) { + resourcesStrings.put(res, msgid); + if (stringsResources.get(msgid) == null) { + stringsResources.put(msgid, new LinkedList()); + } + stringsResources.get(msgid).add(res); + } + } + } + } + + public void compare() { + for (String oldRes : resourcesStringsOld.keySet()) { + String newString = resourcesStringsNew.get(oldRes); + String oldString = resourcesStringsOld.get(oldRes); + if (newString != null) { + if (!newString.equals(oldString)) { + List allOldResources = stringsResourcesOld.get(oldString); + List allNewResources = stringsResourcesNew.get(oldString); + StringBuffer sb = new StringBuffer(); + sb.append("---------------------------------------------\n"); + sb.append("--- TYPO CHECK ------------------------------\n"); + sb.append("---------------------------------------------\n"); + sb.append("String at: " + oldRes + "\n"); + if (allOldResources.size() > 1) { + sb.append("Also present at:\n"); + for (String res : allOldResources) { + if (!res.equals(oldRes)) { + sb.append("- " + res + "\n"); + } + } + } + if (allNewResources != null) { + sb.append("Still present at: \n"); + for (String res : allNewResources) { + sb.append("- " + res + "\n"); + } + } + sb.append("Was : \"" + oldString + "\"\n"); + sb.append("Now : \"" + newString + "\"\n"); + System.out.println(sb.toString()); + showTypoDialog(oldString, newString, sb.toString()); + } + } else { + List allOldResources = stringsResourcesOld.get(oldString); + List allNewResources = stringsResourcesNew.get(oldString); + if (allOldResources.size() >= 1) { + System.out.println("---------------------------------------------"); + System.out.println("--- REMOVED RESOURCE ------------------------"); + System.out.println("---------------------------------------------"); + System.out.println("String at: " + oldRes); + if (allOldResources.size() > 1) { + System.out.println("And also at:"); + for (String res : allOldResources) { + if (!res.equals(oldRes)) { + System.out.println("- " + res); + } + } + } + System.out.println("Was: \"" + oldString + "\""); + if (allNewResources == null) { + System.out.println("Absent from new."); + } else { + System.out.println("Still present at: "); + for (String res : allNewResources) { + System.out.println("- " + res); + } + + } + } + } + } + removedStrings: + for (String oldString : stringsResourcesOld.keySet()) { + if (stringsResourcesNew.get(oldString) == null) { + List allOldResources = stringsResourcesOld.get(oldString); + if (allOldResources.size() >= 1) { + if (allOldResources.size() > 0) { + for (String res : allOldResources) { + String newString = resourcesStringsNew.get(res); + if (newString != null) { + continue removedStrings; + } + } + } + System.out.println("---------------------------------------------"); + System.out.println("--- REMOVED STRING --------------------------"); + System.out.println("---------------------------------------------"); + System.out.println("String: \"" + oldString + "\""); + if (allOldResources.size() > 0) { + System.out.println("Was at:"); + for (String res : allOldResources) { + System.out.println("- " + res); + } + } + System.out.println("This string is absent from the new file, and its attached resources are missing too."); + } + } + } + } + + private void showTypoDialog(String oldMsg, String newMsg, String checkReport) { + String typo = "Typo"; + String review = "Review"; + String outdated = "Outdated"; + String none = "None"; + Object[] options = new Object[]{typo, review, outdated, none}; + + int result = JOptionPane.showOptionDialog(null, checkReport, "Choose action", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, typo); + + if (result < 0 || result >= options.length) { + System.out.println("No decision"); + return; + } + + System.out.println("Decision: " + options[result]); + + if (options[result] != none) { + msgIdToReplace.put(oldMsg, newMsg); + if (options[result] == review) { + msgIdToReview.add(newMsg); + } else if (options[result] == outdated) { + msgIdOutdated.add(newMsg); + } + } + + } + + + public void updatePoFiles(Project proj) { + File poFolder = new File(proj.baseContent.baseFolder.getAbsolutePath() + File.separator + "assets" + File.separator + "translation"); + File[] poFiles = poFolder.listFiles(new FileFilter() { + @Override + public boolean accept(File arg0) { + return arg0.isFile() && arg0.getName().endsWith(".po"); + } + }); + + for (File f : poFiles) { + updatePoFile(proj, f); + } + } + + private void updatePoFile(Project proj, File f) { + POParser parser = new POParser(); + POFile poFile = parser.parseFile(f); + + Map translations = new LinkedHashMap(); + + //Collect existing translations + if (poFile.getHeader() != null) { + Vector msgstrs = poFile.getHeader().getStringsByType(POEntry.StringType.HEADER); + String header = ""; + if (!msgstrs.isEmpty()) { + if (msgstrs.size() == 1) { + header = msgstrs.get(0); + } else { + for (String msgstr : msgstrs) { + header += msgstr; + header += "\n"; + } + } + } + translations.put("", header); + } + + for (POEntry entry : poFile.getEntryArray()) { + Vector msgids = entry.getStringsByType(POEntry.StringType.MSGID); + Vector msgstrs = entry.getStringsByType(POEntry.StringType.MSGSTR); + if (msgids == null || msgids.size() == 0) continue; + String msgid = msgids.get(0); + if (msgids.size() > 1) { + for (int i = 1; i < msgids.size(); i++) { + msgid += msgids.get(i); + } + } + if (msgid.contains("\\n")) { + msgid = msgid.replaceAll("\\\\n", "\\\\n\"\n\""); + msgid = "\"\n\"" + msgid; + } + String translation = ""; + if (!msgstrs.isEmpty()) { + if (msgstrs.size() == 1) { + translation = msgstrs.get(0); + } else { + for (String msgstr : msgstrs) { + translation += msgstr; + } + } + if (translation.contains("\\n")) { + translation = translation.replaceAll("\\\\n", "\\\\n\"\n\""); + translation = "\"\n\"" + translation; + } + } + translations.put(msgid, translation); + } + + //Patch data + for (String oldId : msgIdToReplace.keySet()) { + String newId = msgIdToReplace.get(oldId); + if (translations.containsKey(oldId)) { + String trans = translations.get(oldId); + translations.remove(oldId); + translations.put(newId, trans); + } + } + + for (String msgid : msgIdToReview) { + if (translations.containsKey(msgid)) { + String trans = translations.get(msgid); + if (trans != null && trans.length() >= 1) translations.put(msgid, "[REVIEW]" + trans); + } + } + + for (String msgid : msgIdOutdated) { + if (translations.containsKey(msgid)) { + String trans = translations.get(msgid); + if (trans != null && trans.length() >= 1) translations.put(msgid, "[OUTDATED]" + trans); + } + } + + PoPotWriter.writePoFile(stringsResourcesNew, translations, new File(proj.alteredContent.baseFolder.getAbsolutePath() + File.separator + f.getName())); + } - for (String msgid : msgIdOutdated) { - if (translations.containsKey(msgid)) { - String trans = translations.get(msgid); - if (trans != null && trans.length() >= 1) translations.put(msgid, "[OUTDATED]"+trans); - } - } - - PoPotWriter.writePoFile(stringsResourcesNew, translations, new File(proj.alteredContent.baseFolder.getAbsolutePath()+File.separator+f.getName())); - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotGenerator.java b/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotGenerator.java index 7e7932f..c90d8d2 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotGenerator.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/i18n/PotGenerator.java @@ -1,101 +1,94 @@ package com.gpl.rpg.atcontentstudio.model.tools.i18n; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; + import java.io.File; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; -import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; - public class PotGenerator { - public static void generatePotFileForProject(Project proj) { - Map> stringsResources = new LinkedHashMap>(); - Map resourcesStrings = new LinkedHashMap(); - - GameSource gsrc = proj.baseContent; - - for (ActorCondition ac : gsrc.gameData.actorConditions) { - pushString(stringsResources, resourcesStrings, ac.display_name, getPotContextComment(ac)); - pushString(stringsResources, resourcesStrings, ac.description, getPotContextComment(ac)+":description"); - } - - for (Dialogue d : gsrc.gameData.dialogues ) { - pushString(stringsResources, resourcesStrings, d.message, getPotContextComment(d)); - if (d.replies == null) continue; - for (Dialogue.Reply r : d.replies) { - if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT) ) { - pushString(stringsResources, resourcesStrings, r.text, getPotContextComment(d)+":"+d.replies.indexOf(r)); - } - } - } - - for (ItemCategory ic : gsrc.gameData.itemCategories) { - pushString(stringsResources, resourcesStrings, ic.name, getPotContextComment(ic)); - } - - for (Item i : gsrc.gameData.items) { - pushString(stringsResources, resourcesStrings, i.name, getPotContextComment(i)); - pushString(stringsResources, resourcesStrings, i.description, getPotContextComment(i)+":description"); - } - - for (NPC npc : gsrc.gameData.npcs ) { - pushString(stringsResources, resourcesStrings, npc.name, getPotContextComment(npc)); - } - - for (Quest q : gsrc.gameData.quests) { - if (q.visible_in_log != null && q.visible_in_log != 0) { - pushString(stringsResources, resourcesStrings, q.name, getPotContextComment(q)); - for (QuestStage qs : q.stages) { - pushString(stringsResources, resourcesStrings, qs.log_text, getPotContextComment(q)+":"+Integer.toString(qs.progress)); - } - } - } - - for (WorldmapSegment ws : gsrc.worldmap) { - for (WorldmapSegment.NamedArea area : ws.labels.values()) { - pushString(stringsResources, resourcesStrings, area.name, gsrc.worldmap.worldmapFile.getName()+":"+ws.id+":"+area.id); - } - } - - File f = new File(proj.alteredContent.baseFolder, "english.pot"); - PoPotWriter.writePotFile(stringsResources, f); - - } - - private static void pushString (Map> stringsResources, Map resourcesStrings, String translatableString, String resourceIdentifier) { - if (translatableString == null) return; - if (translatableString.length() == 0) return; - if (translatableString.contains("\"")) { - translatableString = translatableString.replaceAll("\"", "\\\\\""); - } - if (translatableString.contains("\n")) { - translatableString = translatableString.replaceAll("\n", "\\\\n\"\n\""); - translatableString = "\"\n\""+translatableString; - } - resourcesStrings.put(resourceIdentifier, translatableString); - List resourceIdentifiers = stringsResources.get(translatableString); - if (resourceIdentifiers == null) { - resourceIdentifiers = new LinkedList(); - stringsResources.put(translatableString, resourceIdentifiers); - } - resourceIdentifiers.add(resourceIdentifier); - } - - private static String getPotContextComment(JSONElement e) { - return e.jsonFile.getName()+":"+e.id; - } + public static void generatePotFileForProject(Project proj) { + Map> stringsResources = new LinkedHashMap>(); + Map resourcesStrings = new LinkedHashMap(); + + GameSource gsrc = proj.baseContent; + + for (ActorCondition ac : gsrc.gameData.actorConditions) { + pushString(stringsResources, resourcesStrings, ac.display_name, getPotContextComment(ac)); + pushString(stringsResources, resourcesStrings, ac.description, getPotContextComment(ac) + ":description"); + } + + for (Dialogue d : gsrc.gameData.dialogues) { + pushString(stringsResources, resourcesStrings, d.message, getPotContextComment(d)); + if (d.replies == null) continue; + for (Dialogue.Reply r : d.replies) { + if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) { + pushString(stringsResources, resourcesStrings, r.text, getPotContextComment(d) + ":" + d.replies.indexOf(r)); + } + } + } + + for (ItemCategory ic : gsrc.gameData.itemCategories) { + pushString(stringsResources, resourcesStrings, ic.name, getPotContextComment(ic)); + } + + for (Item i : gsrc.gameData.items) { + pushString(stringsResources, resourcesStrings, i.name, getPotContextComment(i)); + pushString(stringsResources, resourcesStrings, i.description, getPotContextComment(i) + ":description"); + } + + for (NPC npc : gsrc.gameData.npcs) { + pushString(stringsResources, resourcesStrings, npc.name, getPotContextComment(npc)); + } + + for (Quest q : gsrc.gameData.quests) { + if (q.visible_in_log != null && q.visible_in_log != 0) { + pushString(stringsResources, resourcesStrings, q.name, getPotContextComment(q)); + for (QuestStage qs : q.stages) { + pushString(stringsResources, resourcesStrings, qs.log_text, getPotContextComment(q) + ":" + Integer.toString(qs.progress)); + } + } + } + + for (WorldmapSegment ws : gsrc.worldmap) { + for (WorldmapSegment.NamedArea area : ws.labels.values()) { + pushString(stringsResources, resourcesStrings, area.name, gsrc.worldmap.worldmapFile.getName() + ":" + ws.id + ":" + area.id); + } + } + + File f = new File(proj.alteredContent.baseFolder, "english.pot"); + PoPotWriter.writePotFile(stringsResources, f); + + } + + private static void pushString(Map> stringsResources, Map resourcesStrings, String translatableString, String resourceIdentifier) { + if (translatableString == null) return; + if (translatableString.length() == 0) return; + if (translatableString.contains("\"")) { + translatableString = translatableString.replaceAll("\"", "\\\\\""); + } + if (translatableString.contains("\n")) { + translatableString = translatableString.replaceAll("\n", "\\\\n\"\n\""); + translatableString = "\"\n\"" + translatableString; + } + resourcesStrings.put(resourceIdentifier, translatableString); + List resourceIdentifiers = stringsResources.get(translatableString); + if (resourceIdentifiers == null) { + resourceIdentifiers = new LinkedList(); + stringsResources.put(translatableString, resourceIdentifiers); + } + resourceIdentifiers.add(resourceIdentifier); + } + + private static String getPotContextComment(JSONElement e) { + return e.jsonFile.getName() + ":" + e.id; + } + - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java b/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java index e69f272..2ae6eb3 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/ResourcesCompactor.java @@ -1,30 +1,7 @@ package com.gpl.rpg.atcontentstudio.model.tools.resoptimizer; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringWriter; -import java.nio.CharBuffer; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.imageio.ImageIO; - -import org.json.simple.JSONArray; - import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; @@ -38,343 +15,351 @@ import com.whoischarles.util.json.Minify; import com.whoischarles.util.json.Minify.UnterminatedCommentException; import com.whoischarles.util.json.Minify.UnterminatedRegExpLiteralException; import com.whoischarles.util.json.Minify.UnterminatedStringLiteralException; - +import org.json.simple.JSONArray; import tiled.core.TileSet; import tiled.io.TMXMapWriter; +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; +import java.util.List; +import java.util.*; + /** - * * @author Kevin - * + *

* To use this, paste the following script in the beanshell console of ATCS. * Don't forget to change the project number to suit your needs. - * -import com.gpl.rpg.atcontentstudio.model.tools.resoptimizer.ResourcesCompactor; -import com.gpl.rpg.atcontentstudio.model.Workspace; - -proj = Workspace.activeWorkspace.projects.get(0); -new ResourcesCompactor(proj).compactData(); + *

+ * + * import com.gpl.rpg.atcontentstudio.model.tools.resoptimizer.ResourcesCompactor; + * import com.gpl.rpg.atcontentstudio.model.Workspace; * + * proj = Workspace.activeWorkspace.projects.get(0); + * new ResourcesCompactor(proj).compactData(); + * */ public class ResourcesCompactor { - public static String DEFAULT_REL_PATH_IN_PROJECT = "compressed"+File.separator; - - private Project proj; - private File baseFolder; - private List compressedSpritesheets = new LinkedList(); - private List preservedSpritesheets = new LinkedList(); - - private Map spritesRelocationForObjects = new LinkedHashMap(); - private Integer currentSpritesheetIndexForObjects = 0; - private CompressedSpritesheet currentSpritesheetForObjects = null; + public static String DEFAULT_REL_PATH_IN_PROJECT = "compressed" + File.separator; - private Map spritesRelocationForMaps = new LinkedHashMap(); - private Map spritesheetsBySidForMaps = new LinkedHashMap(); - private Integer currentSpritesheetIndexForMaps = 0; - private CompressedSpritesheet currentSpritesheetForMaps = null; - - public ResourcesCompactor(Project proj) { - this.proj = proj; - this.baseFolder = new File(proj.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); - if (!baseFolder.exists()) baseFolder.mkdirs(); - } - - public void compactData() { - compactJsonData(); - for(CompressedSpritesheet cs : compressedSpritesheets) { - cs.drawFile(); - } - for (File preserved : preservedSpritesheets) { - FileUtils.copyFile(preserved, new File(baseFolder.getAbsolutePath()+File.separator+DEFAULT_DRAWABLE_REL_PATH+File.separator+preserved.getName())); - } - compactMaps(); - } - - public void compactJsonData() { - final List filesCovered = new LinkedList(); - - File folder = new File(baseFolder.getAbsolutePath()+File.separator+GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); - if (!folder.exists()) folder.mkdirs(); - - for (ActorCondition ac : proj.baseContent.gameData.actorConditions) { - if (filesCovered.contains(ac.jsonFile)) continue; - File currentFile = ac.jsonFile; - filesCovered.add(currentFile); - List dataToSave = new ArrayList(); - for (ActorCondition acond : proj.baseContent.gameData.actorConditions) { - if (!acond.jsonFile.equals(currentFile)) continue; - Map json = acond.toJson(); - json.put("iconID", convertObjectSprite(acond.icon_id).toStringID()); - dataToSave.add(json); - } - File target = new File(folder, ac.jsonFile.getName()); - writeJson(dataToSave, target); - } - - for (Item it : proj.baseContent.gameData.items) { - if (filesCovered.contains(it.jsonFile)) continue; - File currentFile = it.jsonFile; - filesCovered.add(currentFile); - List dataToSave = new ArrayList(); - for (Item item : proj.baseContent.gameData.items) { - if (!item.jsonFile.equals(currentFile)) continue; - Map json = item.toJson(); - json.put("iconID", convertObjectSprite(item.icon_id).toStringID()); - dataToSave.add(json); - } - File target = new File(folder, it.jsonFile.getName()); - writeJson(dataToSave, target); - } - + private Project proj; + private File baseFolder; + private List compressedSpritesheets = new LinkedList(); + private List preservedSpritesheets = new LinkedList(); - for (NPC np : proj.baseContent.gameData.npcs) { - if (filesCovered.contains(np.jsonFile)) continue; - File currentFile = np.jsonFile; - filesCovered.add(currentFile); - List dataToSave = new ArrayList(); - for (NPC npc : proj.baseContent.gameData.npcs) { - if (!npc.jsonFile.equals(currentFile)) continue; - Map json = npc.toJson(); - if (proj.getImage(npc.icon_id).getWidth(null) == TILE_WIDTH_IN_PIXELS || proj.getImage(npc.icon_id).getHeight(null) == TILE_HEIGHT_IN_PIXELS) { - json.put("iconID", convertObjectSprite(npc.icon_id).toStringID()); - } - dataToSave.add(json); - } - File target = new File(folder, np.jsonFile.getName()); - writeJson(dataToSave, target); - } - - File[] remainingFiles = proj.baseContent.gameData.baseFolder.listFiles(new FileFilter() { - @Override - public boolean accept(File arg0) { - return arg0.getName().endsWith(".json") && !filesCovered.contains(arg0); - } - }); - - for (File source : remainingFiles) { - File target = new File(folder, source.getName()); - minifyJson(source, target); - } - } + private Map spritesRelocationForObjects = new LinkedHashMap(); + private Integer currentSpritesheetIndexForObjects = 0; + private CompressedSpritesheet currentSpritesheetForObjects = null; - private Minify jsonMinifier = new Minify(); - - private void writeJson(List dataToSave, File target) { - StringWriter writer = new JsonPrettyWriter(); - try { - JSONArray.writeJSONString(dataToSave, writer); - } catch (IOException e) { - //Impossible with a StringWriter - } - String toWrite = writer.toString(); - try { - FileWriter w = new FileWriter(target); - w.write(jsonMinifier.minify(toWrite)); - w.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } + private Map spritesRelocationForMaps = new LinkedHashMap(); + private Map spritesheetsBySidForMaps = new LinkedHashMap(); + private Integer currentSpritesheetIndexForMaps = 0; + private CompressedSpritesheet currentSpritesheetForMaps = null; - private void minifyJson(File source, File target) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { - FileInputStream fis = new FileInputStream(source); - jsonMinifier.minify(fis, baos); - FileWriter w = new FileWriter(target); - w.write(baos.toString()); - w.close(); - } catch (IOException e) { - e.printStackTrace(); - } catch (UnterminatedRegExpLiteralException e) { - e.printStackTrace(); - } catch (UnterminatedCommentException e) { - e.printStackTrace(); - } catch (UnterminatedStringLiteralException e) { - e.printStackTrace(); - } - } - private void compactMaps() { - for (TMXMap map : proj.baseContent.gameMaps.tmxMaps) { - TMXMap clone = map.clone(); - for (GameDataElement gde : clone.getBacklinks()) { - gde.removeBacklink(clone); - } - clone.getBacklinks().clear(); - tiled.core.Map tmx = clone.tmxMap; - compactMap(tmx, map.id); - clone.tmxMap = null; - clone.groups.clear(); + public ResourcesCompactor(Project proj) { + this.proj = proj; + this.baseFolder = new File(proj.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); + if (!baseFolder.exists()) baseFolder.mkdirs(); + } + + public void compactData() { + compactJsonData(); + for (CompressedSpritesheet cs : compressedSpritesheets) { + cs.drawFile(); } - } - - private void compactMap(tiled.core.Map tmx, String name) { - File target = new File(baseFolder.getAbsolutePath()+File.separator+TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE+File.separator+name+".tmx"); - if (!target.getParentFile().exists()) target.getParentFile().mkdirs(); - - Map localConvertions = new LinkedHashMap(); - List usedSpritesheets = new LinkedList(); - - List toRemove = new LinkedList(); - - for (tiled.core.TileSet ts : tmx.getTileSets()) { - if (!ts.getName().equalsIgnoreCase("map_dynamic_placeholders")) { - toRemove.add(ts); - } - } - - for (tiled.core.TileLayer layer : tmx.getTileLayers()) { - for (int x = 0; x < layer.getWidth(); x++) { - for (int y = 0; y < layer.getHeight(); y++) { - tiled.core.Tile tile = layer.getTileAt(x, y); - if (tile != null && !tile.getTileSet().getName().equalsIgnoreCase("map_dynamic_placeholders")) { - SpritesheetId sid = convertMapSprite(SpritesheetId.toStringID(tile.getTileSet().getName(), tile.getId())); - localConvertions.put(tile, sid); - if (!usedSpritesheets.contains(spritesheetsBySidForMaps.get(sid))) { - usedSpritesheets.add(spritesheetsBySidForMaps.get(sid)); - } - } - } - } - } - - Map csToTs = new LinkedHashMap(); - for (CompressedSpritesheet cs : usedSpritesheets) { - cs.drawFile(); - tiled.core.TileSet ts = new tiled.core.TileSet(); - csToTs.put(cs, ts); - tiled.util.BasicTileCutter cutter = new tiled.util.BasicTileCutter(TILE_WIDTH_IN_PIXELS, TILE_HEIGHT_IN_PIXELS, 0, 0); - try { - ts.importTileBitmap(cs.f.getAbsolutePath(), cutter); - } catch (IOException e) { - e.printStackTrace(); - } - ts.setName(cs.prefix+Integer.toString(cs.index)); - //ts.setSource("../drawable/"+ts.getName()+TILESHEET_SUFFIX); - tmx.addTileset(ts); - } - - for (tiled.core.TileLayer layer : tmx.getTileLayers()) { - for (tiled.core.Tile tile : localConvertions.keySet()) { - SpritesheetId sid = localConvertions.get(tile); - layer.replaceTile(tile, csToTs.get(spritesheetsBySidForMaps.get(sid)).getTile(sid.offset)); - } - } - - for (tiled.core.TileSet ts : toRemove) { - tmx.removeTileset(ts); - } - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - TMXMapWriter writer = new TMXMapWriter(); - writer.settings.layerCompressionMethod = TMXMapWriter.Settings.LAYER_COMPRESSION_METHOD_ZLIB; - try { - writer.writeMap(tmx, baos, target.getAbsolutePath()); - String xml = baos.toString(); - FileWriter w = new FileWriter(target); - w.write(xml); - w.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - private SpritesheetId convertObjectSprite(String originalSpriteId) { - if (spritesRelocationForObjects.containsKey(SpritesheetId.getInstance(originalSpriteId))) { - return spritesRelocationForObjects.get(SpritesheetId.getInstance(originalSpriteId)); - } else if (currentSpritesheetForObjects == null || !currentSpritesheetForObjects.hasFreeSlot()) { - currentSpritesheetForObjects = new CompressedSpritesheet(TILESHEET_PREFIX_FOR_OBJECTS, currentSpritesheetIndexForObjects); - compressedSpritesheets.add(currentSpritesheetForObjects); - currentSpritesheetIndexForObjects++; - } - SpritesheetId sid = currentSpritesheetForObjects.addSprite(originalSpriteId); - spritesRelocationForObjects.put(SpritesheetId.getInstance(originalSpriteId), sid); - return sid; - } - - private SpritesheetId convertMapSprite(String originalSpriteId) { - if (spritesRelocationForMaps.containsKey(SpritesheetId.getInstance(originalSpriteId))) { - return spritesRelocationForMaps.get(SpritesheetId.getInstance(originalSpriteId)); - } else if (currentSpritesheetForMaps == null || !currentSpritesheetForMaps.hasFreeSlot()) { - currentSpritesheetForMaps = new CompressedSpritesheet(TILESHEET_PREFIX_FOR_MAPS, currentSpritesheetIndexForMaps); - compressedSpritesheets.add(currentSpritesheetForMaps); - currentSpritesheetIndexForMaps++; - } - SpritesheetId sid = currentSpritesheetForMaps.addSprite(originalSpriteId); - spritesRelocationForMaps.put(SpritesheetId.getInstance(originalSpriteId), sid); - spritesheetsBySidForMaps.put(sid, currentSpritesheetForMaps); - return sid; - } - - - private static final int TILESHEET_WIDTH_IN_SPRITES = 8; - private static final int TILESHEET_HEIGHT_IN_SPRITES = 8; - private static final int TILE_WIDTH_IN_PIXELS = 32; - private static final int TILE_HEIGHT_IN_PIXELS = 32; - - private static final String TILESHEET_PREFIX_FOR_OBJECTS = "obj_"; - private static final String TILESHEET_PREFIX_FOR_MAPS = "map_"; - private static final String TILESHEET_SUFFIX = ".png"; - - private static final String DEFAULT_DRAWABLE_REL_PATH = SpriteSheetSet.DEFAULT_REL_PATH_IN_SOURCE; - - private class CompressedSpritesheet { - String prefix; - int index; - File f; + for (File preserved : preservedSpritesheets) { + FileUtils.copyFile(preserved, new File(baseFolder.getAbsolutePath() + File.separator + DEFAULT_DRAWABLE_REL_PATH + File.separator + preserved.getName())); + } + compactMaps(); + } + + public void compactJsonData() { + final List filesCovered = new LinkedList(); + + File folder = new File(baseFolder.getAbsolutePath() + File.separator + GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); + if (!folder.exists()) folder.mkdirs(); + + for (ActorCondition ac : proj.baseContent.gameData.actorConditions) { + if (filesCovered.contains(ac.jsonFile)) continue; + File currentFile = ac.jsonFile; + filesCovered.add(currentFile); + List dataToSave = new ArrayList(); + for (ActorCondition acond : proj.baseContent.gameData.actorConditions) { + if (!acond.jsonFile.equals(currentFile)) continue; + Map json = acond.toJson(); + json.put("iconID", convertObjectSprite(acond.icon_id).toStringID()); + dataToSave.add(json); + } + File target = new File(folder, ac.jsonFile.getName()); + writeJson(dataToSave, target); + } + + for (Item it : proj.baseContent.gameData.items) { + if (filesCovered.contains(it.jsonFile)) continue; + File currentFile = it.jsonFile; + filesCovered.add(currentFile); + List dataToSave = new ArrayList(); + for (Item item : proj.baseContent.gameData.items) { + if (!item.jsonFile.equals(currentFile)) continue; + Map json = item.toJson(); + json.put("iconID", convertObjectSprite(item.icon_id).toStringID()); + dataToSave.add(json); + } + File target = new File(folder, it.jsonFile.getName()); + writeJson(dataToSave, target); + } + + + for (NPC np : proj.baseContent.gameData.npcs) { + if (filesCovered.contains(np.jsonFile)) continue; + File currentFile = np.jsonFile; + filesCovered.add(currentFile); + List dataToSave = new ArrayList(); + for (NPC npc : proj.baseContent.gameData.npcs) { + if (!npc.jsonFile.equals(currentFile)) continue; + Map json = npc.toJson(); + if (proj.getImage(npc.icon_id).getWidth(null) == TILE_WIDTH_IN_PIXELS || proj.getImage(npc.icon_id).getHeight(null) == TILE_HEIGHT_IN_PIXELS) { + json.put("iconID", convertObjectSprite(npc.icon_id).toStringID()); + } + dataToSave.add(json); + } + File target = new File(folder, np.jsonFile.getName()); + writeJson(dataToSave, target); + } + + File[] remainingFiles = proj.baseContent.gameData.baseFolder.listFiles(new FileFilter() { + @Override + public boolean accept(File arg0) { + return arg0.getName().endsWith(".json") && !filesCovered.contains(arg0); + } + }); + + for (File source : remainingFiles) { + File target = new File(folder, source.getName()); + minifyJson(source, target); + } + } + + private Minify jsonMinifier = new Minify(); + + private void writeJson(List dataToSave, File target) { + StringWriter writer = new JsonPrettyWriter(); + try { + JSONArray.writeJSONString(dataToSave, writer); + } catch (IOException e) { + //Impossible with a StringWriter + } + String toWrite = writer.toString(); + try { + FileWriter w = new FileWriter(target); + w.write(jsonMinifier.minify(toWrite)); + w.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private void minifyJson(File source, File target) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try { + FileInputStream fis = new FileInputStream(source); + jsonMinifier.minify(fis, baos); + FileWriter w = new FileWriter(target); + w.write(baos.toString()); + w.close(); + } catch (IOException e) { + e.printStackTrace(); + } catch (UnterminatedRegExpLiteralException e) { + e.printStackTrace(); + } catch (UnterminatedCommentException e) { + e.printStackTrace(); + } catch (UnterminatedStringLiteralException e) { + e.printStackTrace(); + } + } + + private void compactMaps() { + for (TMXMap map : proj.baseContent.gameMaps.tmxMaps) { + TMXMap clone = map.clone(); + for (GameDataElement gde : clone.getBacklinks()) { + gde.removeBacklink(clone); + } + clone.getBacklinks().clear(); + tiled.core.Map tmx = clone.tmxMap; + compactMap(tmx, map.id); + clone.tmxMap = null; + clone.groups.clear(); + } + } + + private void compactMap(tiled.core.Map tmx, String name) { + File target = new File(baseFolder.getAbsolutePath() + File.separator + TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE + File.separator + name + ".tmx"); + if (!target.getParentFile().exists()) target.getParentFile().mkdirs(); + + Map localConvertions = new LinkedHashMap(); + List usedSpritesheets = new LinkedList(); + + List toRemove = new LinkedList(); + + for (tiled.core.TileSet ts : tmx.getTileSets()) { + if (!ts.getName().equalsIgnoreCase("map_dynamic_placeholders")) { + toRemove.add(ts); + } + } + + for (tiled.core.TileLayer layer : tmx.getTileLayers()) { + for (int x = 0; x < layer.getWidth(); x++) { + for (int y = 0; y < layer.getHeight(); y++) { + tiled.core.Tile tile = layer.getTileAt(x, y); + if (tile != null && !tile.getTileSet().getName().equalsIgnoreCase("map_dynamic_placeholders")) { + SpritesheetId sid = convertMapSprite(SpritesheetId.toStringID(tile.getTileSet().getName(), tile.getId())); + localConvertions.put(tile, sid); + if (!usedSpritesheets.contains(spritesheetsBySidForMaps.get(sid))) { + usedSpritesheets.add(spritesheetsBySidForMaps.get(sid)); + } + } + } + } + } + + Map csToTs = new LinkedHashMap(); + for (CompressedSpritesheet cs : usedSpritesheets) { + cs.drawFile(); + tiled.core.TileSet ts = new tiled.core.TileSet(); + csToTs.put(cs, ts); + tiled.util.BasicTileCutter cutter = new tiled.util.BasicTileCutter(TILE_WIDTH_IN_PIXELS, TILE_HEIGHT_IN_PIXELS, 0, 0); + try { + ts.importTileBitmap(cs.f.getAbsolutePath(), cutter); + } catch (IOException e) { + e.printStackTrace(); + } + ts.setName(cs.prefix + Integer.toString(cs.index)); + //ts.setSource("../drawable/"+ts.getName()+TILESHEET_SUFFIX); + tmx.addTileset(ts); + } + + for (tiled.core.TileLayer layer : tmx.getTileLayers()) { + for (tiled.core.Tile tile : localConvertions.keySet()) { + SpritesheetId sid = localConvertions.get(tile); + layer.replaceTile(tile, csToTs.get(spritesheetsBySidForMaps.get(sid)).getTile(sid.offset)); + } + } + + for (tiled.core.TileSet ts : toRemove) { + tmx.removeTileset(ts); + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + TMXMapWriter writer = new TMXMapWriter(); + writer.settings.layerCompressionMethod = TMXMapWriter.Settings.LAYER_COMPRESSION_METHOD_ZLIB; + try { + writer.writeMap(tmx, baos, target.getAbsolutePath()); + String xml = baos.toString(); + FileWriter w = new FileWriter(target); + w.write(xml); + w.close(); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + private SpritesheetId convertObjectSprite(String originalSpriteId) { + if (spritesRelocationForObjects.containsKey(SpritesheetId.getInstance(originalSpriteId))) { + return spritesRelocationForObjects.get(SpritesheetId.getInstance(originalSpriteId)); + } else if (currentSpritesheetForObjects == null || !currentSpritesheetForObjects.hasFreeSlot()) { + currentSpritesheetForObjects = new CompressedSpritesheet(TILESHEET_PREFIX_FOR_OBJECTS, currentSpritesheetIndexForObjects); + compressedSpritesheets.add(currentSpritesheetForObjects); + currentSpritesheetIndexForObjects++; + } + SpritesheetId sid = currentSpritesheetForObjects.addSprite(originalSpriteId); + spritesRelocationForObjects.put(SpritesheetId.getInstance(originalSpriteId), sid); + return sid; + } + + private SpritesheetId convertMapSprite(String originalSpriteId) { + if (spritesRelocationForMaps.containsKey(SpritesheetId.getInstance(originalSpriteId))) { + return spritesRelocationForMaps.get(SpritesheetId.getInstance(originalSpriteId)); + } else if (currentSpritesheetForMaps == null || !currentSpritesheetForMaps.hasFreeSlot()) { + currentSpritesheetForMaps = new CompressedSpritesheet(TILESHEET_PREFIX_FOR_MAPS, currentSpritesheetIndexForMaps); + compressedSpritesheets.add(currentSpritesheetForMaps); + currentSpritesheetIndexForMaps++; + } + SpritesheetId sid = currentSpritesheetForMaps.addSprite(originalSpriteId); + spritesRelocationForMaps.put(SpritesheetId.getInstance(originalSpriteId), sid); + spritesheetsBySidForMaps.put(sid, currentSpritesheetForMaps); + return sid; + } + + + private static final int TILESHEET_WIDTH_IN_SPRITES = 8; + private static final int TILESHEET_HEIGHT_IN_SPRITES = 8; + private static final int TILE_WIDTH_IN_PIXELS = 32; + private static final int TILE_HEIGHT_IN_PIXELS = 32; + + private static final String TILESHEET_PREFIX_FOR_OBJECTS = "obj_"; + private static final String TILESHEET_PREFIX_FOR_MAPS = "map_"; + private static final String TILESHEET_SUFFIX = ".png"; + + private static final String DEFAULT_DRAWABLE_REL_PATH = SpriteSheetSet.DEFAULT_REL_PATH_IN_SOURCE; + + private class CompressedSpritesheet { + String prefix; + int index; + File f; + + + boolean mustDraw = true; + int nextFreeSlot = 0; + String[] originalSpritesId = new String[TILESHEET_WIDTH_IN_SPRITES * TILESHEET_HEIGHT_IN_SPRITES]; + + public CompressedSpritesheet(String prefix, int index) { + this.prefix = prefix; + this.index = index; + + File folder = new File(ResourcesCompactor.this.baseFolder.getAbsolutePath() + File.separator + DEFAULT_DRAWABLE_REL_PATH); + if (!folder.exists()) folder.mkdirs(); + this.f = new File(folder, prefix + Integer.toString(index) + TILESHEET_SUFFIX); + } + + public boolean hasFreeSlot() { + return nextFreeSlot < TILESHEET_WIDTH_IN_SPRITES * TILESHEET_HEIGHT_IN_SPRITES; + } + + public SpritesheetId addSprite(String spriteId) { + mustDraw = true; + originalSpritesId[nextFreeSlot] = spriteId; + nextFreeSlot++; + return SpritesheetId.getInstance(prefix + Integer.toString(index), nextFreeSlot - 1); + } + + + public void drawFile() { + if (!mustDraw) return; + BufferedImage img = new BufferedImage(TILESHEET_WIDTH_IN_SPRITES * TILE_WIDTH_IN_PIXELS, TILESHEET_HEIGHT_IN_SPRITES * TILE_HEIGHT_IN_PIXELS, BufferedImage.TYPE_INT_ARGB); + Graphics2D g = (Graphics2D) img.getGraphics(); + Color transparent = new Color(0, 0, 0, 0); + g.setColor(transparent); + g.fillRect(0, 0, img.getWidth(), img.getHeight()); + for (int i = 0; i < nextFreeSlot; i++) { + g.drawImage( + proj.getImage(originalSpritesId[i]), + (i % TILESHEET_WIDTH_IN_SPRITES) * TILE_WIDTH_IN_PIXELS, + (i / TILESHEET_WIDTH_IN_SPRITES) * TILE_HEIGHT_IN_PIXELS, + TILE_WIDTH_IN_PIXELS, + TILE_HEIGHT_IN_PIXELS, + null); + } + try { + ImageIO.write(img, "png", f); + mustDraw = false; + } catch (IOException e) { + e.printStackTrace(); + } + } + } - - boolean mustDraw = true; - int nextFreeSlot = 0; - String[] originalSpritesId = new String[TILESHEET_WIDTH_IN_SPRITES * TILESHEET_HEIGHT_IN_SPRITES]; - - public CompressedSpritesheet(String prefix, int index) { - this.prefix = prefix; - this.index = index; - - File folder = new File(ResourcesCompactor.this.baseFolder.getAbsolutePath()+File.separator+DEFAULT_DRAWABLE_REL_PATH); - if (!folder.exists()) folder.mkdirs(); - this.f = new File(folder, prefix+Integer.toString(index)+TILESHEET_SUFFIX); - } - - public boolean hasFreeSlot() { - return nextFreeSlot < TILESHEET_WIDTH_IN_SPRITES * TILESHEET_HEIGHT_IN_SPRITES; - } - - public SpritesheetId addSprite(String spriteId) { - mustDraw = true; - originalSpritesId[nextFreeSlot] = spriteId; - nextFreeSlot++; - return SpritesheetId.getInstance(prefix+Integer.toString(index), nextFreeSlot - 1); - } - - - public void drawFile() { - if (!mustDraw) return; - BufferedImage img = new BufferedImage(TILESHEET_WIDTH_IN_SPRITES * TILE_WIDTH_IN_PIXELS, TILESHEET_HEIGHT_IN_SPRITES * TILE_HEIGHT_IN_PIXELS, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = (Graphics2D)img.getGraphics(); - Color transparent = new Color(0, 0, 0, 0); - g.setColor(transparent); - g.fillRect(0, 0, img.getWidth(), img.getHeight()); - for (int i = 0; i < nextFreeSlot; i++) { - g.drawImage( - proj.getImage(originalSpritesId[i]), - (i % TILESHEET_WIDTH_IN_SPRITES) * TILE_WIDTH_IN_PIXELS, - (i / TILESHEET_WIDTH_IN_SPRITES) * TILE_HEIGHT_IN_PIXELS, - TILE_WIDTH_IN_PIXELS, - TILE_HEIGHT_IN_PIXELS, - null); - } - try { - ImageIO.write(img, "png", f); - mustDraw = false; - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } \ No newline at end of file diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/SpritesheetId.java b/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/SpritesheetId.java index 1200da7..d8c7cd2 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/SpritesheetId.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/resoptimizer/SpritesheetId.java @@ -4,35 +4,35 @@ import java.util.LinkedHashMap; import java.util.Map; public class SpritesheetId { - static Map instancesCache = new LinkedHashMap(); + static Map instancesCache = new LinkedHashMap(); - String tileset; - int offset; + String tileset; + int offset; - static SpritesheetId getInstance(String id) { - String[] values = id.split(":"); - return getInstance(values[0], Integer.parseInt(values[1])); - } + static SpritesheetId getInstance(String id) { + String[] values = id.split(":"); + return getInstance(values[0], Integer.parseInt(values[1])); + } - static SpritesheetId getInstance(String tilesetId, int offset) { - if (!instancesCache.containsKey(toStringID(tilesetId, offset))) { - SpritesheetId instance = new SpritesheetId(tilesetId, offset); - instancesCache.put(instance.toStringID(), instance); - } - return instancesCache.get(toStringID(tilesetId, offset)); - } + static SpritesheetId getInstance(String tilesetId, int offset) { + if (!instancesCache.containsKey(toStringID(tilesetId, offset))) { + SpritesheetId instance = new SpritesheetId(tilesetId, offset); + instancesCache.put(instance.toStringID(), instance); + } + return instancesCache.get(toStringID(tilesetId, offset)); + } - private SpritesheetId(String tileset, int offset) { - this.tileset = tileset; - this.offset = offset; - } + private SpritesheetId(String tileset, int offset) { + this.tileset = tileset; + this.offset = offset; + } - public String toStringID() { - return toStringID(tileset, offset); - } + public String toStringID() { + return toStringID(tileset, offset); + } - static String toStringID(String tileset, int offset) { - return tileset+":"+Integer.toString(offset); - } + static String toStringID(String tileset, int offset) { + return tileset + ":" + Integer.toString(offset); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java index 432c648..d2bf908 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java @@ -1,6 +1,17 @@ package com.gpl.rpg.atcontentstudio.model.tools.writermode; -import java.awt.Image; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; +import com.gpl.rpg.atcontentstudio.model.SaveEvent; +import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; +import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; @@ -12,521 +23,551 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.SaveEvent; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; - public class WriterModeData extends GameDataElement { - private static final long serialVersionUID = -7062544089063979696L; - - public File jsonFile; + private static final long serialVersionUID = -7062544089063979696L; - public Image npcIcon; + public File jsonFile; + + public Image npcIcon; // public String sketchName; - - public List rootsId = new ArrayList(); - public List roots = new ArrayList(); - public WriterDialogue begin; - public Map nodesById = new LinkedHashMap(); - //public Map dialogueThreads = new LinkedHashMap(); - public Map threadsNextIndex = new LinkedHashMap(); - + public List rootsId = new ArrayList(); + public List roots = new ArrayList(); + public WriterDialogue begin; + public Map nodesById = new LinkedHashMap(); - public WriterModeData(String id_prefix){ - this.id = id_prefix; - } + //public Map dialogueThreads = new LinkedHashMap(); + public Map threadsNextIndex = new LinkedHashMap(); - @SuppressWarnings("rawtypes") - public WriterModeData(WriterModeDataSet parent, Map jsonObj) { - this.parent = parent; - this.jsonFile = parent.writerFile; - this.parse(jsonObj); - this.state = State.parsed; - } - - public WriterModeData(String id_prefix, Dialogue imported) { - this.id = id_prefix; - this.begin = new WriterDialogue(imported); - this.state = State.linked; - } - - public int getNextIndex(String id_prefix) { - Integer index = threadsNextIndex.get(id_prefix); - if (index == null) index = 0; - while (getProject().getDialogue(id_prefix+index) != null) { - index++; - } - threadsNextIndex.put(id_prefix, index + 1); - return index; - } - - - public abstract class WriterNode { - public String text; - - public abstract String getTitle(); - - } - - public WriterDialogue createDialogue(Dialogue dialogue) { - if (dialogue.message == null) { - return new SelectorDialogue(dialogue); - } else { - return new WriterDialogue(dialogue); - } - } - - public class WriterDialogue extends WriterNode { - public String id; - public String id_prefix; - public int index; - public List replies = new ArrayList(); - public List parents = new ArrayList(); - public String dialogue_id; - public Dialogue dialogue; - - public WriterDialogue() {} - - public WriterDialogue(Dialogue dialogue) { - this.dialogue = dialogue; - this.text = dialogue.message; - this.id = this.dialogue_id = dialogue.id; - Pattern p = Pattern.compile("(.*)([0-9]+)"); - Matcher m = p.matcher(dialogue.id); - if (m.matches()) { - this.id_prefix = m.group(1); - this.index = Integer.parseInt(m.group(2)); - } else { - this.id_prefix = this.id+"_"; - } - nodesById.put(this.id, this); - if (dialogue.replies != null) { - for (Dialogue.Reply reply : dialogue.replies) { - if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text) || reply.text == null) { - replies.add(new EmptyReply(this, reply)); - } else { - replies.add(new WriterReply(this, reply)); - } - } - } - } - - public WriterDialogue(String id_prefix) { - text = ""; - this.id_prefix = id_prefix; - index = getNextIndex(id_prefix); - } - - @Override - public String getTitle() { - return "Dialogue "+getID(); - } - - public String getID() { - return this.id != null ? this.id : this.id_prefix+this.index; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void toJson(List visited, List jsonData) { - if (visited.contains(this)) return; - visited.add(this); - Map dialogueJson = new LinkedHashMap(); - jsonData.add(dialogueJson); - dialogueJson.put("id", id); - dialogueJson.put("id_prefix", id_prefix); - dialogueJson.put("index", index); - dialogueJson.put("text", text); - if (dialogue != null) { - dialogueJson.put("dialogue", dialogue.id); - } else if (dialogue_id != null) { - dialogueJson.put("dialogue", dialogue_id); - } - dialogueJson.put("special", isSpecial()); - dialogueJson.put("begin", begin == this); - if (!replies.isEmpty()) { - List repliesJson = new ArrayList(); - for (WriterReply reply : replies) { - repliesJson.add(reply.toJson(visited, jsonData)); - } - dialogueJson.put("replies", repliesJson); - } - } - - @SuppressWarnings("rawtypes") - public WriterDialogue(Map json) { - this.id = (String) json.get("id"); - this.index = ((Number)json.get("index")).intValue(); - this.id_prefix = (String) json.get("id_prefix"); - if (threadsNextIndex.get(id_prefix) == null || threadsNextIndex.get(id_prefix) <= index) { - threadsNextIndex.put(id_prefix, index+1); - } - this.text = (String) json.get("text"); - this.dialogue_id = (String) json.get("dialogue"); - if (json.get("begin") != null && ((Boolean)json.get("begin"))) begin = this; - if (json.get("replies") != null) { - List repliesJson = (List) json.get("replies"); - for (Object rJson : repliesJson) { - if (((Map)rJson).get("special") != null && (Boolean)((Map)rJson).get("special")) { - //TODO Check different cases. But there are none currently. - this.replies.add(new EmptyReply(this, ((Map)rJson))); - } else { - this.replies.add(new WriterReply(this, (Map)rJson)); - } - } - } - } - - public boolean isSpecial() {return false;} - - public Dialogue toDialogue(Map visited, List created, List modified) { - if (visited.get(this) != null) return visited.get(this); - //Creating a new Dialogue - if (dialogue == null) { - dialogue = new Dialogue(); - dialogue.id = getID(); - dialogue.state = GameDataElement.State.parsed; - created.add(dialogue); - } else { - if (hasChanged()) { - if (dialogue.writable) { - //Modifying a created or altered Dialogue - dialogue.state = GameDataElement.State.modified; - modified.add(dialogue); - } else { - //Altering a game source Dialogue - //Dialogue clone = (Dialogue) dialogue.clone(); - dialogue.getProject().makeWritable(dialogue); - Dialogue clone = dialogue.getProject().getDialogue(dialogue.id); - if (this.replies != null) { - for (WriterReply wReply : this.replies) { - if (wReply.reply != null) { - wReply.reply = clone.replies.get(dialogue.replies.indexOf(wReply.reply)); - } - } - } - dialogue = clone; - dialogue.state = GameDataElement.State.parsed; - created.add(dialogue); - } - } - } - visited.put(this, dialogue); - dialogue.message = this.text; - if (this.replies != null && !this.replies.isEmpty()) { - if (dialogue.replies == null) { - dialogue.replies = new ArrayList(); - } else { - dialogue.replies.clear(); - } - for (WriterReply wReply : this.replies) { - //if (wReply.reply != null && dialogue.replies) - dialogue.replies.add(wReply.toReply(visited, created, modified)); - } - } else { - dialogue.replies = null; - } - return dialogue; - } - - public boolean hasChanged() { - return dialogue == null || - text == null ? dialogue.message!=null : !text.equals(dialogue.message) || - repliesHaveChanged(); - } - - public boolean repliesHaveChanged() { - if (replies.isEmpty() && (dialogue.replies == null || dialogue.replies.isEmpty())) return false; - if (!replies.isEmpty() && (dialogue.replies == null || dialogue.replies.isEmpty())) return true; - if (replies.isEmpty() && (dialogue.replies != null && !dialogue.replies.isEmpty())) return true; - if (replies.size() != dialogue.replies.size()) return true; - for (WriterReply reply : replies) { - if (reply.hasChanged()) return true; - } - return false; - } - - } - - public abstract class SpecialDialogue extends WriterDialogue { - - public SpecialDialogue() {} - public boolean isSpecial() {return true;} - public abstract SpecialDialogue duplicate(); - public SpecialDialogue(Dialogue dialogue) { - super(dialogue); - } - } - public class SelectorDialogue extends SpecialDialogue { - public SelectorDialogue() {} - public SpecialDialogue duplicate() {return new SelectorDialogue();} - public SelectorDialogue(Dialogue dialogue) { - super(dialogue); - } - } - public class ShopDialogue extends SpecialDialogue { - public static final String id = Dialogue.Reply.SHOP_PHRASE_ID; - public SpecialDialogue duplicate() {return new ShopDialogue();} - } - public class FightDialogue extends SpecialDialogue { - public static final String id = Dialogue.Reply.FIGHT_PHRASE_ID; - public SpecialDialogue duplicate() {return new FightDialogue();} - } - public class EndDialogue extends SpecialDialogue { - public static final String id = Dialogue.Reply.EXIT_PHRASE_ID; - public SpecialDialogue duplicate() {return new EndDialogue();} - } - public class RemoveNPCDialogue extends SpecialDialogue { - public static final String id = Dialogue.Reply.REMOVE_PHRASE_ID; - public SpecialDialogue duplicate() {return new RemoveNPCDialogue();} - } - - public class WriterReply extends WriterNode { - public WriterDialogue parent; - public String next_dialogue_id; - public WriterDialogue next_dialogue; - public Dialogue.Reply reply; - - public WriterReply() {} - - public WriterReply(WriterDialogue parent) { - this.parent = parent; - this.text = ""; - parent.replies.add(this); - } + public WriterModeData(String id_prefix) { + this.id = id_prefix; + } - public WriterReply(WriterDialogue parent, Dialogue.Reply reply) { - this.parent = parent; - this.reply = reply; - this.text = reply.text; - this.next_dialogue_id = reply.next_phrase_id; - if (nodesById.get(this.next_dialogue_id) != null) { - this.next_dialogue = nodesById.get(this.next_dialogue_id); - } else if (reply.next_phrase != null ){ - this.next_dialogue = new WriterDialogue(reply.next_phrase); - } - } - - @SuppressWarnings("rawtypes") - public WriterReply(WriterDialogue parent, Map json) { - this.parent = parent; - this.text = (String) json.get("text"); - if (json.containsKey("next_dialogue_id")) { - next_dialogue_id = (String) json.get("next_dialogue_id"); - } - } - - @Override - public String getTitle() { - return "Reply in "+parent.id_prefix+parent.index; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Map toJson(List visited, List jsonData) { - Map replyJson = new LinkedHashMap(); - replyJson.put("text", text); - replyJson.put("special", isSpecial()); - if (next_dialogue != null) { - replyJson.put("next_dialogue_id", next_dialogue.getID()); - next_dialogue.toJson(visited, jsonData); - } - return replyJson; - } + @SuppressWarnings("rawtypes") + public WriterModeData(WriterModeDataSet parent, Map jsonObj) { + this.parent = parent; + this.jsonFile = parent.writerFile; + this.parse(jsonObj); + this.state = State.parsed; + } - public boolean isSpecial() {return false;} - - public Dialogue.Reply toReply(Map visited, List created, List modified) { - if (reply == null) { - reply = new Dialogue.Reply(); - } - reply.text = this.text; - if (this.next_dialogue != null) { - this.next_dialogue.toDialogue(visited, created, modified); - reply.next_phrase_id = this.next_dialogue.getID(); - } else if (this.next_dialogue_id != null) { - reply.next_phrase_id = this.next_dialogue_id; - } else { - reply.next_phrase_id = Dialogue.Reply.EXIT_PHRASE_ID; - } - return reply; - } - - public boolean hasChanged() { - if (reply == null) return true; - if (text == null && reply.text != null) return true; - if (text != null && reply.text == null) return true; - if (text != null && !text.equals(reply.text)) return true; - String targetDialogueId = next_dialogue != null ? next_dialogue.getID() : next_dialogue_id; - String replyTargetDialogueId = reply.next_phrase != null ? reply.next_phrase.id : reply.next_phrase_id; - if (targetDialogueId == null && replyTargetDialogueId != null) return true; - if (targetDialogueId != null && replyTargetDialogueId == null) return true; - if (targetDialogueId != null && !targetDialogueId.equals(replyTargetDialogueId)) return true; - return false; - } - - + public WriterModeData(String id_prefix, Dialogue imported) { + this.id = id_prefix; + this.begin = new WriterDialogue(imported); + this.state = State.linked; + } - } - - public class SpecialReply extends WriterReply { + public int getNextIndex(String id_prefix) { + Integer index = threadsNextIndex.get(id_prefix); + if (index == null) index = 0; + while (getProject().getDialogue(id_prefix + index) != null) { + index++; + } + threadsNextIndex.put(id_prefix, index + 1); + return index; + } - public boolean isSpecial() {return true;} - - public SpecialReply(WriterDialogue parent, Dialogue.Reply reply) { - super(parent, reply); - } - - public SpecialReply(WriterDialogue parent) { - super(parent); - } - - public SpecialReply(WriterDialogue parent, @SuppressWarnings("rawtypes") Map json) { - super(parent, json); - } - } - public class EmptyReply extends SpecialReply { - - public EmptyReply(WriterDialogue parent, Dialogue.Reply reply) { - super(parent, reply); - text = Dialogue.Reply.GO_NEXT_TEXT; - } - public EmptyReply(WriterDialogue parent) { - super(parent); - text = Dialogue.Reply.GO_NEXT_TEXT; - } - - public EmptyReply(WriterDialogue parent, @SuppressWarnings("rawtypes") Map json) { - super(parent, json); - text = Dialogue.Reply.GO_NEXT_TEXT; - } - } - - - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+id; - } - @Override - public Project getProject() { - return parent.getProject(); - } - - @Override - public Image getIcon() { - return DefaultIcons.getDialogueIcon(); - } - @Override - public Image getOpenIcon() { - return null; - } - @Override - public Image getClosedIcon() { - return null; - } - @Override - public Image getLeafIcon() { - return getIcon(); - } - @Override - public GameDataSet getDataSet() { - return null; - } - - @Override - public GameDataElement clone() { - //TODO - return null; - } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - // Useless here. - - } - @Override - public String getProjectFilename() { - return WriterModeDataSet.DEFAULT_REL_PATH_IN_PROJECT; - } - - @Override - public void save() { - ((WriterModeDataSet)this.getParent()).save(this.jsonFile); - } - - @Override - public List attemptSave() { - List events = ((WriterModeDataSet)parent).attemptSave(); - if (events == null || events.isEmpty()) { - return null; - } - if (events.size() == 1 && events.get(0).type == SaveEvent.Type.alsoSave && events.get(0).target == this) { - save(); - return null; - } - return events; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public Map toJson() { - List jsonData = new ArrayList(); - begin.toJson(new ArrayList(), jsonData); - Map jsonObj = new LinkedHashMap(); - jsonObj.put("id", id); - jsonObj.put("dialogues", jsonData); - return jsonObj; - } - - @SuppressWarnings("rawtypes") - public void parse() { - if (checkNotRelatedToParseOrLink()) return; - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List gameDataElements = (List) parser.parse(reader); - for (Object obj : gameDataElements) { - Map jsonObj = (Map)obj; - String id = (String) jsonObj.get("id"); - if (id != null && id.equals(this.id )) { - this.parse(jsonObj); - this.state = State.parsed; - break; - } - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+jsonFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } + public abstract class WriterNode { + public String text; - } + public abstract String getTitle(); - @SuppressWarnings("rawtypes") - public void parse(Map json) { - this.id = (String) json.get("id"); + } + + public WriterDialogue createDialogue(Dialogue dialogue) { + if (dialogue.message == null) { + return new SelectorDialogue(dialogue); + } else { + return new WriterDialogue(dialogue); + } + } + + public class WriterDialogue extends WriterNode { + public String id; + public String id_prefix; + public int index; + public List replies = new ArrayList(); + public List parents = new ArrayList(); + public String dialogue_id; + public Dialogue dialogue; + + public WriterDialogue() { + } + + public WriterDialogue(Dialogue dialogue) { + this.dialogue = dialogue; + this.text = dialogue.message; + this.id = this.dialogue_id = dialogue.id; + Pattern p = Pattern.compile("(.*)([0-9]+)"); + Matcher m = p.matcher(dialogue.id); + if (m.matches()) { + this.id_prefix = m.group(1); + this.index = Integer.parseInt(m.group(2)); + } else { + this.id_prefix = this.id + "_"; + } + nodesById.put(this.id, this); + if (dialogue.replies != null) { + for (Dialogue.Reply reply : dialogue.replies) { + if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text) || reply.text == null) { + replies.add(new EmptyReply(this, reply)); + } else { + replies.add(new WriterReply(this, reply)); + } + } + } + } + + public WriterDialogue(String id_prefix) { + text = ""; + this.id_prefix = id_prefix; + index = getNextIndex(id_prefix); + } + + @Override + public String getTitle() { + return "Dialogue " + getID(); + } + + public String getID() { + return this.id != null ? this.id : this.id_prefix + this.index; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public void toJson(List visited, List jsonData) { + if (visited.contains(this)) return; + visited.add(this); + Map dialogueJson = new LinkedHashMap(); + jsonData.add(dialogueJson); + dialogueJson.put("id", id); + dialogueJson.put("id_prefix", id_prefix); + dialogueJson.put("index", index); + dialogueJson.put("text", text); + if (dialogue != null) { + dialogueJson.put("dialogue", dialogue.id); + } else if (dialogue_id != null) { + dialogueJson.put("dialogue", dialogue_id); + } + dialogueJson.put("special", isSpecial()); + dialogueJson.put("begin", begin == this); + if (!replies.isEmpty()) { + List repliesJson = new ArrayList(); + for (WriterReply reply : replies) { + repliesJson.add(reply.toJson(visited, jsonData)); + } + dialogueJson.put("replies", repliesJson); + } + } + + @SuppressWarnings("rawtypes") + public WriterDialogue(Map json) { + this.id = (String) json.get("id"); + this.index = ((Number) json.get("index")).intValue(); + this.id_prefix = (String) json.get("id_prefix"); + if (threadsNextIndex.get(id_prefix) == null || threadsNextIndex.get(id_prefix) <= index) { + threadsNextIndex.put(id_prefix, index + 1); + } + this.text = (String) json.get("text"); + this.dialogue_id = (String) json.get("dialogue"); + if (json.get("begin") != null && ((Boolean) json.get("begin"))) begin = this; + if (json.get("replies") != null) { + List repliesJson = (List) json.get("replies"); + for (Object rJson : repliesJson) { + if (((Map) rJson).get("special") != null && (Boolean) ((Map) rJson).get("special")) { + //TODO Check different cases. But there are none currently. + this.replies.add(new EmptyReply(this, ((Map) rJson))); + } else { + this.replies.add(new WriterReply(this, (Map) rJson)); + } + } + } + } + + public boolean isSpecial() { + return false; + } + + + public Dialogue toDialogue(Map visited, List created, List modified) { + if (visited.get(this) != null) return visited.get(this); + //Creating a new Dialogue + if (dialogue == null) { + dialogue = new Dialogue(); + dialogue.id = getID(); + dialogue.state = GameDataElement.State.parsed; + created.add(dialogue); + } else { + if (hasChanged()) { + if (dialogue.writable) { + //Modifying a created or altered Dialogue + dialogue.state = GameDataElement.State.modified; + modified.add(dialogue); + } else { + //Altering a game source Dialogue + //Dialogue clone = (Dialogue) dialogue.clone(); + dialogue.getProject().makeWritable(dialogue); + Dialogue clone = dialogue.getProject().getDialogue(dialogue.id); + if (this.replies != null) { + for (WriterReply wReply : this.replies) { + if (wReply.reply != null) { + wReply.reply = clone.replies.get(dialogue.replies.indexOf(wReply.reply)); + } + } + } + dialogue = clone; + dialogue.state = GameDataElement.State.parsed; + created.add(dialogue); + } + } + } + visited.put(this, dialogue); + dialogue.message = this.text; + if (this.replies != null && !this.replies.isEmpty()) { + if (dialogue.replies == null) { + dialogue.replies = new ArrayList(); + } else { + dialogue.replies.clear(); + } + for (WriterReply wReply : this.replies) { + //if (wReply.reply != null && dialogue.replies) + dialogue.replies.add(wReply.toReply(visited, created, modified)); + } + } else { + dialogue.replies = null; + } + return dialogue; + } + + public boolean hasChanged() { + return dialogue == null || + text == null ? dialogue.message != null : !text.equals(dialogue.message) || + repliesHaveChanged(); + } + + public boolean repliesHaveChanged() { + if (replies.isEmpty() && (dialogue.replies == null || dialogue.replies.isEmpty())) return false; + if (!replies.isEmpty() && (dialogue.replies == null || dialogue.replies.isEmpty())) return true; + if (replies.isEmpty() && (dialogue.replies != null && !dialogue.replies.isEmpty())) return true; + if (replies.size() != dialogue.replies.size()) return true; + for (WriterReply reply : replies) { + if (reply.hasChanged()) return true; + } + return false; + } + + } + + public abstract class SpecialDialogue extends WriterDialogue { + + public SpecialDialogue() { + } + + public boolean isSpecial() { + return true; + } + + public abstract SpecialDialogue duplicate(); + + public SpecialDialogue(Dialogue dialogue) { + super(dialogue); + } + } + + public class SelectorDialogue extends SpecialDialogue { + public SelectorDialogue() { + } + + public SpecialDialogue duplicate() { + return new SelectorDialogue(); + } + + public SelectorDialogue(Dialogue dialogue) { + super(dialogue); + } + } + + public class ShopDialogue extends SpecialDialogue { + public static final String id = Dialogue.Reply.SHOP_PHRASE_ID; + + public SpecialDialogue duplicate() { + return new ShopDialogue(); + } + } + + public class FightDialogue extends SpecialDialogue { + public static final String id = Dialogue.Reply.FIGHT_PHRASE_ID; + + public SpecialDialogue duplicate() { + return new FightDialogue(); + } + } + + public class EndDialogue extends SpecialDialogue { + public static final String id = Dialogue.Reply.EXIT_PHRASE_ID; + + public SpecialDialogue duplicate() { + return new EndDialogue(); + } + } + + public class RemoveNPCDialogue extends SpecialDialogue { + public static final String id = Dialogue.Reply.REMOVE_PHRASE_ID; + + public SpecialDialogue duplicate() { + return new RemoveNPCDialogue(); + } + } + + public class WriterReply extends WriterNode { + public WriterDialogue parent; + public String next_dialogue_id; + public WriterDialogue next_dialogue; + public Dialogue.Reply reply; + + public WriterReply() { + } + + public WriterReply(WriterDialogue parent) { + this.parent = parent; + this.text = ""; + parent.replies.add(this); + } + + public WriterReply(WriterDialogue parent, Dialogue.Reply reply) { + this.parent = parent; + this.reply = reply; + this.text = reply.text; + this.next_dialogue_id = reply.next_phrase_id; + if (nodesById.get(this.next_dialogue_id) != null) { + this.next_dialogue = nodesById.get(this.next_dialogue_id); + } else if (reply.next_phrase != null) { + this.next_dialogue = new WriterDialogue(reply.next_phrase); + } + } + + @SuppressWarnings("rawtypes") + public WriterReply(WriterDialogue parent, Map json) { + this.parent = parent; + this.text = (String) json.get("text"); + if (json.containsKey("next_dialogue_id")) { + next_dialogue_id = (String) json.get("next_dialogue_id"); + } + } + + @Override + public String getTitle() { + return "Reply in " + parent.id_prefix + parent.index; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public Map toJson(List visited, List jsonData) { + Map replyJson = new LinkedHashMap(); + replyJson.put("text", text); + replyJson.put("special", isSpecial()); + if (next_dialogue != null) { + replyJson.put("next_dialogue_id", next_dialogue.getID()); + next_dialogue.toJson(visited, jsonData); + } + return replyJson; + } + + public boolean isSpecial() { + return false; + } + + public Dialogue.Reply toReply(Map visited, List created, List modified) { + if (reply == null) { + reply = new Dialogue.Reply(); + } + reply.text = this.text; + if (this.next_dialogue != null) { + this.next_dialogue.toDialogue(visited, created, modified); + reply.next_phrase_id = this.next_dialogue.getID(); + } else if (this.next_dialogue_id != null) { + reply.next_phrase_id = this.next_dialogue_id; + } else { + reply.next_phrase_id = Dialogue.Reply.EXIT_PHRASE_ID; + } + return reply; + } + + public boolean hasChanged() { + if (reply == null) return true; + if (text == null && reply.text != null) return true; + if (text != null && reply.text == null) return true; + if (text != null && !text.equals(reply.text)) return true; + String targetDialogueId = next_dialogue != null ? next_dialogue.getID() : next_dialogue_id; + String replyTargetDialogueId = reply.next_phrase != null ? reply.next_phrase.id : reply.next_phrase_id; + if (targetDialogueId == null && replyTargetDialogueId != null) return true; + if (targetDialogueId != null && replyTargetDialogueId == null) return true; + if (targetDialogueId != null && !targetDialogueId.equals(replyTargetDialogueId)) return true; + return false; + } + + + } + + public class SpecialReply extends WriterReply { + + public boolean isSpecial() { + return true; + } + + public SpecialReply(WriterDialogue parent, Dialogue.Reply reply) { + super(parent, reply); + } + + public SpecialReply(WriterDialogue parent) { + super(parent); + } + + public SpecialReply(WriterDialogue parent, @SuppressWarnings("rawtypes") Map json) { + super(parent, json); + } + } + + public class EmptyReply extends SpecialReply { + + public EmptyReply(WriterDialogue parent, Dialogue.Reply reply) { + super(parent, reply); + text = Dialogue.Reply.GO_NEXT_TEXT; + } + + public EmptyReply(WriterDialogue parent) { + super(parent); + text = Dialogue.Reply.GO_NEXT_TEXT; + } + + public EmptyReply(WriterDialogue parent, @SuppressWarnings("rawtypes") Map json) { + super(parent, json); + text = Dialogue.Reply.GO_NEXT_TEXT; + } + } + + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + id; + } + + @Override + public Project getProject() { + return parent.getProject(); + } + + @Override + public Image getIcon() { + return DefaultIcons.getDialogueIcon(); + } + + @Override + public Image getOpenIcon() { + return null; + } + + @Override + public Image getClosedIcon() { + return null; + } + + @Override + public Image getLeafIcon() { + return getIcon(); + } + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public GameDataElement clone() { + //TODO + return null; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + // Useless here. + + } + + @Override + public String getProjectFilename() { + return WriterModeDataSet.DEFAULT_REL_PATH_IN_PROJECT; + } + + @Override + public void save() { + ((WriterModeDataSet) this.getParent()).save(this.jsonFile); + } + + @Override + public List attemptSave() { + List events = ((WriterModeDataSet) parent).attemptSave(); + if (events == null || events.isEmpty()) { + return null; + } + if (events.size() == 1 && events.get(0).type == SaveEvent.Type.alsoSave && events.get(0).target == this) { + save(); + return null; + } + return events; + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public Map toJson() { + List jsonData = new ArrayList(); + begin.toJson(new ArrayList(), jsonData); + Map jsonObj = new LinkedHashMap(); + jsonObj.put("id", id); + jsonObj.put("dialogues", jsonData); + return jsonObj; + } + + @SuppressWarnings("rawtypes") + public void parse() { + if (checkNotRelatedToParseOrLink()) return; + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List gameDataElements = (List) parser.parse(reader); + for (Object obj : gameDataElements) { + Map jsonObj = (Map) obj; + String id = (String) jsonObj.get("id"); + if (id != null && id.equals(this.id)) { + this.parse(jsonObj); + this.state = State.parsed; + break; + } + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + + @SuppressWarnings("rawtypes") + public void parse(Map json) { + this.id = (String) json.get("id"); // this.sketchName = (String) json.get("name"); // List jsonRootsId = (List) json.get("roots_id"); // if (jsonRootsId != null) { @@ -534,121 +575,123 @@ public class WriterModeData extends GameDataElement { // rootsId.add((String) jsonRootId); // } // } - List jsonDialogues = (List) json.get("dialogues"); - if (jsonDialogues != null) { - for (Object jsonDialogue : jsonDialogues) { - WriterDialogue dialogue = new WriterDialogue((Map)jsonDialogue); - nodesById.put(dialogue.getID(), dialogue); - } - } - - this.state = State.parsed; - } - - @Override - public void link() { - if (this.state == State.created) { - this.begin = new WriterDialogue(); - begin.id_prefix = id; - begin.index = getNextIndex(id); - begin.text = ""; - } - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } - if (this.state == State.parsed) { - for (String prefix : threadsNextIndex.keySet()) { - while (getProject().getDialogue(prefix+threadsNextIndex.get(prefix)) != null) { - threadsNextIndex.put(prefix, threadsNextIndex.get(prefix)+1); - } - } - for (WriterDialogue dialogue : nodesById.values()) { - if (dialogue.dialogue_id != null) { - dialogue.dialogue = getProject().getDialogue(dialogue.dialogue_id); - } - if (dialogue.replies == null) continue; - for (WriterReply reply : dialogue.replies) { - if (reply.next_dialogue_id != null) { - if (isSpecial(reply.next_dialogue_id)) { - reply.next_dialogue = getSpecial(reply.next_dialogue_id); - } else { - reply.next_dialogue = nodesById.get(reply.next_dialogue_id); - } - } - //TODO Seriously, this is failure-prone by design. Can't do much better though... - if (dialogue.dialogue != null) { - List linked = new ArrayList(dialogue.dialogue.replies.size()); - if (dialogue.dialogue != null && dialogue.dialogue.replies != null) { - //Try to hook to existing replies... not as easy when there's no ID. - Dialogue.Reply best = null; - int score, maxScore = 0; - for (Dialogue.Reply dReply : dialogue.dialogue.replies) { - //Never link twice to the same... - if (linked.contains(dReply)) continue; - score = 0; - //Arbitrary values... hopefully this gives good results. - //Same target gives good hope of preserving at least the structure. - if (dReply.next_phrase_id != null && dReply.next_phrase_id.equals(reply.next_dialogue_id)) score +=50; - //Same text is almost as good as an ID, but there may be duplicates due to requirements system... - if (dReply.text != null && dReply.text.equals(reply.text)) score +=40; - //Same slot in the list. That's not so bad if all else fails, and could help sort duplicates with same text. - if (dialogue.dialogue.replies.indexOf(dReply) == dialogue.replies.indexOf(reply)) score +=20; - //Both have null text. It's not much, but it's something.... - if (dReply.text == null && reply.text == null) score += 10; - if (score > maxScore) { - maxScore = score; - best = dReply; - } - } - if (maxScore > 0) { - reply.reply = best; - linked.add(best); - } - } - } - } - } - for (String rootId : rootsId) { - roots.add(nodesById.get(rootId)); - } + List jsonDialogues = (List) json.get("dialogues"); + if (jsonDialogues != null) { + for (Object jsonDialogue : jsonDialogues) { + WriterDialogue dialogue = new WriterDialogue((Map) jsonDialogue); + nodesById.put(dialogue.getID(), dialogue); + } + } - } - if (this.state == State.linked) { - //Already linked. - return; - } + this.state = State.parsed; + } - this.state = State.linked; - } - - public boolean isSpecial(String id) { - if (id == null) return false; - if (ShopDialogue.id.equals(id)) return true; - if (FightDialogue.id.equals(id)) return true; - if (EndDialogue.id.equals(id)) return true; - if (RemoveNPCDialogue.id.equals(id)) return true; - return false; - } - - public SpecialDialogue getSpecial(String id) { - if (id == null) return null; - if (ShopDialogue.id.equals(id)) return new ShopDialogue(); - if (FightDialogue.id.equals(id)) return new FightDialogue(); - if (EndDialogue.id.equals(id)) return new EndDialogue(); - if (RemoveNPCDialogue.id.equals(id)) return new RemoveNPCDialogue(); - return null; - } + @Override + public void link() { + if (this.state == State.created) { + this.begin = new WriterDialogue(); + begin.id_prefix = id; + begin.index = getNextIndex(id); + begin.text = ""; + } + if (this.state == State.init) { + //Not parsed yet. + this.parse(); + } + if (this.state == State.parsed) { + for (String prefix : threadsNextIndex.keySet()) { + while (getProject().getDialogue(prefix + threadsNextIndex.get(prefix)) != null) { + threadsNextIndex.put(prefix, threadsNextIndex.get(prefix) + 1); + } + } + for (WriterDialogue dialogue : nodesById.values()) { + if (dialogue.dialogue_id != null) { + dialogue.dialogue = getProject().getDialogue(dialogue.dialogue_id); + } + if (dialogue.replies == null) continue; + for (WriterReply reply : dialogue.replies) { + if (reply.next_dialogue_id != null) { + if (isSpecial(reply.next_dialogue_id)) { + reply.next_dialogue = getSpecial(reply.next_dialogue_id); + } else { + reply.next_dialogue = nodesById.get(reply.next_dialogue_id); + } + } + //TODO Seriously, this is failure-prone by design. Can't do much better though... + if (dialogue.dialogue != null) { + List linked = new ArrayList(dialogue.dialogue.replies.size()); + if (dialogue.dialogue != null && dialogue.dialogue.replies != null) { + //Try to hook to existing replies... not as easy when there's no ID. + Dialogue.Reply best = null; + int score, maxScore = 0; + for (Dialogue.Reply dReply : dialogue.dialogue.replies) { + //Never link twice to the same... + if (linked.contains(dReply)) continue; + score = 0; + //Arbitrary values... hopefully this gives good results. + //Same target gives good hope of preserving at least the structure. + if (dReply.next_phrase_id != null && dReply.next_phrase_id.equals(reply.next_dialogue_id)) + score += 50; + //Same text is almost as good as an ID, but there may be duplicates due to requirements system... + if (dReply.text != null && dReply.text.equals(reply.text)) score += 40; + //Same slot in the list. That's not so bad if all else fails, and could help sort duplicates with same text. + if (dialogue.dialogue.replies.indexOf(dReply) == dialogue.replies.indexOf(reply)) + score += 20; + //Both have null text. It's not much, but it's something.... + if (dReply.text == null && reply.text == null) score += 10; + if (score > maxScore) { + maxScore = score; + best = dReply; + } + } + if (maxScore > 0) { + reply.reply = best; + linked.add(best); + } + } + } + } + } + for (String rootId : rootsId) { + roots.add(nodesById.get(rootId)); + } + + } + if (this.state == State.linked) { + //Already linked. + return; + } + + this.state = State.linked; + } + + public boolean isSpecial(String id) { + if (id == null) return false; + if (ShopDialogue.id.equals(id)) return true; + if (FightDialogue.id.equals(id)) return true; + if (EndDialogue.id.equals(id)) return true; + if (RemoveNPCDialogue.id.equals(id)) return true; + return false; + } + + public SpecialDialogue getSpecial(String id) { + if (id == null) return null; + if (ShopDialogue.id.equals(id)) return new ShopDialogue(); + if (FightDialogue.id.equals(id)) return new FightDialogue(); + if (EndDialogue.id.equals(id)) return new EndDialogue(); + if (RemoveNPCDialogue.id.equals(id)) return new RemoveNPCDialogue(); + return null; + } + + public List toDialogue() { + Map visited = new LinkedHashMap(); + List created = new ArrayList(); + List modified = new ArrayList(); + begin.toDialogue(visited, created, modified); + for (Dialogue modifiedDialogue : modified) { + modifiedDialogue.childrenChanged(new ArrayList()); + } + return created; + } - public List toDialogue(){ - Map visited = new LinkedHashMap(); - List created = new ArrayList(); - List modified = new ArrayList(); - begin.toDialogue(visited, created, modified); - for (Dialogue modifiedDialogue : modified) { - modifiedDialogue.childrenChanged(new ArrayList()); - } - return created; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeDataSet.java b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeDataSet.java index 39d5625..11ba490 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeDataSet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeDataSet.java @@ -1,274 +1,260 @@ package com.gpl.rpg.atcontentstudio.model.tools.writermode; -import java.awt.Image; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.Serializable; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; - -import javax.swing.tree.TreeNode; - +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; +import com.gpl.rpg.atcontentstudio.model.*; +import com.gpl.rpg.atcontentstudio.model.GameSource.Type; +import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.io.JsonPrettyWriter; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.GameSource.Type; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.SaveEvent; -import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.tree.TreeNode; +import java.awt.*; +import java.io.*; +import java.util.List; +import java.util.*; public class WriterModeDataSet implements ProjectTreeNode, Serializable { - private static final long serialVersionUID = 5434504851883441971L; - public static final String DEFAULT_REL_PATH_IN_PROJECT = "writer.json"; - - - public GameSource parent; - public File writerFile; - - public List writerModeDataList = new ArrayList(); - - public WriterModeDataSet(GameSource gameSource) { - this.parent = gameSource; - writerFile = new File(parent.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); - parse(); - } + private static final long serialVersionUID = 5434504851883441971L; + public static final String DEFAULT_REL_PATH_IN_PROJECT = "writer.json"; - @Override - public TreeNode getChildAt(int childIndex) { - return writerModeDataList.get(childIndex); - } - @Override - public int getChildCount() { - return writerModeDataList.size(); - } + public GameSource parent; + public File writerFile; - @Override - public TreeNode getParent() { - return parent; - } + public List writerModeDataList = new ArrayList(); - @Override - public int getIndex(TreeNode node) { - return writerModeDataList.indexOf(node); - } + public WriterModeDataSet(GameSource gameSource) { + this.parent = gameSource; + writerFile = new File(parent.baseFolder, DEFAULT_REL_PATH_IN_PROJECT); + parse(); + } - @Override - public boolean getAllowsChildren() { - return true; - } + @Override + public TreeNode getChildAt(int childIndex) { + return writerModeDataList.get(childIndex); + } - @Override - public boolean isLeaf() { - return false; - } + @Override + public int getChildCount() { + return writerModeDataList.size(); + } - @SuppressWarnings("rawtypes") - @Override - public Enumeration children() { - return Collections.enumeration(writerModeDataList); - } + @Override + public TreeNode getParent() { + return parent; + } - @Override - public void childrenAdded(List path) { - path.add(0,this); - parent.childrenAdded(path); - } + @Override + public int getIndex(TreeNode node) { + return writerModeDataList.indexOf(node); + } - @Override - public void childrenChanged(List path) { - path.add(0,this); - parent.childrenChanged(path); - } + @Override + public boolean getAllowsChildren() { + return true; + } - @Override - public void childrenRemoved(List path) { - path.add(0,this); - parent.childrenRemoved(path); - } - - @Override - public void notifyCreated() { - childrenAdded(new ArrayList()); - } + @Override + public boolean isLeaf() { + return false; + } - @Override - public String getDesc() { - return (needsSaving() ? "*" : "")+"Dialogue sketches"; - } + @SuppressWarnings("rawtypes") + @Override + public Enumeration children() { + return Collections.enumeration(writerModeDataList); + } - @Override - public Project getProject() { - return parent.getProject(); - } + @Override + public void childrenAdded(List path) { + path.add(0, this); + parent.childrenAdded(path); + } - @Override - public GameDataSet getDataSet() { - return null; - } + @Override + public void childrenChanged(List path) { + path.add(0, this); + parent.childrenChanged(path); + } - @Override - public Image getIcon() { - return DefaultIcons.getStdClosedIcon(); - } + @Override + public void childrenRemoved(List path) { + path.add(0, this); + parent.childrenRemoved(path); + } - @Override - public Image getOpenIcon() { - return DefaultIcons.getStdOpenIcon(); - } + @Override + public void notifyCreated() { + childrenAdded(new ArrayList()); + } - @Override - public Image getClosedIcon() { - return DefaultIcons.getStdClosedIcon(); - } + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + "Dialogue sketches"; + } - @Override - public Image getLeafIcon() { - return null; - } + @Override + public Project getProject() { + return parent.getProject(); + } - @Override - public Type getDataType() { - return parent.getDataType(); - } + @Override + public GameDataSet getDataSet() { + return null; + } - @Override - public boolean isEmpty() { - return writerModeDataList.isEmpty(); - } - - - @SuppressWarnings("rawtypes") - public void save(File jsonFile) { - List dataToSave = new ArrayList(); - for (WriterModeData data : writerModeDataList) { - if (data.jsonFile.equals(jsonFile)) { - dataToSave.add(data.toJson()); - } - } - if (dataToSave.isEmpty() && writerFile.exists()) { - if (writerFile.delete()) { - Notification.addSuccess("File "+writerFile.getAbsolutePath()+" deleted."); - } else { - Notification.addError("Error deleting file "+writerFile.getAbsolutePath()); - } - - return; - } - StringWriter writer = new JsonPrettyWriter(); - try { - JSONArray.writeJSONString(dataToSave, writer); - } catch (IOException e) { - //Impossible with a StringWriter - } - String toWrite = writer.toString(); - try { - FileWriter w = new FileWriter(writerFile); - w.write(toWrite); - w.close(); - for (WriterModeData element : writerModeDataList) { - element.state = GameDataElement.State.saved; - } - Notification.addSuccess("Json file "+writerFile.getAbsolutePath()+" saved."); - } catch (IOException e) { - Notification.addError("Error while writing json file "+writerFile.getAbsolutePath()+" : "+e.getMessage()); - e.printStackTrace(); - } - } - - public List attemptSave() { - List events = new ArrayList(); - for (WriterModeData data : writerModeDataList) { - if (data.needsSaving()) { - events.add(new SaveEvent(SaveEvent.Type.alsoSave, data)); - } - } - return events; - } - - @SuppressWarnings("rawtypes") - public void parse() { - if (!writerFile.exists()) return; - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(writerFile); - List writerDataListJson = (List) parser.parse(reader); - for (Object obj : writerDataListJson) { - Map jsonObj = (Map)obj; - WriterModeData data = new WriterModeData(this, jsonObj); - data.writable = true; - writerModeDataList.add(data); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file "+writerFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file "+writerFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file "+writerFile.getAbsolutePath()+": "+e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } + @Override + public Image getIcon() { + return DefaultIcons.getStdClosedIcon(); + } - public WriterModeData getWriterSketch(String id) { - for (WriterModeData sketch : writerModeDataList) { - if (id.equals(sketch.id)){ - return sketch; - } - } - return null; - } + @Override + public Image getOpenIcon() { + return DefaultIcons.getStdOpenIcon(); + } - public WriterModeData get(int index) { - return writerModeDataList.get(index); - } + @Override + public Image getClosedIcon() { + return DefaultIcons.getStdClosedIcon(); + } - public void add(WriterModeData node) { - ProjectTreeNode higherEmptyParent = this; - while (higherEmptyParent != null) { - if (higherEmptyParent.getParent() != null && ((ProjectTreeNode)higherEmptyParent.getParent()).isEmpty()) higherEmptyParent = (ProjectTreeNode)higherEmptyParent.getParent(); - else break; - } - if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; - writerModeDataList.add(node); - node.writable = true; - if (node.jsonFile == null) node.jsonFile = this.writerFile; - node.parent = this; - if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); - else node.notifyCreated(); - } - + @Override + public Image getLeafIcon() { + return null; + } - @Override - public boolean needsSaving() { - for (ProjectTreeNode node : writerModeDataList) { - if (node.needsSaving()) return true; - } - return false; - } + @Override + public Type getDataType() { + return parent.getDataType(); + } + + @Override + public boolean isEmpty() { + return writerModeDataList.isEmpty(); + } + + + @SuppressWarnings("rawtypes") + public void save(File jsonFile) { + List dataToSave = new ArrayList(); + for (WriterModeData data : writerModeDataList) { + if (data.jsonFile.equals(jsonFile)) { + dataToSave.add(data.toJson()); + } + } + if (dataToSave.isEmpty() && writerFile.exists()) { + if (writerFile.delete()) { + Notification.addSuccess("File " + writerFile.getAbsolutePath() + " deleted."); + } else { + Notification.addError("Error deleting file " + writerFile.getAbsolutePath()); + } + + return; + } + StringWriter writer = new JsonPrettyWriter(); + try { + JSONArray.writeJSONString(dataToSave, writer); + } catch (IOException e) { + //Impossible with a StringWriter + } + String toWrite = writer.toString(); + try { + FileWriter w = new FileWriter(writerFile); + w.write(toWrite); + w.close(); + for (WriterModeData element : writerModeDataList) { + element.state = GameDataElement.State.saved; + } + Notification.addSuccess("Json file " + writerFile.getAbsolutePath() + " saved."); + } catch (IOException e) { + Notification.addError("Error while writing json file " + writerFile.getAbsolutePath() + " : " + e.getMessage()); + e.printStackTrace(); + } + } + + public List attemptSave() { + List events = new ArrayList(); + for (WriterModeData data : writerModeDataList) { + if (data.needsSaving()) { + events.add(new SaveEvent(SaveEvent.Type.alsoSave, data)); + } + } + return events; + } + + @SuppressWarnings("rawtypes") + public void parse() { + if (!writerFile.exists()) return; + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(writerFile); + List writerDataListJson = (List) parser.parse(reader); + for (Object obj : writerDataListJson) { + Map jsonObj = (Map) obj; + WriterModeData data = new WriterModeData(this, jsonObj); + data.writable = true; + writerModeDataList.add(data); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + writerFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + writerFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + writerFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public WriterModeData getWriterSketch(String id) { + for (WriterModeData sketch : writerModeDataList) { + if (id.equals(sketch.id)) { + return sketch; + } + } + return null; + } + + public WriterModeData get(int index) { + return writerModeDataList.get(index); + } + + public void add(WriterModeData node) { + ProjectTreeNode higherEmptyParent = this; + while (higherEmptyParent != null) { + if (higherEmptyParent.getParent() != null && ((ProjectTreeNode) higherEmptyParent.getParent()).isEmpty()) + higherEmptyParent = (ProjectTreeNode) higherEmptyParent.getParent(); + else break; + } + if (higherEmptyParent == this && !this.isEmpty()) higherEmptyParent = null; + writerModeDataList.add(node); + node.writable = true; + if (node.jsonFile == null) node.jsonFile = this.writerFile; + node.parent = this; + if (higherEmptyParent != null) higherEmptyParent.notifyCreated(); + else node.notifyCreated(); + } + + + @Override + public boolean needsSaving() { + for (ProjectTreeNode node : writerModeDataList) { + if (node.needsSaving()) return true; + } + return false; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java index afe584d..aec5e70 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java @@ -1,180 +1,200 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Desktop; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Scanner; - -import javax.swing.ImageIcon; -import javax.swing.JEditorPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.event.HyperlinkEvent; -import javax.swing.event.HyperlinkEvent.EventType; -import javax.swing.event.HyperlinkListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.jidesoft.swing.JideTabbedPane; +import javax.swing.*; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkEvent.EventType; +import javax.swing.event.HyperlinkListener; +import java.awt.*; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Scanner; + public class AboutEditor extends Editor { - private static final long serialVersionUID = 6230549148222457139L; + private static final long serialVersionUID = 6230549148222457139L; - public static final String WELCOME_STRING = - "" + - "" + - "" + - "" + - "" + - "
Welcome to "+ATContentStudio.APP_NAME+" "+ATContentStudio.APP_VERSION+"
" + - "
" + - "This is a content editor for Andor's Trail.
" + - "Right click on the left area or use the \"File\" menu to create a project.
" + - "
" + - "Play Andor's Trail for free on your Android device.
" + - "Visit the official forum to give or receive help.
" + - "Open the project's GitHub project page to check out the game's source code.
" + - "
" + - "For content creation help, make sure to use the following resources:
" + - "The contribution guide on the forums
" + - "The developer section of the Andor's Trail wiki
" + - "The design outline document on Google Drive/Docs
" + - "
" + - "Credits:
" + - "
" + - "Author: Zukero
" + - "Licence: GPL v3
" + - "Sources are included in this package and on GitHub.
" + - "
" + - "Contributors:
" + - "Quentin Delvallet
" + - "Žižkin
" + - "Gonk
" + - "
" + - "This project uses the following libraries:
" + - "JSON.simple by Yidong Fang & Chris Nokleberg.
" + - "License: Apache License 2.0
" + - "
" + - "RSyntaxTextArea by Robert Futrell.
" + - "License: Modified BSD License (a.k.a. 3-Clause BSD)
" + - "
" + - "JIDE Common Layer by JIDE Software.
" + - "License: GPL v2 with classpath exception
" + - "
" + - "A modified version of libtiled-java by Adam Turk & Thorbjorn Lindeijer.
" + - "License: Simplified BSD License (a.k.a 2-Clause BSD)
" + - "Sources of the modified version are included in this package.
" + - "
" + - "Prefuse by the Berkeley Institue of Design.
" + - "License: Modified BSD License (a.k.a 3-Clause BSD)
" + - "
" + - "BeanShell by Pat Niemeyer.
" + - "License: LGPL v3
" + - "
" + - "A slightly modified version of SipHash for Java by Isaac Whitfield.
" + - "License: MIT License
" + - "
" + - "jsoup by Jonathan Hedley
" + - "License: MIT License
" + - "
" + - "A slightly modified version of General PO Parser by Bal�zs T�th
" + - "License: GPL v3
" + - "
" + - "A slightly modified version of Minify.java by Charles Bihis
" + - "License: Douglas Crockford variant of MIT License
" + - "
" + - "See the tabs below to find the full license text for each of these.
" + - "
" + - "The Windows installer was created with:
" + - "NSIS (Nullsoft Scriptable Install System) v2.46" + - "
" + - ""; - - - public static final AboutEditor instance = new AboutEditor(); - @SuppressWarnings("resource") - private AboutEditor() { - this.name="About "+ATContentStudio.APP_NAME; - this.icon = new ImageIcon(DefaultIcons.getMainIconIcon()); - this.target = new GameDataElement(){ - private static final long serialVersionUID = -227480102288529682L; - @Override - public GameDataSet getDataSet() {return null;} - @Override - public String getDesc() {return null;} - @Override - public void parse() {} - @Override - public void link() {} - @Override - public GameDataElement clone() {return null;} - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) {} - @Override - public String getProjectFilename() {return null;} - @Override - public void save() {} - @Override - public List attemptSave() {return null;} - }; - - setLayout(new BorderLayout()); - JideTabbedPane editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); - editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); - editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); - editorTabsHolder.setShowCloseButtonOnTab(false); - add(editorTabsHolder, BorderLayout.CENTER); - - editorTabsHolder.add("Welcome", getInfoPane(WELCOME_STRING, "text/html")); - editorTabsHolder.add("JSON.simple License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JSON.simple.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("RSyntaxTextArea License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/RSyntaxTextArea.License.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("JIDE Common Layer License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JIDE.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("libtiled-java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.libtiled.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("prefuse License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/license-prefuse.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("BeanShell License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.LGPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("SipHash for Java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.siphash-zackehh.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("jsoup License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.jsoup.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("General PO Parser License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.GPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("Minify.java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.minify.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("ATCS License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.GPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - - } - - private JPanel getInfoPane(String content, String mime) { - JEditorPane welcome = new JEditorPane(); - welcome.setContentType(mime); - welcome.setText(content); - welcome.setEditable(false); - welcome.addHyperlinkListener(new HyperlinkListener() { - @Override - public void hyperlinkUpdate(HyperlinkEvent arg0) { - arg0.getEventType(); - if (arg0.getEventType() == EventType.ACTIVATED) { - if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { - try { - Desktop.getDesktop().browse(arg0.getURL().toURI()); - } catch (IOException e) { - e.printStackTrace(); - } catch (URISyntaxException e) { - e.printStackTrace(); - } - } - } - } - }); - JPanel pane = new JPanel(); - pane.setLayout(new BorderLayout()); - pane.add(new JScrollPane(welcome), BorderLayout.CENTER); - return pane; - } - - - @Override - public void targetUpdated() {} + public static final String WELCOME_STRING = + "" + + "" + + "" + + "" + + "" + + "
Welcome to " + ATContentStudio.APP_NAME + " " + ATContentStudio.APP_VERSION + "
" + + "
" + + "This is a content editor for Andor's Trail.
" + + "Right click on the left area or use the \"File\" menu to create a project.
" + + "
" + + "Play Andor's Trail for free on your Android device.
" + + "Visit the official forum to give or receive help.
" + + "Open the project's GitHub project page to check out the game's source code.
" + + "
" + + "For content creation help, make sure to use the following resources:
" + + "The contribution guide on the forums
" + + "The developer section of the Andor's Trail wiki
" + + "The design outline document on Google Drive/Docs
" + + "
" + + "Credits:
" + + "
" + + "Author: Zukero
" + + "Licence: GPL v3
" + + "Sources are included in this package and on GitHub.
" + + "
" + + "Contributors:
" + + "Quentin Delvallet
" + + "Žižkin
" + + "Gonk
" + + "
" + + "This project uses the following libraries:
" + + "JSON.simple by Yidong Fang & Chris Nokleberg.
" + + "License: Apache License 2.0
" + + "
" + + "RSyntaxTextArea by Robert Futrell.
" + + "License: Modified BSD License (a.k.a. 3-Clause BSD)
" + + "
" + + "JIDE Common Layer by JIDE Software.
" + + "License: GPL v2 with classpath exception
" + + "
" + + "A modified version of libtiled-java by Adam Turk & Thorbjorn Lindeijer.
" + + "License: Simplified BSD License (a.k.a 2-Clause BSD)
" + + "Sources of the modified version are included in this package.
" + + "
" + + "Prefuse by the Berkeley Institue of Design.
" + + "License: Modified BSD License (a.k.a 3-Clause BSD)
" + + "
" + + "BeanShell by Pat Niemeyer.
" + + "License: LGPL v3
" + + "
" + + "A slightly modified version of SipHash for Java by Isaac Whitfield.
" + + "License: MIT License
" + + "
" + + "jsoup by Jonathan Hedley
" + + "License: MIT License
" + + "
" + + "A slightly modified version of General PO Parser by Bal�zs T�th
" + + "License: GPL v3
" + + "
" + + "A slightly modified version of Minify.java by Charles Bihis
" + + "License: Douglas Crockford variant of MIT License
" + + "
" + + "See the tabs below to find the full license text for each of these.
" + + "
" + + "The Windows installer was created with:
" + + "NSIS (Nullsoft Scriptable Install System) v2.46" + + "
" + + ""; + + + public static final AboutEditor instance = new AboutEditor(); + + @SuppressWarnings("resource") + private AboutEditor() { + this.name = "About " + ATContentStudio.APP_NAME; + this.icon = new ImageIcon(DefaultIcons.getMainIconIcon()); + this.target = new GameDataElement() { + private static final long serialVersionUID = -227480102288529682L; + + @Override + public GameDataSet getDataSet() { + return null; + } + + @Override + public String getDesc() { + return null; + } + + @Override + public void parse() { + } + + @Override + public void link() { + } + + @Override + public GameDataElement clone() { + return null; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + } + + @Override + public String getProjectFilename() { + return null; + } + + @Override + public void save() { + } + + @Override + public List attemptSave() { + return null; + } + }; + + setLayout(new BorderLayout()); + JideTabbedPane editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); + editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); + editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); + editorTabsHolder.setShowCloseButtonOnTab(false); + add(editorTabsHolder, BorderLayout.CENTER); + + editorTabsHolder.add("Welcome", getInfoPane(WELCOME_STRING, "text/html")); + editorTabsHolder.add("JSON.simple License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JSON.simple.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("RSyntaxTextArea License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/RSyntaxTextArea.License.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("JIDE Common Layer License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JIDE.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("libtiled-java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.libtiled.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("prefuse License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/license-prefuse.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("BeanShell License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.LGPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("SipHash for Java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.siphash-zackehh.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("jsoup License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.jsoup.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("General PO Parser License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.GPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("Minify.java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.minify.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("ATCS License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.GPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + + } + + private JPanel getInfoPane(String content, String mime) { + JEditorPane welcome = new JEditorPane(); + welcome.setContentType(mime); + welcome.setText(content); + welcome.setEditable(false); + welcome.addHyperlinkListener(new HyperlinkListener() { + @Override + public void hyperlinkUpdate(HyperlinkEvent arg0) { + arg0.getEventType(); + if (arg0.getEventType() == EventType.ACTIVATED) { + if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + try { + Desktop.getDesktop().browse(arg0.getURL().toURI()); + } catch (IOException e) { + e.printStackTrace(); + } catch (URISyntaxException e) { + e.printStackTrace(); + } + } + } + } + }); + JPanel pane = new JPanel(); + pane.setLayout(new BorderLayout()); + pane.add(new JScrollPane(welcome), BorderLayout.CENTER); + return pane; + } + + + @Override + public void targetUpdated() { + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/BooleanBasedCheckBox.java b/src/com/gpl/rpg/atcontentstudio/ui/BooleanBasedCheckBox.java index b0bd514..ae3efc5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/BooleanBasedCheckBox.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/BooleanBasedCheckBox.java @@ -1,17 +1,17 @@ package com.gpl.rpg.atcontentstudio.ui; -import javax.swing.JCheckBox; +import javax.swing.*; public class BooleanBasedCheckBox extends JCheckBox { - private static final long serialVersionUID = 3941646360487399554L; - - public Boolean getBooleanValue() { - return isSelected() ? Boolean.TRUE : null; - } - - public void setBooleanValue(Boolean val) { - setSelected(val != null && val); - } + private static final long serialVersionUID = 3941646360487399554L; + + public Boolean getBooleanValue() { + return isSelected() ? Boolean.TRUE : null; + } + + public void setBooleanValue(Boolean val) { + setSelected(val != null && val); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/CollapsiblePanel.java b/src/com/gpl/rpg/atcontentstudio/ui/CollapsiblePanel.java index e19180a..919a5e8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/CollapsiblePanel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/CollapsiblePanel.java @@ -1,160 +1,155 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.ComponentListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; - -import javax.swing.BorderFactory; -import javax.swing.JPanel; +import javax.swing.*; import javax.swing.border.TitledBorder; - -public class CollapsiblePanel extends JPanel { - - private static final long serialVersionUID = 319384990345722150L; - - String title; - TitledBorder border; - +import java.awt.*; +import java.awt.event.*; + +public class CollapsiblePanel extends JPanel { + + private static final long serialVersionUID = 319384990345722150L; + + String title; + TitledBorder border; + public CollapsiblePanel(String title) { - super(); - this.title = title; - border = BorderFactory.createTitledBorder(title); - setBorder(border); - BorderLayout borderLayout = new BorderLayout(); - setLayout(borderLayout); - addMouseListener(mouseListener); - } - - MouseListener mouseListener = new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - toggleVisibility(); - } - }; - - ComponentListener contentComponentListener = new ComponentAdapter() { - @Override - public void componentShown(ComponentEvent e) { - updateBorderTitle(); - } - @Override - public void componentHidden(ComponentEvent e) { - updateBorderTitle(); - } - }; - - public String getTitle() { - return title; - } - + super(); + this.title = title; + border = BorderFactory.createTitledBorder(title); + setBorder(border); + BorderLayout borderLayout = new BorderLayout(); + setLayout(borderLayout); + addMouseListener(mouseListener); + } + + MouseListener mouseListener = new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + toggleVisibility(); + } + }; + + ComponentListener contentComponentListener = new ComponentAdapter() { + @Override + public void componentShown(ComponentEvent e) { + updateBorderTitle(); + } + + @Override + public void componentHidden(ComponentEvent e) { + updateBorderTitle(); + } + }; + + public String getTitle() { + return title; + } + public void setTitle(String title) { - String oldTitle = this.title; - this.title = title; + String oldTitle = this.title; + this.title = title; firePropertyChange("title", oldTitle, this.title); updateBorderTitle(); - } - - @Override - public Component add(Component comp) { - comp.addComponentListener(contentComponentListener); - Component r = super.add(comp); - updateBorderTitle(); - return r; - } - - @Override - public Component add(String name, Component comp) { - comp.addComponentListener(contentComponentListener); - Component r = super.add(name, comp); - updateBorderTitle(); - return r; - } - - @Override - public Component add(Component comp, int index) { - comp.addComponentListener(contentComponentListener); - Component r = super.add(comp, index); - updateBorderTitle(); - return r; - } - - @Override - public void add(Component comp, Object constraints) { - comp.addComponentListener(contentComponentListener); - super.add(comp, constraints); - updateBorderTitle(); - } - - @Override - public void add(Component comp, Object constraints, int index) { - comp.addComponentListener(contentComponentListener); - super.add(comp, constraints, index); - updateBorderTitle(); - } - - @Override - public void remove(int index) { - Component comp = getComponent(index); - comp.removeComponentListener(contentComponentListener); - super.remove(index); - } - - @Override - public void remove(Component comp) { - comp.removeComponentListener(contentComponentListener); - super.remove(comp); - } - - @Override - public void removeAll() { - for (Component c : getComponents()) { - c.removeComponentListener(contentComponentListener); - } - super.removeAll(); - } - - protected void toggleVisibility() { - toggleVisibility(hasInvisibleComponent()); - } - - protected void toggleVisibility(boolean visible) { - for (Component c : getComponents()) { - c.setVisible(visible); - } - updateBorderTitle(); - } - - protected void updateBorderTitle() { - String arrow = ""; - if (getComponentCount() > 0) { - arrow = (hasInvisibleComponent()?"[+] ":"[-] "); - } - border.setTitle(arrow+title); - repaint(); - } - - protected final boolean hasInvisibleComponent() { - for (Component c : getComponents()) { - if (!c.isVisible()) { - return true; - } - } - return false; - } - + } + + @Override + public Component add(Component comp) { + comp.addComponentListener(contentComponentListener); + Component r = super.add(comp); + updateBorderTitle(); + return r; + } + + @Override + public Component add(String name, Component comp) { + comp.addComponentListener(contentComponentListener); + Component r = super.add(name, comp); + updateBorderTitle(); + return r; + } + + @Override + public Component add(Component comp, int index) { + comp.addComponentListener(contentComponentListener); + Component r = super.add(comp, index); + updateBorderTitle(); + return r; + } + + @Override + public void add(Component comp, Object constraints) { + comp.addComponentListener(contentComponentListener); + super.add(comp, constraints); + updateBorderTitle(); + } + + @Override + public void add(Component comp, Object constraints, int index) { + comp.addComponentListener(contentComponentListener); + super.add(comp, constraints, index); + updateBorderTitle(); + } + + @Override + public void remove(int index) { + Component comp = getComponent(index); + comp.removeComponentListener(contentComponentListener); + super.remove(index); + } + + @Override + public void remove(Component comp) { + comp.removeComponentListener(contentComponentListener); + super.remove(comp); + } + + @Override + public void removeAll() { + for (Component c : getComponents()) { + c.removeComponentListener(contentComponentListener); + } + super.removeAll(); + } + + protected void toggleVisibility() { + toggleVisibility(hasInvisibleComponent()); + } + + protected void toggleVisibility(boolean visible) { + for (Component c : getComponents()) { + c.setVisible(visible); + } + updateBorderTitle(); + } + + protected void updateBorderTitle() { + String arrow = ""; + if (getComponentCount() > 0) { + arrow = (hasInvisibleComponent() ? "[+] " : "[-] "); + } + border.setTitle(arrow + title); + repaint(); + } + + protected final boolean hasInvisibleComponent() { + for (Component c : getComponents()) { + if (!c.isVisible()) { + return true; + } + } + return false; + } + public void collapse() { - toggleVisibility(false); + toggleVisibility(false); } + public void expand() { - toggleVisibility(true); + toggleVisibility(true); } + public void setExpanded(boolean expand) { - toggleVisibility(expand); + toggleVisibility(expand); } - + } \ No newline at end of file diff --git a/src/com/gpl/rpg/atcontentstudio/ui/DefaultIcons.java b/src/com/gpl/rpg/atcontentstudio/ui/DefaultIcons.java index 0bee0df..ab91ad4 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/DefaultIcons.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/DefaultIcons.java @@ -1,324 +1,749 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.Image; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.imageio.ImageIO; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; +import javax.imageio.ImageIO; +import java.awt.*; +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + public class DefaultIcons { - private static Map imageCache = new LinkedHashMap(); - private static Map iconCache = new LinkedHashMap(); + private static Map imageCache = new LinkedHashMap(); + private static Map iconCache = new LinkedHashMap(); - - private static String MAIN_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/andorstrainer.png"; - public static Image getMainIconImage() { return getImage(MAIN_ICON_RES); } - public static Image getMainIconIcon() { return getIcon(MAIN_ICON_RES); } - - private static String FOLDER_STD_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_closed.png"; - public static Image getStdClosedImage() { return getImage(FOLDER_STD_CLOSED_RES); } - public static Image getStdClosedIcon() { return getIcon(FOLDER_STD_CLOSED_RES); } - private static String FOLDER_STD_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_open.png"; - public static Image getStdOpenImage() { return getImage(FOLDER_STD_OPEN_RES); } - public static Image getStdOpenIcon() { return getIcon(FOLDER_STD_OPEN_RES); } + private static String MAIN_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/andorstrainer.png"; - private static String FOLDER_JSON_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_closed.png"; - public static Image getJsonClosedImage() { return getImage(FOLDER_JSON_CLOSED_RES); } - public static Image getJsonClosedIcon() { return getIcon(FOLDER_JSON_CLOSED_RES); } + public static Image getMainIconImage() { + return getImage(MAIN_ICON_RES); + } - private static String FOLDER_JSON_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_open.png"; - public static Image getJsonOpenImage() { return getImage(FOLDER_JSON_OPEN_RES); } - public static Image getJsonOpenIcon() { return getIcon(FOLDER_JSON_OPEN_RES); } + public static Image getMainIconIcon() { + return getIcon(MAIN_ICON_RES); + } - private static String FOLDER_SAV_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_closed.png"; - public static Image getSavClosedImage() { return getImage(FOLDER_SAV_CLOSED_RES); } - public static Image getSavClosedIcon() { return getIcon(FOLDER_SAV_CLOSED_RES); } + private static String FOLDER_STD_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_closed.png"; - private static String FOLDER_SAV_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_open.png"; - public static Image getSavOpenImage() { return getImage(FOLDER_SAV_OPEN_RES); } - public static Image getSavOpenIcon() { return getIcon(FOLDER_SAV_OPEN_RES); } + public static Image getStdClosedImage() { + return getImage(FOLDER_STD_CLOSED_RES); + } - private static String FOLDER_SPRITE_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_closed.png"; - public static Image getSpriteClosedImage() { return getImage(FOLDER_SPRITE_CLOSED_RES); } - public static Image getSpriteClosedIcon() { return getIcon(FOLDER_SPRITE_CLOSED_RES); } + public static Image getStdClosedIcon() { + return getIcon(FOLDER_STD_CLOSED_RES); + } - private static String FOLDER_SPRITE_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_open.png"; - public static Image getSpriteOpenImage() { return getImage(FOLDER_SPRITE_OPEN_RES); } - public static Image getSpriteOpenIcon() { return getIcon(FOLDER_SPRITE_OPEN_RES); } + private static String FOLDER_STD_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_std_open.png"; - private static String FOLDER_TMX_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_closed.png"; - public static Image getTmxClosedImage() { return getImage(FOLDER_TMX_CLOSED_RES); } - public static Image getTmxClosedIcon() { return getIcon(FOLDER_TMX_CLOSED_RES); } + public static Image getStdOpenImage() { + return getImage(FOLDER_STD_OPEN_RES); + } - private static String FOLDER_TMX_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_open.png"; - public static Image getTmxOpenImage() { return getImage(FOLDER_TMX_OPEN_RES); } - public static Image getTmxOpenIcon() { return getIcon(FOLDER_TMX_OPEN_RES); } + public static Image getStdOpenIcon() { + return getIcon(FOLDER_STD_OPEN_RES); + } - private static String FOLDER_MAP_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_closed.png"; - public static Image getMapClosedImage() { return getImage(FOLDER_MAP_CLOSED_RES); } - public static Image getMapClosedIcon() { return getIcon(FOLDER_MAP_CLOSED_RES); } + private static String FOLDER_JSON_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_closed.png"; - private static String FOLDER_MAP_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_open.png"; - public static Image getMapOpenImage() { return getImage(FOLDER_MAP_OPEN_RES); } - public static Image getMapOpenIcon() { return getIcon(FOLDER_MAP_OPEN_RES); } + public static Image getJsonClosedImage() { + return getImage(FOLDER_JSON_CLOSED_RES); + } - private static String FOLDER_AT_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_closed.png"; - public static Image getATClosedImage() { return getImage(FOLDER_AT_CLOSED_RES); } - public static Image getATClosedIcon() { return getIcon(FOLDER_AT_CLOSED_RES); } + public static Image getJsonClosedIcon() { + return getIcon(FOLDER_JSON_CLOSED_RES); + } - private static String FOLDER_AT_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_open.png"; - public static Image getATOpenImage() { return getImage(FOLDER_AT_OPEN_RES); } - public static Image getATOpenIcon() { return getIcon(FOLDER_AT_OPEN_RES); } - - private static String FOLDER_BOOKMARK_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_closed.png"; - public static Image getBookmarkClosedImage() { return getImage(FOLDER_BOOKMARK_CLOSED_RES); } - public static Image getBookmarkClosedIcon() { return getIcon(FOLDER_BOOKMARK_CLOSED_RES); } + private static String FOLDER_JSON_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_json_open.png"; - private static String FOLDER_BOOKMARK_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_open.png"; - public static Image getBookmarkOpenImage() { return getImage(FOLDER_BOOKMARK_OPEN_RES); } - public static Image getBookmarkOpenIcon() { return getIcon(FOLDER_BOOKMARK_OPEN_RES); } + public static Image getJsonOpenImage() { + return getImage(FOLDER_JSON_OPEN_RES); + } - private static String TILED_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/tiled-icon.png"; - public static Image getTiledIconImage() { return getImage(TILED_ICON_RES); } - public static Image getTiledIconIcon() { return getIcon(TILED_ICON_RES); } + public static Image getJsonOpenIcon() { + return getIcon(FOLDER_JSON_OPEN_RES); + } - private static String UI_MAP_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_map.png"; - public static Image getUIMapImage() { return getImage(UI_MAP_RES); } - public static Image getUIMapIcon() { return getIcon(UI_MAP_RES); } + private static String FOLDER_SAV_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_closed.png"; - private static String HERO_RES = "/com/gpl/rpg/atcontentstudio/img/char_hero.png"; - public static Image getHeroImage() { return getImage(HERO_RES); } - public static Image getHeroIcon() { return getIcon(HERO_RES); } - - private static String TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/tile_layer.png"; - public static Image getTileLayerImage() { return getImage(TILE_LAYER_RES); } - public static Image getTileLayerIcon() { return getIcon(TILE_LAYER_RES); } - - private static String OBJECT_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/object_layer.png"; - public static Image getObjectLayerImage() { return getImage(OBJECT_LAYER_RES); } - public static Image getObjectLayerIcon() { return getIcon(OBJECT_LAYER_RES); } - - private static String ACTOR_CONDITION_RES = "/com/gpl/rpg/atcontentstudio/img/actor_condition.png"; - public static Image getActorConditionImage() { return getImage(ACTOR_CONDITION_RES); } - public static Image getActorConditionIcon() { return getIcon(ACTOR_CONDITION_RES); } - - private static String ITEM_RES = "/com/gpl/rpg/atcontentstudio/img/item.png"; - public static Image getItemImage() { return getImage(ITEM_RES); } - public static Image getItemIcon() { return getIcon(ITEM_RES); } - - private static String NPC_RES = "/com/gpl/rpg/atcontentstudio/img/npc.png"; - public static Image getNPCImage() { return getImage(NPC_RES); } - public static Image getNPCIcon() { return getIcon(NPC_RES); } - - private static String BONEMEAL_RES = "/com/gpl/rpg/atcontentstudio/img/bonemeal.png"; - public static Image getBonemealImage() { return getImage(BONEMEAL_RES); } - public static Image getBonemealIcon() { return getIcon(BONEMEAL_RES); } - - private static String NPC_CLOSE_RES = "/com/gpl/rpg/atcontentstudio/img/npc_close.png"; - public static Image getNPCCloseImage() { return getImage(NPC_CLOSE_RES); } - public static Image getNPCCloseIcon() { return getIcon(NPC_CLOSE_RES); } - - private static String DIALOGUE_RES = "/com/gpl/rpg/atcontentstudio/img/dialogue.png"; - public static Image getDialogueImage() { return getImage(DIALOGUE_RES); } - public static Image getDialogueIcon() { return getIcon(DIALOGUE_RES); } - - private static String QUEST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_quest.png"; - public static Image getQuestImage() { return getImage(QUEST_RES); } - public static Image getQuestIcon() { return getIcon(QUEST_RES); } - - private static String DROPLIST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_equipment.png"; - public static Image getDroplistImage() { return getImage(DROPLIST_RES); } - public static Image getDroplistIcon() { return getIcon(DROPLIST_RES); } - - private static String COMBAT_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_combat.png"; - public static Image getCombatImage() { return getImage(COMBAT_RES); } - public static Image getCombatIcon() { return getIcon(COMBAT_RES); } + public static Image getSavClosedImage() { + return getImage(FOLDER_SAV_CLOSED_RES); + } - private static String GOLD_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_coins.png"; - public static Image getGoldImage() { return getImage(GOLD_RES); } - public static Image getGoldIcon() { return getIcon(GOLD_RES); } + public static Image getSavClosedIcon() { + return getIcon(FOLDER_SAV_CLOSED_RES); + } - private static String SKILL_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_skill.png"; - public static Image getSkillImage() { return getImage(SKILL_RES); } - public static Image getSkillIcon() { return getIcon(SKILL_RES); } + private static String FOLDER_SAV_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sav_open.png"; - private static String IMMUNITY_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_immunity.png"; - public static Image getImmunityImage() { return getImage(IMMUNITY_RES); } - public static Image getImmunityIcon() { return getIcon(IMMUNITY_RES); } - - private static String ITEM_CATEGORY_RES = "/com/gpl/rpg/atcontentstudio/img/equip_weapon.png"; - public static Image getItemCategoryImage() { return getImage(ITEM_CATEGORY_RES); } - public static Image getItemCategoryIcon() { return getIcon(ITEM_CATEGORY_RES); } - - private static String NULLIFY_RES = "/com/gpl/rpg/atcontentstudio/img/nullify.png"; - public static Image getNullifyImage() { return getImage(NULLIFY_RES); } - public static Image getNullifyIcon() { return getIcon(NULLIFY_RES); } - - private static String CREATE_RES = "/com/gpl/rpg/atcontentstudio/img/file_create.png"; - public static Image getCreateImage() { return getImage(CREATE_RES); } - public static Image getCreateIcon() { return getIcon(CREATE_RES); } - - private static String ARROW_UP_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_up.png"; - public static Image getArrowUpImage() { return getImage(ARROW_UP_RES); } - public static Image getArrowUpIcon() { return getIcon(ARROW_UP_RES); } + public static Image getSavOpenImage() { + return getImage(FOLDER_SAV_OPEN_RES); + } - private static String ARROW_DOWN_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_down.png"; - public static Image getArrowDownImage() { return getImage(ARROW_DOWN_RES); } - public static Image getArrowDownIcon() { return getIcon(ARROW_DOWN_RES); } + public static Image getSavOpenIcon() { + return getIcon(FOLDER_SAV_OPEN_RES); + } - private static String ARROW_LEFT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_left.png"; - public static Image getArrowLeftImage() { return getImage(ARROW_LEFT_RES); } - public static Image getArrowLeftIcon() { return getIcon(ARROW_LEFT_RES); } + private static String FOLDER_SPRITE_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_closed.png"; - private static String ARROW_RIGHT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_right.png"; - public static Image getArrowRightImage() { return getImage(ARROW_RIGHT_RES); } - public static Image getArrowRightIcon() { return getIcon(ARROW_RIGHT_RES); } - - private static String CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/container.png"; - public static Image getContainerImage() { return getImage(CONTAINER_RES); } - public static Image getContainerIcon() { return getIcon(CONTAINER_RES); } - - private static String KEY_RES = "/com/gpl/rpg/atcontentstudio/img/key.png"; - public static Image getKeyImage() { return getImage(KEY_RES); } - public static Image getKeyIcon() { return getIcon(KEY_RES); } - - private static String MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/mapchange.png"; - public static Image getMapchangeImage() { return getImage(MAPCHANGE_RES); } - public static Image getMapchangeIcon() { return getIcon(MAPCHANGE_RES); } - - private static String REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/replace.png"; - public static Image getReplaceImage() { return getImage(REPLACE_RES); } - public static Image getReplaceIcon() { return getIcon(REPLACE_RES); } - - private static String REST_RES = "/com/gpl/rpg/atcontentstudio/img/rest.png"; - public static Image getRestImage() { return getImage(REST_RES); } - public static Image getRestIcon() { return getIcon(REST_RES); } - - private static String SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/script.png"; - public static Image getScriptImage() { return getImage(SCRIPT_RES); } - public static Image getScriptIcon() { return getIcon(SCRIPT_RES); } - - private static String SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/sign.png"; - public static Image getSignImage() { return getImage(SIGN_RES); } - public static Image getSignIcon() { return getIcon(SIGN_RES); } - - private static String CREATE_CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/create_container.png"; - public static Image getCreateContainerImage() { return getImage(CREATE_CONTAINER_RES); } - public static Image getCreateContainerIcon() { return getIcon(CREATE_CONTAINER_RES); } - - private static String CREATE_KEY_RES = "/com/gpl/rpg/atcontentstudio/img/create_key.png"; - public static Image getCreateKeyImage() { return getImage(CREATE_KEY_RES); } - public static Image getCreateKeyIcon() { return getIcon(CREATE_KEY_RES); } - - private static String CREATE_REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/create_replace.png"; - public static Image getCreateReplaceImage() { return getImage(CREATE_REPLACE_RES); } - public static Image getCreateReplaceIcon() { return getIcon(CREATE_REPLACE_RES); } + public static Image getSpriteClosedImage() { + return getImage(FOLDER_SPRITE_CLOSED_RES); + } - private static String CREATE_REST_RES = "/com/gpl/rpg/atcontentstudio/img/create_rest.png"; - public static Image getCreateRestImage() { return getImage(CREATE_REST_RES); } - public static Image getCreateRestIcon() { return getIcon(CREATE_REST_RES); } + public static Image getSpriteClosedIcon() { + return getIcon(FOLDER_SPRITE_CLOSED_RES); + } - private static String CREATE_SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/create_script.png"; - public static Image getCreateScriptImage() { return getImage(CREATE_SCRIPT_RES); } - public static Image getCreateScriptIcon() { return getIcon(CREATE_SCRIPT_RES); } + private static String FOLDER_SPRITE_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_sprite_open.png"; - private static String CREATE_SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/create_sign.png"; - public static Image getCreateSignImage() { return getImage(CREATE_SIGN_RES); } - public static Image getCreateSignIcon() { return getIcon(CREATE_SIGN_RES); } - - private static String CREATE_SPAWNAREA_RES = "/com/gpl/rpg/atcontentstudio/img/create_spawnarea.png"; - public static Image getCreateSpawnareaImage() { return getImage(CREATE_SPAWNAREA_RES); } - public static Image getCreateSpawnareaIcon() { return getIcon(CREATE_SPAWNAREA_RES); } + public static Image getSpriteOpenImage() { + return getImage(FOLDER_SPRITE_OPEN_RES); + } - private static String CREATE_MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/create_tiled.png"; - public static Image getCreateMapchangeImage() { return getImage(CREATE_MAPCHANGE_RES); } - public static Image getCreateMapchangeIcon() { return getIcon(CREATE_MAPCHANGE_RES); } - - private static String CREATE_OBJECT_GROUP_RES = "/com/gpl/rpg/atcontentstudio/img/create_object_group.png"; - public static Image getCreateObjectGroupImage() { return getImage(CREATE_OBJECT_GROUP_RES); } - public static Image getCreateObjectGroupIcon() { return getIcon(CREATE_OBJECT_GROUP_RES); } + public static Image getSpriteOpenIcon() { + return getIcon(FOLDER_SPRITE_OPEN_RES); + } - private static String CREATE_TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/create_tile_layer.png"; - public static Image getCreateTileLayerImage() { return getImage(CREATE_TILE_LAYER_RES); } - public static Image getCreateTileLayerIcon() { return getIcon(CREATE_TILE_LAYER_RES); } + private static String FOLDER_TMX_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_closed.png"; - private static String LABEL_RES = "/com/gpl/rpg/atcontentstudio/img/label.png"; - public static Image getLabelImage() { return getImage(LABEL_RES); } - public static Image getLabelIcon() { return getIcon(LABEL_RES); } + public static Image getTmxClosedImage() { + return getImage(FOLDER_TMX_CLOSED_RES); + } - private static String ZOOM_RES = "/com/gpl/rpg/atcontentstudio/img/zoom.png"; - public static Image getZoomImage() { return getImage(ZOOM_RES); } - public static Image getZoomIcon() { return getIcon(ZOOM_RES); } - - private static String TIMER_RES = "/com/gpl/rpg/atcontentstudio/img/timer.png"; - public static Image getTimerImage() { return getImage(TIMER_RES); } - public static Image getTimerIcon() { return getIcon(TIMER_RES); } - - private static String DATE_RES = "/com/gpl/rpg/atcontentstudio/img/date.png"; - public static Image getDateImage() { return getImage(DATE_RES); } - public static Image getDateIcon() { return getIcon(DATE_RES); } - - private static String TIME_RES = "/com/gpl/rpg/atcontentstudio/img/date.png"; - public static Image getTimeImage() { return getImage(TIME_RES); } - public static Image getTimeIcon() { return getIcon(TIME_RES); } - - private static String ALIGNMENT_RES = "/com/gpl/rpg/atcontentstudio/img/alignment.png"; - public static Image getAlignmentImage() { return getImage(ALIGNMENT_RES); } - public static Image getAlignmentIcon() { return getIcon(ALIGNMENT_RES); } - - private static String STATUS_RED_RES = "/com/gpl/rpg/atcontentstudio/img/status_red.png"; - public static Image getStatusRedImage() { return getImage(STATUS_RED_RES); } - public static Image getStatusRedIcon() { return getIcon(STATUS_RED_RES); } - - private static String STATUS_ORANGE_RES = "/com/gpl/rpg/atcontentstudio/img/status_orange.png"; - public static Image getStatusOrangeImage() { return getImage(STATUS_ORANGE_RES); } - public static Image getStatusOrangeIcon() { return getIcon(STATUS_ORANGE_RES); } - - private static String STATUS_GREEN_RES = "/com/gpl/rpg/atcontentstudio/img/status_green.png"; - public static Image getStatusGreenImage() { return getImage(STATUS_GREEN_RES); } - public static Image getStatusGreenIcon() { return getIcon(STATUS_GREEN_RES); } - - private static String STATUS_BLUE_RES = "/com/gpl/rpg/atcontentstudio/img/status_blue.png"; - public static Image getStatusBlueImage() { return getImage(STATUS_BLUE_RES); } - public static Image getStatusBlueIcon() { return getIcon(STATUS_BLUE_RES); } - - private static String STATUS_UNKNOWN_RES = "/com/gpl/rpg/atcontentstudio/img/status_unknown.png"; - public static Image getStatusUnknownImage() { return getImage(STATUS_UNKNOWN_RES); } - public static Image getStatusUnknownIcon() { return getIcon(STATUS_UNKNOWN_RES); } - - private static String BOOKMARK_INACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_inactive.png"; - public static Image getBookmarkInactiveImage() { return getImage(BOOKMARK_INACTIVE); } - public static Image getBookmarkInactiveIcon() { return getIcon(BOOKMARK_INACTIVE); } - - private static String BOOKMARK_ACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_active.png"; - public static Image getBookmarkActiveImage() { return getImage(BOOKMARK_ACTIVE); } - public static Image getBookmarkActiveIcon() { return getIcon(BOOKMARK_ACTIVE); } - - - private static Image getImage(String res) { - if (imageCache.get(res) == null) { - try { - Image img = ImageIO.read(DefaultIcons.class.getResourceAsStream(res)); - imageCache.put(res, img); - } catch (IOException e) { - Notification.addError("Failed to load image "+res); - e.printStackTrace(); - } - } - return imageCache.get(res); - } - - private static Image getIcon(String res) { - if (iconCache.get(res) == null) { - Image icon = getImage(res).getScaledInstance((int)(16*ATContentStudio.SCALING), (int)(16*ATContentStudio.SCALING), Image.SCALE_SMOOTH); - iconCache.put(res, icon); - } - return iconCache.get(res); - } + public static Image getTmxClosedIcon() { + return getIcon(FOLDER_TMX_CLOSED_RES); + } + + private static String FOLDER_TMX_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_tmx_open.png"; + + public static Image getTmxOpenImage() { + return getImage(FOLDER_TMX_OPEN_RES); + } + + public static Image getTmxOpenIcon() { + return getIcon(FOLDER_TMX_OPEN_RES); + } + + private static String FOLDER_MAP_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_closed.png"; + + public static Image getMapClosedImage() { + return getImage(FOLDER_MAP_CLOSED_RES); + } + + public static Image getMapClosedIcon() { + return getIcon(FOLDER_MAP_CLOSED_RES); + } + + private static String FOLDER_MAP_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_map_open.png"; + + public static Image getMapOpenImage() { + return getImage(FOLDER_MAP_OPEN_RES); + } + + public static Image getMapOpenIcon() { + return getIcon(FOLDER_MAP_OPEN_RES); + } + + private static String FOLDER_AT_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_closed.png"; + + public static Image getATClosedImage() { + return getImage(FOLDER_AT_CLOSED_RES); + } + + public static Image getATClosedIcon() { + return getIcon(FOLDER_AT_CLOSED_RES); + } + + private static String FOLDER_AT_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_at_open.png"; + + public static Image getATOpenImage() { + return getImage(FOLDER_AT_OPEN_RES); + } + + public static Image getATOpenIcon() { + return getIcon(FOLDER_AT_OPEN_RES); + } + + private static String FOLDER_BOOKMARK_CLOSED_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_closed.png"; + + public static Image getBookmarkClosedImage() { + return getImage(FOLDER_BOOKMARK_CLOSED_RES); + } + + public static Image getBookmarkClosedIcon() { + return getIcon(FOLDER_BOOKMARK_CLOSED_RES); + } + + private static String FOLDER_BOOKMARK_OPEN_RES = "/com/gpl/rpg/atcontentstudio/img/folder_bookmark_open.png"; + + public static Image getBookmarkOpenImage() { + return getImage(FOLDER_BOOKMARK_OPEN_RES); + } + + public static Image getBookmarkOpenIcon() { + return getIcon(FOLDER_BOOKMARK_OPEN_RES); + } + + private static String TILED_ICON_RES = "/com/gpl/rpg/atcontentstudio/img/tiled-icon.png"; + + public static Image getTiledIconImage() { + return getImage(TILED_ICON_RES); + } + + public static Image getTiledIconIcon() { + return getIcon(TILED_ICON_RES); + } + + private static String UI_MAP_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_map.png"; + + public static Image getUIMapImage() { + return getImage(UI_MAP_RES); + } + + public static Image getUIMapIcon() { + return getIcon(UI_MAP_RES); + } + + private static String HERO_RES = "/com/gpl/rpg/atcontentstudio/img/char_hero.png"; + + public static Image getHeroImage() { + return getImage(HERO_RES); + } + + public static Image getHeroIcon() { + return getIcon(HERO_RES); + } + + private static String TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/tile_layer.png"; + + public static Image getTileLayerImage() { + return getImage(TILE_LAYER_RES); + } + + public static Image getTileLayerIcon() { + return getIcon(TILE_LAYER_RES); + } + + private static String OBJECT_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/object_layer.png"; + + public static Image getObjectLayerImage() { + return getImage(OBJECT_LAYER_RES); + } + + public static Image getObjectLayerIcon() { + return getIcon(OBJECT_LAYER_RES); + } + + private static String ACTOR_CONDITION_RES = "/com/gpl/rpg/atcontentstudio/img/actor_condition.png"; + + public static Image getActorConditionImage() { + return getImage(ACTOR_CONDITION_RES); + } + + public static Image getActorConditionIcon() { + return getIcon(ACTOR_CONDITION_RES); + } + + private static String ITEM_RES = "/com/gpl/rpg/atcontentstudio/img/item.png"; + + public static Image getItemImage() { + return getImage(ITEM_RES); + } + + public static Image getItemIcon() { + return getIcon(ITEM_RES); + } + + private static String NPC_RES = "/com/gpl/rpg/atcontentstudio/img/npc.png"; + + public static Image getNPCImage() { + return getImage(NPC_RES); + } + + public static Image getNPCIcon() { + return getIcon(NPC_RES); + } + + private static String BONEMEAL_RES = "/com/gpl/rpg/atcontentstudio/img/bonemeal.png"; + + public static Image getBonemealImage() { + return getImage(BONEMEAL_RES); + } + + public static Image getBonemealIcon() { + return getIcon(BONEMEAL_RES); + } + + private static String NPC_CLOSE_RES = "/com/gpl/rpg/atcontentstudio/img/npc_close.png"; + + public static Image getNPCCloseImage() { + return getImage(NPC_CLOSE_RES); + } + + public static Image getNPCCloseIcon() { + return getIcon(NPC_CLOSE_RES); + } + + private static String DIALOGUE_RES = "/com/gpl/rpg/atcontentstudio/img/dialogue.png"; + + public static Image getDialogueImage() { + return getImage(DIALOGUE_RES); + } + + public static Image getDialogueIcon() { + return getIcon(DIALOGUE_RES); + } + + private static String QUEST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_quest.png"; + + public static Image getQuestImage() { + return getImage(QUEST_RES); + } + + public static Image getQuestIcon() { + return getIcon(QUEST_RES); + } + + private static String DROPLIST_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_equipment.png"; + + public static Image getDroplistImage() { + return getImage(DROPLIST_RES); + } + + public static Image getDroplistIcon() { + return getIcon(DROPLIST_RES); + } + + private static String COMBAT_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_combat.png"; + + public static Image getCombatImage() { + return getImage(COMBAT_RES); + } + + public static Image getCombatIcon() { + return getIcon(COMBAT_RES); + } + + private static String GOLD_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_coins.png"; + + public static Image getGoldImage() { + return getImage(GOLD_RES); + } + + public static Image getGoldIcon() { + return getIcon(GOLD_RES); + } + + private static String SKILL_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_skill.png"; + + public static Image getSkillImage() { + return getImage(SKILL_RES); + } + + public static Image getSkillIcon() { + return getIcon(SKILL_RES); + } + + private static String IMMUNITY_RES = "/com/gpl/rpg/atcontentstudio/img/ui_icon_immunity.png"; + + public static Image getImmunityImage() { + return getImage(IMMUNITY_RES); + } + + public static Image getImmunityIcon() { + return getIcon(IMMUNITY_RES); + } + + private static String ITEM_CATEGORY_RES = "/com/gpl/rpg/atcontentstudio/img/equip_weapon.png"; + + public static Image getItemCategoryImage() { + return getImage(ITEM_CATEGORY_RES); + } + + public static Image getItemCategoryIcon() { + return getIcon(ITEM_CATEGORY_RES); + } + + private static String NULLIFY_RES = "/com/gpl/rpg/atcontentstudio/img/nullify.png"; + + public static Image getNullifyImage() { + return getImage(NULLIFY_RES); + } + + public static Image getNullifyIcon() { + return getIcon(NULLIFY_RES); + } + + private static String CREATE_RES = "/com/gpl/rpg/atcontentstudio/img/file_create.png"; + + public static Image getCreateImage() { + return getImage(CREATE_RES); + } + + public static Image getCreateIcon() { + return getIcon(CREATE_RES); + } + + private static String ARROW_UP_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_up.png"; + + public static Image getArrowUpImage() { + return getImage(ARROW_UP_RES); + } + + public static Image getArrowUpIcon() { + return getIcon(ARROW_UP_RES); + } + + private static String ARROW_DOWN_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_down.png"; + + public static Image getArrowDownImage() { + return getImage(ARROW_DOWN_RES); + } + + public static Image getArrowDownIcon() { + return getIcon(ARROW_DOWN_RES); + } + + private static String ARROW_LEFT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_left.png"; + + public static Image getArrowLeftImage() { + return getImage(ARROW_LEFT_RES); + } + + public static Image getArrowLeftIcon() { + return getIcon(ARROW_LEFT_RES); + } + + private static String ARROW_RIGHT_RES = "/com/gpl/rpg/atcontentstudio/img/arrow_right.png"; + + public static Image getArrowRightImage() { + return getImage(ARROW_RIGHT_RES); + } + + public static Image getArrowRightIcon() { + return getIcon(ARROW_RIGHT_RES); + } + + private static String CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/container.png"; + + public static Image getContainerImage() { + return getImage(CONTAINER_RES); + } + + public static Image getContainerIcon() { + return getIcon(CONTAINER_RES); + } + + private static String KEY_RES = "/com/gpl/rpg/atcontentstudio/img/key.png"; + + public static Image getKeyImage() { + return getImage(KEY_RES); + } + + public static Image getKeyIcon() { + return getIcon(KEY_RES); + } + + private static String MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/mapchange.png"; + + public static Image getMapchangeImage() { + return getImage(MAPCHANGE_RES); + } + + public static Image getMapchangeIcon() { + return getIcon(MAPCHANGE_RES); + } + + private static String REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/replace.png"; + + public static Image getReplaceImage() { + return getImage(REPLACE_RES); + } + + public static Image getReplaceIcon() { + return getIcon(REPLACE_RES); + } + + private static String REST_RES = "/com/gpl/rpg/atcontentstudio/img/rest.png"; + + public static Image getRestImage() { + return getImage(REST_RES); + } + + public static Image getRestIcon() { + return getIcon(REST_RES); + } + + private static String SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/script.png"; + + public static Image getScriptImage() { + return getImage(SCRIPT_RES); + } + + public static Image getScriptIcon() { + return getIcon(SCRIPT_RES); + } + + private static String SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/sign.png"; + + public static Image getSignImage() { + return getImage(SIGN_RES); + } + + public static Image getSignIcon() { + return getIcon(SIGN_RES); + } + + private static String CREATE_CONTAINER_RES = "/com/gpl/rpg/atcontentstudio/img/create_container.png"; + + public static Image getCreateContainerImage() { + return getImage(CREATE_CONTAINER_RES); + } + + public static Image getCreateContainerIcon() { + return getIcon(CREATE_CONTAINER_RES); + } + + private static String CREATE_KEY_RES = "/com/gpl/rpg/atcontentstudio/img/create_key.png"; + + public static Image getCreateKeyImage() { + return getImage(CREATE_KEY_RES); + } + + public static Image getCreateKeyIcon() { + return getIcon(CREATE_KEY_RES); + } + + private static String CREATE_REPLACE_RES = "/com/gpl/rpg/atcontentstudio/img/create_replace.png"; + + public static Image getCreateReplaceImage() { + return getImage(CREATE_REPLACE_RES); + } + + public static Image getCreateReplaceIcon() { + return getIcon(CREATE_REPLACE_RES); + } + + private static String CREATE_REST_RES = "/com/gpl/rpg/atcontentstudio/img/create_rest.png"; + + public static Image getCreateRestImage() { + return getImage(CREATE_REST_RES); + } + + public static Image getCreateRestIcon() { + return getIcon(CREATE_REST_RES); + } + + private static String CREATE_SCRIPT_RES = "/com/gpl/rpg/atcontentstudio/img/create_script.png"; + + public static Image getCreateScriptImage() { + return getImage(CREATE_SCRIPT_RES); + } + + public static Image getCreateScriptIcon() { + return getIcon(CREATE_SCRIPT_RES); + } + + private static String CREATE_SIGN_RES = "/com/gpl/rpg/atcontentstudio/img/create_sign.png"; + + public static Image getCreateSignImage() { + return getImage(CREATE_SIGN_RES); + } + + public static Image getCreateSignIcon() { + return getIcon(CREATE_SIGN_RES); + } + + private static String CREATE_SPAWNAREA_RES = "/com/gpl/rpg/atcontentstudio/img/create_spawnarea.png"; + + public static Image getCreateSpawnareaImage() { + return getImage(CREATE_SPAWNAREA_RES); + } + + public static Image getCreateSpawnareaIcon() { + return getIcon(CREATE_SPAWNAREA_RES); + } + + private static String CREATE_MAPCHANGE_RES = "/com/gpl/rpg/atcontentstudio/img/create_tiled.png"; + + public static Image getCreateMapchangeImage() { + return getImage(CREATE_MAPCHANGE_RES); + } + + public static Image getCreateMapchangeIcon() { + return getIcon(CREATE_MAPCHANGE_RES); + } + + private static String CREATE_OBJECT_GROUP_RES = "/com/gpl/rpg/atcontentstudio/img/create_object_group.png"; + + public static Image getCreateObjectGroupImage() { + return getImage(CREATE_OBJECT_GROUP_RES); + } + + public static Image getCreateObjectGroupIcon() { + return getIcon(CREATE_OBJECT_GROUP_RES); + } + + private static String CREATE_TILE_LAYER_RES = "/com/gpl/rpg/atcontentstudio/img/create_tile_layer.png"; + + public static Image getCreateTileLayerImage() { + return getImage(CREATE_TILE_LAYER_RES); + } + + public static Image getCreateTileLayerIcon() { + return getIcon(CREATE_TILE_LAYER_RES); + } + + private static String LABEL_RES = "/com/gpl/rpg/atcontentstudio/img/label.png"; + + public static Image getLabelImage() { + return getImage(LABEL_RES); + } + + public static Image getLabelIcon() { + return getIcon(LABEL_RES); + } + + private static String ZOOM_RES = "/com/gpl/rpg/atcontentstudio/img/zoom.png"; + + public static Image getZoomImage() { + return getImage(ZOOM_RES); + } + + public static Image getZoomIcon() { + return getIcon(ZOOM_RES); + } + + private static String TIMER_RES = "/com/gpl/rpg/atcontentstudio/img/timer.png"; + + public static Image getTimerImage() { + return getImage(TIMER_RES); + } + + public static Image getTimerIcon() { + return getIcon(TIMER_RES); + } + + private static String DATE_RES = "/com/gpl/rpg/atcontentstudio/img/date.png"; + + public static Image getDateImage() { + return getImage(DATE_RES); + } + + public static Image getDateIcon() { + return getIcon(DATE_RES); + } + + private static String TIME_RES = "/com/gpl/rpg/atcontentstudio/img/date.png"; + + public static Image getTimeImage() { + return getImage(TIME_RES); + } + + public static Image getTimeIcon() { + return getIcon(TIME_RES); + } + + private static String ALIGNMENT_RES = "/com/gpl/rpg/atcontentstudio/img/alignment.png"; + + public static Image getAlignmentImage() { + return getImage(ALIGNMENT_RES); + } + + public static Image getAlignmentIcon() { + return getIcon(ALIGNMENT_RES); + } + + private static String STATUS_RED_RES = "/com/gpl/rpg/atcontentstudio/img/status_red.png"; + + public static Image getStatusRedImage() { + return getImage(STATUS_RED_RES); + } + + public static Image getStatusRedIcon() { + return getIcon(STATUS_RED_RES); + } + + private static String STATUS_ORANGE_RES = "/com/gpl/rpg/atcontentstudio/img/status_orange.png"; + + public static Image getStatusOrangeImage() { + return getImage(STATUS_ORANGE_RES); + } + + public static Image getStatusOrangeIcon() { + return getIcon(STATUS_ORANGE_RES); + } + + private static String STATUS_GREEN_RES = "/com/gpl/rpg/atcontentstudio/img/status_green.png"; + + public static Image getStatusGreenImage() { + return getImage(STATUS_GREEN_RES); + } + + public static Image getStatusGreenIcon() { + return getIcon(STATUS_GREEN_RES); + } + + private static String STATUS_BLUE_RES = "/com/gpl/rpg/atcontentstudio/img/status_blue.png"; + + public static Image getStatusBlueImage() { + return getImage(STATUS_BLUE_RES); + } + + public static Image getStatusBlueIcon() { + return getIcon(STATUS_BLUE_RES); + } + + private static String STATUS_UNKNOWN_RES = "/com/gpl/rpg/atcontentstudio/img/status_unknown.png"; + + public static Image getStatusUnknownImage() { + return getImage(STATUS_UNKNOWN_RES); + } + + public static Image getStatusUnknownIcon() { + return getIcon(STATUS_UNKNOWN_RES); + } + + private static String BOOKMARK_INACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_inactive.png"; + + public static Image getBookmarkInactiveImage() { + return getImage(BOOKMARK_INACTIVE); + } + + public static Image getBookmarkInactiveIcon() { + return getIcon(BOOKMARK_INACTIVE); + } + + private static String BOOKMARK_ACTIVE = "/com/gpl/rpg/atcontentstudio/img/bookmark_active.png"; + + public static Image getBookmarkActiveImage() { + return getImage(BOOKMARK_ACTIVE); + } + + public static Image getBookmarkActiveIcon() { + return getIcon(BOOKMARK_ACTIVE); + } + + + private static Image getImage(String res) { + if (imageCache.get(res) == null) { + try { + Image img = ImageIO.read(DefaultIcons.class.getResourceAsStream(res)); + imageCache.put(res, img); + } catch (IOException e) { + Notification.addError("Failed to load image " + res); + e.printStackTrace(); + } + } + return imageCache.get(res); + } + + private static Image getIcon(String res) { + if (iconCache.get(res) == null) { + Image icon = getImage(res).getScaledInstance((int) (16 * ATContentStudio.SCALING), (int) (16 * ATContentStudio.SCALING), Image.SCALE_SMOOTH); + iconCache.put(res, icon); + } + return iconCache.get(res); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index a129f3f..b07c7c9 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -1,1143 +1,1158 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Desktop; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.regex.Matcher; - -import javax.swing.AbstractListModel; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultListCellRenderer; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JSpinner.NumberEditor; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ListModel; -import javax.swing.SpinnerNumberModel; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import javax.swing.text.DefaultFormatter; -import javax.swing.text.JTextComponent; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectElementListener; import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; import com.jidesoft.swing.ComboBoxSearchable; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.JSpinner.NumberEditor; +import javax.swing.event.*; +import javax.swing.text.DefaultFormatter; +import javax.swing.text.JTextComponent; +import java.awt.*; +import java.awt.event.*; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.regex.Matcher; + public abstract class Editor extends JPanel implements ProjectElementListener { - private static final long serialVersionUID = 241750514033596878L; - private static final FieldUpdateListener nullListener = new FieldUpdateListener() {@Override public void valueChanged(JComponent source, Object value) {}}; - - public static final String SAVE = "Save"; - public static final String DELETE = "Delete"; - public static final String REVERT = "Revert to original"; - public static final String ALTER = "Alter"; - public static final String GO_TO_ALTERED = "Go to altered"; - - - public static final String READ_ONLY_MESSAGE = - "" + - "This element is not modifiable.
" + - "Click on the \"Alter\" button to create a writable copy." + - "
"; + private static final long serialVersionUID = 241750514033596878L; + private static final FieldUpdateListener nullListener = new FieldUpdateListener() { + @Override + public void valueChanged(JComponent source, Object value) { + } + }; - public static final String ALTERED_EXISTS_MESSAGE = - "" + - "This element is not modifiable.
" + - "A writable copy exists in this project. Click on \"Go to altered\" to open it." + - "
"; - - public static final String ALTERED_MESSAGE = - "" + - "This element is a writable copy of an element of the referenced game source.
" + - "Take care not to break existing content when modifying it." + - "
"; + public static final String SAVE = "Save"; + public static final String DELETE = "Delete"; + public static final String REVERT = "Revert to original"; + public static final String ALTER = "Alter"; + public static final String GO_TO_ALTERED = "Go to altered"; - public static final String CREATED_MESSAGE = - "" + - "This element is a creation of yours.
" + - "Do as you please." + - "
"; - - public String name = "Editor"; - public Icon icon = null; - public GameDataElement target = null; + public static final String READ_ONLY_MESSAGE = + "" + + "This element is not modifiable.
" + + "Click on the \"Alter\" button to create a writable copy." + + "
"; - public JLabel message = null; - - - public static JTextField addLabelField(JPanel pane, String label, String value) { - return addTextField(pane, label, value, false, nullListener); - } - - public static void addTranslationPane(JPanel pane, final JTextComponent tfComponent, final String initialValue) {if (Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null) { - JPanel labelPane = new JPanel(); - labelPane.setLayout(new JideBoxLayout(labelPane, JideBoxLayout.LINE_AXIS, 6)); - final JLabel translateLinkLabel = new JLabel(getWeblateLabelLink(initialValue)); - labelPane.add(translateLinkLabel, JideBoxLayout.FIX); - labelPane.add(new JLabel(" "), JideBoxLayout.FIX); - final JLabel translationStatus = new JLabel("Retrieving..."); - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusUnknownIcon())); - translationStatus.setToolTipText("Connecting to weblate..."); - labelPane.add(translationStatus, JideBoxLayout.VARY); - new Thread() { - public void run() { - WeblateIntegration.WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(initialValue); - switch (unit.status) { - case absent: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); - translationStatus.setToolTipText("This string isn't managed by weblate (yet)."); - break; - case done: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusGreenIcon())); - translationStatus.setToolTipText("This string is translated on weblate."); - break; - case fuzzy: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); - translationStatus.setToolTipText("This string is translated on weblate, but needs a review."); - break; - case notTranslated: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); - translationStatus.setToolTipText("This string isn't translated in your language on weblate yet."); - break; - case warning: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); - translationStatus.setToolTipText("This string is translated on weblate, but triggered some weblate checks."); - break; - case error: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); - translationStatus.setToolTipText("Cannot connect to weblate. Check internet connection and firewall settings."); - break; - case notAllowed: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusBlueIcon())); - translationStatus.setToolTipText("You have not allowed ATCS to access to internet. You can change this in the workspace settings."); - break; - } - translationStatus.setText(unit.translatedText); - }; - }.start(); - pane.add(labelPane, JideBoxLayout.FIX); - tfComponent.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); - translateLinkLabel.revalidate(); - translateLinkLabel.repaint(); - } - @Override - public void insertUpdate(DocumentEvent e) { - translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); - translateLinkLabel.revalidate(); - translateLinkLabel.repaint(); - } - @Override - public void changedUpdate(DocumentEvent e) { - translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); - translateLinkLabel.revalidate(); - translateLinkLabel.repaint(); - } - }); - translateLinkLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); - translateLinkLabel.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - try { - Desktop.getDesktop().browse(new URI(WeblateIntegration.getWeblateLabelURI(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))))); - } catch (IOException e1) { - e1.printStackTrace(); - } catch (URISyntaxException e1) { - e1.printStackTrace(); - } - } - } - }); - } - } - - public static JTextField addTranslatableTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - final JTextField tfField = addTextField(pane, label, initialValue, editable, listener); - addTranslationPane(pane, tfField, initialValue); - return tfField; - } - - public static String getWeblateLabelLink(String text) { - return "Translate on weblate"; - } - - public static JTextField addTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - final JTextField tfField = new JTextField(initialValue); - tfField.setEditable(editable); - tfPane.add(tfField, JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - tfField.setText(""); - listener.valueChanged(tfField, null); - } - }); - tfField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - listener.valueChanged(tfField, tfField.getText()); - } - @Override - public void insertUpdate(DocumentEvent e) { - listener.valueChanged(tfField, tfField.getText()); - } - @Override - public void changedUpdate(DocumentEvent e) { - listener.valueChanged(tfField, tfField.getText()); - } - }); - tfField.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(tfField, tfField.getText()); - } - }); - return tfField; - } - - - public static JTextArea addTranslatableTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - final JTextArea tfArea = addTextArea(pane, label, initialValue, editable, listener); - addTranslationPane(pane, tfArea, initialValue); - return tfArea; - } - - public static JTextArea addTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - String text= initialValue == null ? "" : initialValue.replaceAll("\\n", "\n"); - - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - final JTextArea tfArea = new JTextArea(text); - tfArea.setEditable(editable); - tfArea.setRows(2); - tfArea.setLineWrap(true); - tfArea.setWrapStyleWord(true); - tfPane.add(new JScrollPane(tfArea), JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - tfArea.setText(""); - listener.valueChanged(tfArea, null); - } - }); - tfArea.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); - } - @Override - public void insertUpdate(DocumentEvent e) { - listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); - } - @Override - public void changedUpdate(DocumentEvent e) { - listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); - } - }); + public static final String ALTERED_EXISTS_MESSAGE = + "" + + "This element is not modifiable.
" + + "A writable copy exists in this project. Click on \"Go to altered\" to open it." + + "
"; + + public static final String ALTERED_MESSAGE = + "" + + "This element is a writable copy of an element of the referenced game source.
" + + "Take care not to break existing content when modifying it." + + "
"; + + public static final String CREATED_MESSAGE = + "" + + "This element is a creation of yours.
" + + "Do as you please." + + "
"; + + + public String name = "Editor"; + public Icon icon = null; + public GameDataElement target = null; + + public JLabel message = null; + + + public static JTextField addLabelField(JPanel pane, String label, String value) { + return addTextField(pane, label, value, false, nullListener); + } + + public static void addTranslationPane(JPanel pane, final JTextComponent tfComponent, final String initialValue) { + if (Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null) { + JPanel labelPane = new JPanel(); + labelPane.setLayout(new JideBoxLayout(labelPane, JideBoxLayout.LINE_AXIS, 6)); + final JLabel translateLinkLabel = new JLabel(getWeblateLabelLink(initialValue)); + labelPane.add(translateLinkLabel, JideBoxLayout.FIX); + labelPane.add(new JLabel(" "), JideBoxLayout.FIX); + final JLabel translationStatus = new JLabel("Retrieving..."); + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusUnknownIcon())); + translationStatus.setToolTipText("Connecting to weblate..."); + labelPane.add(translationStatus, JideBoxLayout.VARY); + new Thread() { + public void run() { + WeblateIntegration.WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(initialValue); + switch (unit.status) { + case absent: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); + translationStatus.setToolTipText("This string isn't managed by weblate (yet)."); + break; + case done: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusGreenIcon())); + translationStatus.setToolTipText("This string is translated on weblate."); + break; + case fuzzy: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); + translationStatus.setToolTipText("This string is translated on weblate, but needs a review."); + break; + case notTranslated: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); + translationStatus.setToolTipText("This string isn't translated in your language on weblate yet."); + break; + case warning: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); + translationStatus.setToolTipText("This string is translated on weblate, but triggered some weblate checks."); + break; + case error: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); + translationStatus.setToolTipText("Cannot connect to weblate. Check internet connection and firewall settings."); + break; + case notAllowed: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusBlueIcon())); + translationStatus.setToolTipText("You have not allowed ATCS to access to internet. You can change this in the workspace settings."); + break; + } + translationStatus.setText(unit.translatedText); + } + + ; + }.start(); + pane.add(labelPane, JideBoxLayout.FIX); + tfComponent.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); + translateLinkLabel.revalidate(); + translateLinkLabel.repaint(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); + translateLinkLabel.revalidate(); + translateLinkLabel.repaint(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); + translateLinkLabel.revalidate(); + translateLinkLabel.repaint(); + } + }); + translateLinkLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); + translateLinkLabel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + try { + Desktop.getDesktop().browse(new URI(WeblateIntegration.getWeblateLabelURI(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))))); + } catch (IOException e1) { + e1.printStackTrace(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); + } + } + } + }); + } + } + + public static JTextField addTranslatableTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + final JTextField tfField = addTextField(pane, label, initialValue, editable, listener); + addTranslationPane(pane, tfField, initialValue); + return tfField; + } + + public static String getWeblateLabelLink(String text) { + return "Translate on weblate"; + } + + public static JTextField addTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + final JTextField tfField = new JTextField(initialValue); + tfField.setEditable(editable); + tfPane.add(tfField, JideBoxLayout.VARY); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + tfField.setText(""); + listener.valueChanged(tfField, null); + } + }); + tfField.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + listener.valueChanged(tfField, tfField.getText()); + } + + @Override + public void insertUpdate(DocumentEvent e) { + listener.valueChanged(tfField, tfField.getText()); + } + + @Override + public void changedUpdate(DocumentEvent e) { + listener.valueChanged(tfField, tfField.getText()); + } + }); + tfField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(tfField, tfField.getText()); + } + }); + return tfField; + } + + + public static JTextArea addTranslatableTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + final JTextArea tfArea = addTextArea(pane, label, initialValue, editable, listener); + addTranslationPane(pane, tfArea, initialValue); + return tfArea; + } + + public static JTextArea addTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + String text = initialValue == null ? "" : initialValue.replaceAll("\\n", "\n"); + + JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + final JTextArea tfArea = new JTextArea(text); + tfArea.setEditable(editable); + tfArea.setRows(2); + tfArea.setLineWrap(true); + tfArea.setWrapStyleWord(true); + tfPane.add(new JScrollPane(tfArea), JideBoxLayout.VARY); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + tfArea.setText(""); + listener.valueChanged(tfArea, null); + } + }); + tfArea.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); + } + + @Override + public void insertUpdate(DocumentEvent e) { + listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); + } + + @Override + public void changedUpdate(DocumentEvent e) { + listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); + } + }); // tfArea.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", "\\n")); // } // }); - return tfArea; - } + return tfArea; + } // public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, boolean allowNegatives, boolean editable) { // return addIntegerField(pane, label, initialValue, allowNegatives, editable, nullListener); // } - - public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { - return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener); - } - - public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.intValue() : defaultValue.intValue(), allowNegatives ? Integer.MIN_VALUE : 0, Integer.MAX_VALUE, 1)); - ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - spinner.setEnabled(editable); - ((DefaultFormatter)((NumberEditor)spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(spinner, JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - spinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - listener.valueChanged(spinner, spinner.getValue()); - } - }); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - spinner.setValue(0); - listener.valueChanged(spinner, null); - } - }); - return spinner; - } - - - private static final String percent = "%"; - private static final String ratio = "x/y"; - public static JComponent addChanceField(JPanel pane, String label, String initialValue, String defaultValue, boolean editable, final FieldUpdateListener listener) { - int defaultChance = 1; - int defaultMaxChance = 100; - if (defaultValue != null) { - if (defaultValue.contains("/")) { - int c = defaultValue.indexOf('/'); - try { defaultChance = Integer.parseInt(defaultValue.substring(0, c)); } catch (NumberFormatException nfe) {}; - try { defaultMaxChance = Integer.parseInt(defaultValue.substring(c+1)); } catch (NumberFormatException nfe) {}; - } else { - try { defaultChance = Integer.parseInt(defaultValue); } catch (NumberFormatException nfe) {}; - } - } - - boolean currentFormIsRatio = true; - int chance = defaultChance; - int maxChance = defaultMaxChance; - if (initialValue != null) { - if (initialValue.contains("/")) { - int c = initialValue.indexOf('/'); - try { chance = Integer.parseInt(initialValue.substring(0, c)); } catch (NumberFormatException nfe) {}; - try { maxChance = Integer.parseInt(initialValue.substring(c+1)); } catch (NumberFormatException nfe) {}; - } else { - try { - chance = Integer.parseInt(initialValue); - currentFormIsRatio = false; - } catch (NumberFormatException nfe) {}; - } - } - - final JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - - final JComboBox entryTypeBox = new JComboBox(new String[] {percent, ratio}); - if (currentFormIsRatio) { - entryTypeBox.setSelectedItem(ratio); - } else { - entryTypeBox.setSelectedItem(percent); - } - entryTypeBox.setEnabled(editable); - tfPane.add(entryTypeBox, JideBoxLayout.FIX); - /////////////////////////////////////////////////////////////////////////////////////////////////// make sure "chance" is between 1 and 100. If lower than 1 get 1. If higher than 100, get chance/maxChance * 100... Then do the same with defaultChance, in case no value exist. - final SpinnerNumberModel percentModel = new SpinnerNumberModel(initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 / defaultMaxChance)) , 1, 100, 1); - final SpinnerNumberModel ratioChanceModel = new SpinnerNumberModel(initialValue != null ? chance : defaultChance, 1, Integer.MAX_VALUE, 1); - - final JSpinner chanceSpinner = new JSpinner(currentFormIsRatio ? ratioChanceModel : percentModel); - if (!currentFormIsRatio) ((JSpinner.DefaultEditor)chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - chanceSpinner.setEnabled(editable); - ((DefaultFormatter)((NumberEditor)chanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(chanceSpinner, JideBoxLayout.FLEXIBLE); - - final JLabel ratioLabel = new JLabel("/"); - tfPane.add(ratioLabel, JideBoxLayout.FIX); - - final JSpinner maxChanceSpinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? maxChance : defaultMaxChance, 1, Integer.MAX_VALUE, 1)); - ((JSpinner.DefaultEditor)maxChanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - maxChanceSpinner.setEnabled(editable); - ((DefaultFormatter)((NumberEditor)maxChanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(maxChanceSpinner, JideBoxLayout.FLEXIBLE); - - if (!currentFormIsRatio) { - ratioLabel.setVisible(false); - maxChanceSpinner.setVisible(false); - tfPane.revalidate(); - tfPane.repaint(); - } - - final JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - - entryTypeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (entryTypeBox.getSelectedItem() == percent) { - int chance = ((Integer)chanceSpinner.getValue()); - int maxChance = ((Integer)maxChanceSpinner.getValue()); - chance *= 100; - chance /= maxChance; - chance = Math.max(0, Math.min(100, chance)); - chanceSpinner.setModel(percentModel); - chanceSpinner.setValue(chance); - ((JSpinner.DefaultEditor)chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - ratioLabel.setVisible(false); - maxChanceSpinner.setVisible(false); - tfPane.revalidate(); - tfPane.repaint(); - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); - } else if (entryTypeBox.getSelectedItem() == ratio) { - int chance = ((Integer)chanceSpinner.getValue()); - chanceSpinner.setModel(ratioChanceModel); - chanceSpinner.setValue(chance); - maxChanceSpinner.setValue(100); - ratioLabel.setVisible(true); - maxChanceSpinner.setVisible(true); - tfPane.revalidate(); - tfPane.repaint(); - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); - } - } - }); - chanceSpinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - if (entryTypeBox.getSelectedItem() == percent) { - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); - } else if (entryTypeBox.getSelectedItem() == ratio) { - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); - } - } - }); - maxChanceSpinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); - } - }); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - chanceSpinner.setValue(1); - listener.valueChanged(chanceSpinner, null); - } - }); - return chanceSpinner; - } - + + public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { + return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener); + } + + public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { + JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.intValue() : defaultValue.intValue(), allowNegatives ? Integer.MIN_VALUE : 0, Integer.MAX_VALUE, 1)); + ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + spinner.setEnabled(editable); + ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); + tfPane.add(spinner, JideBoxLayout.VARY); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + spinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + listener.valueChanged(spinner, spinner.getValue()); + } + }); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + spinner.setValue(0); + listener.valueChanged(spinner, null); + } + }); + return spinner; + } + + + private static final String percent = "%"; + private static final String ratio = "x/y"; + + public static JComponent addChanceField(JPanel pane, String label, String initialValue, String defaultValue, boolean editable, final FieldUpdateListener listener) { + int defaultChance = 1; + int defaultMaxChance = 100; + if (defaultValue != null) { + if (defaultValue.contains("/")) { + int c = defaultValue.indexOf('/'); + try { + defaultChance = Integer.parseInt(defaultValue.substring(0, c)); + } catch (NumberFormatException nfe) { + } + ; + try { + defaultMaxChance = Integer.parseInt(defaultValue.substring(c + 1)); + } catch (NumberFormatException nfe) { + } + ; + } else { + try { + defaultChance = Integer.parseInt(defaultValue); + } catch (NumberFormatException nfe) { + } + ; + } + } + + boolean currentFormIsRatio = true; + int chance = defaultChance; + int maxChance = defaultMaxChance; + if (initialValue != null) { + if (initialValue.contains("/")) { + int c = initialValue.indexOf('/'); + try { + chance = Integer.parseInt(initialValue.substring(0, c)); + } catch (NumberFormatException nfe) { + } + ; + try { + maxChance = Integer.parseInt(initialValue.substring(c + 1)); + } catch (NumberFormatException nfe) { + } + ; + } else { + try { + chance = Integer.parseInt(initialValue); + currentFormIsRatio = false; + } catch (NumberFormatException nfe) { + } + ; + } + } + + final JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + + final JComboBox entryTypeBox = new JComboBox(new String[]{percent, ratio}); + if (currentFormIsRatio) { + entryTypeBox.setSelectedItem(ratio); + } else { + entryTypeBox.setSelectedItem(percent); + } + entryTypeBox.setEnabled(editable); + tfPane.add(entryTypeBox, JideBoxLayout.FIX); + /////////////////////////////////////////////////////////////////////////////////////////////////// make sure "chance" is between 1 and 100. If lower than 1 get 1. If higher than 100, get chance/maxChance * 100... Then do the same with defaultChance, in case no value exist. + final SpinnerNumberModel percentModel = new SpinnerNumberModel(initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 / defaultMaxChance)), 1, 100, 1); + final SpinnerNumberModel ratioChanceModel = new SpinnerNumberModel(initialValue != null ? chance : defaultChance, 1, Integer.MAX_VALUE, 1); + + final JSpinner chanceSpinner = new JSpinner(currentFormIsRatio ? ratioChanceModel : percentModel); + if (!currentFormIsRatio) + ((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + chanceSpinner.setEnabled(editable); + ((DefaultFormatter) ((NumberEditor) chanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); + tfPane.add(chanceSpinner, JideBoxLayout.FLEXIBLE); + + final JLabel ratioLabel = new JLabel("/"); + tfPane.add(ratioLabel, JideBoxLayout.FIX); + + final JSpinner maxChanceSpinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? maxChance : defaultMaxChance, 1, Integer.MAX_VALUE, 1)); + ((JSpinner.DefaultEditor) maxChanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + maxChanceSpinner.setEnabled(editable); + ((DefaultFormatter) ((NumberEditor) maxChanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); + tfPane.add(maxChanceSpinner, JideBoxLayout.FLEXIBLE); + + if (!currentFormIsRatio) { + ratioLabel.setVisible(false); + maxChanceSpinner.setVisible(false); + tfPane.revalidate(); + tfPane.repaint(); + } + + final JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + + entryTypeBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (entryTypeBox.getSelectedItem() == percent) { + int chance = ((Integer) chanceSpinner.getValue()); + int maxChance = ((Integer) maxChanceSpinner.getValue()); + chance *= 100; + chance /= maxChance; + chance = Math.max(0, Math.min(100, chance)); + chanceSpinner.setModel(percentModel); + chanceSpinner.setValue(chance); + ((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + ratioLabel.setVisible(false); + maxChanceSpinner.setVisible(false); + tfPane.revalidate(); + tfPane.repaint(); + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); + } else if (entryTypeBox.getSelectedItem() == ratio) { + int chance = ((Integer) chanceSpinner.getValue()); + chanceSpinner.setModel(ratioChanceModel); + chanceSpinner.setValue(chance); + maxChanceSpinner.setValue(100); + ratioLabel.setVisible(true); + maxChanceSpinner.setVisible(true); + tfPane.revalidate(); + tfPane.repaint(); + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); + } + } + }); + chanceSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + if (entryTypeBox.getSelectedItem() == percent) { + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); + } else if (entryTypeBox.getSelectedItem() == ratio) { + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); + } + } + }); + maxChanceSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); + } + }); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + chanceSpinner.setValue(1); + listener.valueChanged(chanceSpinner, null); + } + }); + return chanceSpinner; + } + // public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable) { // return addDoubleField(pane, label, initialValue, editable, nullListener); // } - - public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) { - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.doubleValue() : 0.0d, 0.0d, new Float(Float.MAX_VALUE).doubleValue(), 1.0d)); - ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - spinner.setEnabled(editable); - ((DefaultFormatter)((NumberEditor)spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(spinner, JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - pane.add(tfPane, JideBoxLayout.FIX); - spinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - listener.valueChanged(spinner, spinner.getValue()); - } - }); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - spinner.setValue(0.0d); - listener.valueChanged(spinner, null); - } - }); - return spinner; - } - - public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) { - return addIntegerBasedCheckBox(pane, label, initialValue, editable, nullListener); - } - - public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable, final FieldUpdateListener listener) { - JPanel ibcbPane = new JPanel(); - ibcbPane.setLayout(new BorderLayout()); - final IntegerBasedCheckBox ibcb = new IntegerBasedCheckBox(); - ibcb.setText(label); - ibcb.setIntegerValue(initialValue); - ibcb.setEnabled(editable); - ibcbPane.add(ibcb, BorderLayout.WEST); - ibcbPane.add(new JPanel(), BorderLayout.CENTER); - pane.add(ibcbPane, JideBoxLayout.FIX); - ibcb.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(ibcb, ibcb.getIntegerValue()); - } - }); - return ibcb; - } - - public static BooleanBasedCheckBox addBooleanBasedCheckBox(JPanel pane, String label, Boolean initialValue, boolean editable, final FieldUpdateListener listener) { - JPanel bbcbPane = new JPanel(); - bbcbPane.setLayout(new BorderLayout()); - final BooleanBasedCheckBox bbcb = new BooleanBasedCheckBox(); - bbcb.setText(label); - bbcb.setBooleanValue(initialValue); - bbcb.setEnabled(editable); - bbcbPane.add(bbcb, BorderLayout.WEST); - bbcbPane.add(new JPanel(), BorderLayout.CENTER); - pane.add(bbcbPane, JideBoxLayout.FIX); - bbcb.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(bbcb, bbcb.isSelected()); - } - }); - return bbcb; - } - - @SuppressWarnings("rawtypes") - public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable) { - return addEnumValueBox(pane, label, values, initialValue, writable, new FieldUpdateListener() {@Override public void valueChanged(JComponent source, Object value) {}}); - } - - @SuppressWarnings("rawtypes") - public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable, final FieldUpdateListener listener) { - JPanel comboPane = new JPanel(); - comboPane.setLayout(new JideBoxLayout(comboPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel comboLabel = new JLabel(label); - comboPane.add(comboLabel, JideBoxLayout.FIX); - @SuppressWarnings("unchecked") - final JComboBox enumValuesCombo = new JComboBox(values); - enumValuesCombo.setEnabled(writable); - enumValuesCombo.setSelectedItem(initialValue); - comboPane.add(enumValuesCombo, JideBoxLayout.VARY); - enumValuesCombo.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - listener.valueChanged(enumValuesCombo, e.getItem()); - } - } - }); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - comboPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(writable); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - enumValuesCombo.setSelectedItem(null); - listener.valueChanged(enumValuesCombo, null); - } - }); - - pane.add(comboPane, JideBoxLayout.FIX); - return enumValuesCombo; - } - - public MyComboBox addNPCBox(JPanel pane, Project proj, String label, NPC npc, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, npc){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public NPC getTypedElementAt(int index) { - return project.getNPC(index); - } - @Override - public int getSize() { - return project.getNPCCount()+1; - } - }; - return addGDEBox(pane, label, npc, NPC.class, comboModel, writable, listener); - } - - public MyComboBox addActorConditionBox(JPanel pane, Project proj, String label, ActorCondition acond, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, acond){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public ActorCondition getTypedElementAt(int index) { - return project.getActorCondition(index); - } - @Override - public int getSize() { - return project.getActorConditionCount()+1; - } - }; - return addGDEBox(pane, label, acond, ActorCondition.class, comboModel, writable, listener); - } - - public MyComboBox addItemBox(JPanel pane, Project proj, String label, Item item, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, item){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public Item getTypedElementAt(int index) { - return project.getItem(index); - } - @Override - public int getSize() { - return project.getItemCount()+1; - } - }; - return addGDEBox(pane, label, item, Item.class, comboModel, writable, listener); - } - - public MyComboBox addItemCategoryBox(JPanel pane, Project proj, String label, ItemCategory ic, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, ic){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public ItemCategory getTypedElementAt(int index) { - return project.getItemCategory(index); - } - @Override - public int getSize() { - return project.getItemCategoryCount()+1; - } - }; - return addGDEBox(pane, label, ic, ItemCategory.class, comboModel, writable, listener); - } + public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) { + JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.doubleValue() : 0.0d, 0.0d, new Float(Float.MAX_VALUE).doubleValue(), 1.0d)); + ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + spinner.setEnabled(editable); + ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); + tfPane.add(spinner, JideBoxLayout.VARY); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + pane.add(tfPane, JideBoxLayout.FIX); + spinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + listener.valueChanged(spinner, spinner.getValue()); + } + }); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + spinner.setValue(0.0d); + listener.valueChanged(spinner, null); + } + }); + return spinner; + } - public MyComboBox addQuestBox(JPanel pane, Project proj, String label, Quest quest, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, quest){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public Quest getTypedElementAt(int index) { - return project.getQuest(index); - } - @Override - public int getSize() { - return project.getQuestCount()+1; - } - }; - return addGDEBox(pane, label, quest, Quest.class, comboModel, writable, listener); - } + public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) { + return addIntegerBasedCheckBox(pane, label, initialValue, editable, nullListener); + } - public MyComboBox addDroplistBox(JPanel pane, Project proj, String label, Droplist droplist, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, droplist){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public Droplist getTypedElementAt(int index) { - return project.getDroplist(index); - } - @Override - public int getSize() { - return project.getDroplistCount()+1; - } - }; - return addGDEBox(pane, label, droplist, Droplist.class, comboModel, writable, listener); - } - - public MyComboBox addDialogueBox(JPanel pane, Project proj, String label, Dialogue dialogue, boolean writable, final FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, dialogue){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public Dialogue getTypedElementAt(int index) { - return project.getDialogue(index); - } - @Override - public int getSize() { - return project.getDialogueCount()+1; - } - }; - return addGDEBox(pane, label, dialogue, Dialogue.class, comboModel, writable, listener); - } + public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable, final FieldUpdateListener listener) { + JPanel ibcbPane = new JPanel(); + ibcbPane.setLayout(new BorderLayout()); + final IntegerBasedCheckBox ibcb = new IntegerBasedCheckBox(); + ibcb.setText(label); + ibcb.setIntegerValue(initialValue); + ibcb.setEnabled(editable); + ibcbPane.add(ibcb, BorderLayout.WEST); + ibcbPane.add(new JPanel(), BorderLayout.CENTER); + pane.add(ibcbPane, JideBoxLayout.FIX); + ibcb.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(ibcb, ibcb.getIntegerValue()); + } + }); + return ibcb; + } - public MyComboBox addMapBox(JPanel pane, Project proj, String label, TMXMap map, boolean writable, final FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, map){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public TMXMap getTypedElementAt(int index) { - return project.getMap(index); - } - @Override - public int getSize() { - return project.getMapCount()+1; - } - }; - return addGDEBox(pane, label, map, TMXMap.class, comboModel, writable, listener); - } - - @SuppressWarnings("unchecked") - public MyComboBox addGDEBox(JPanel pane, String label, GameDataElement gde, final Class dataClass, final GDEComboModel comboModel, final boolean writable, final FieldUpdateListener listener) { - JPanel gdePane = new JPanel(); - gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); - JLabel gdeLabel = new JLabel(label); - gdePane.add(gdeLabel, JideBoxLayout.FIX); - final MyComboBox gdeBox = new MyComboBox(dataClass, comboModel); - gdeBox.setRenderer(new GDERenderer(false, writable)); - new ComboBoxSearchable(gdeBox){ - @Override - protected String convertElementToString(Object object) { - if (object == null) return "none"; - else return ((GameDataElement)object).getDesc(); - } - }; - gdeBox.setEnabled(writable); - gdePane.add(gdeBox, JideBoxLayout.VARY); - final JButton goToGde = new JButton((Icon) ((gde != null) ? new ImageIcon(gde.getIcon()) : (writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null))); - goToGde.setEnabled(gde != null || writable); - goToGde.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - GameDataElement selected = ((GameDataElement)comboModel.getSelectedItem()); - if (selected != null) { - ATContentStudio.frame.openEditor(((GameDataElement)comboModel.getSelectedItem())); - ATContentStudio.frame.selectInTree((GameDataElement)comboModel.getSelectedItem()); - } else if (writable) { - JSONCreationWizard wizard = new JSONCreationWizard(((GameDataElement)target).getProject(), dataClass); - wizard.addCreationListener(new JSONCreationWizard.CreationCompletedListener() { - - @Override - public void elementCreated(JSONElement created) { - gdeBox.setSelectedItem(created); - } - }); - wizard.setVisible(true); - } - } - }); - gdePane.add(goToGde, JideBoxLayout.FIX); - gdeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (gdeBox.getModel().getSelectedItem() == null) { - goToGde.setIcon((writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null)); - goToGde.setEnabled(writable); - } else { - goToGde.setIcon(new ImageIcon(((GameDataElement)comboModel.getSelectedItem()).getIcon())); - goToGde.setEnabled(true); - } - listener.valueChanged(gdeBox, gdeBox.getModel().getSelectedItem()); - } - }); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - gdePane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(writable); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - gdeBox.setSelectedItem(null); - } - }); - pane.add(gdePane, JideBoxLayout.FIX); - - return gdeBox; - } - - public JComboBox addQuestStageBox(JPanel pane, Project proj, String label, Integer initialValue, boolean writable, final FieldUpdateListener listener, Quest quest, @SuppressWarnings("rawtypes") final JComboBox questSelectionBox) { - JPanel gdePane = new JPanel(); - gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); - JLabel gdeLabel = new JLabel(label); - gdePane.add(gdeLabel, JideBoxLayout.FIX); - - QuestStage initial = null; - if (quest != null) { - initial = quest.getStage(initialValue); - } - final QuestStageComboModel comboModel = new QuestStageComboModel(proj, initial, quest); - final JComboBox combo = new JComboBox(comboModel); - combo.setRenderer(new GDERenderer(false, writable)); - new ComboBoxSearchable(combo){ - @Override - protected String convertElementToString(Object object) { - if (object == null) return "none"; - else return ((GameDataElement)object).getDesc(); - } - }; - questSelectionBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (comboModel.selected != null) { - Editor.this.target.removeBacklink(comboModel.selected); - } - Quest newQuest = (Quest) questSelectionBox.getSelectedItem(); - comboModel.changeQuest(newQuest); - combo.revalidate(); - } - }); - combo.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(combo, comboModel.selected == null ? null : comboModel.selected.progress); - } - }); - - + public static BooleanBasedCheckBox addBooleanBasedCheckBox(JPanel pane, String label, Boolean initialValue, boolean editable, final FieldUpdateListener listener) { + JPanel bbcbPane = new JPanel(); + bbcbPane.setLayout(new BorderLayout()); + final BooleanBasedCheckBox bbcb = new BooleanBasedCheckBox(); + bbcb.setText(label); + bbcb.setBooleanValue(initialValue); + bbcb.setEnabled(editable); + bbcbPane.add(bbcb, BorderLayout.WEST); + bbcbPane.add(new JPanel(), BorderLayout.CENTER); + pane.add(bbcbPane, JideBoxLayout.FIX); + bbcb.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(bbcb, bbcb.isSelected()); + } + }); + return bbcb; + } - combo.setEnabled(writable); - gdePane.add(combo, JideBoxLayout.VARY); - - pane.add(gdePane, JideBoxLayout.FIX); - - return combo; - } - - - - @SuppressWarnings({ "rawtypes"}) - public JList addBacklinksList(JPanel pane, GameDataElement gde) { - return addBacklinksList(pane, gde, "Elements linking to this one"); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public JList addBacklinksList(JPanel pane, GameDataElement gde, String title) { - final JList list = new JList(new GDEBacklinksListModel(gde)); - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - ATContentStudio.frame.openEditor((GameDataElement)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((GameDataElement)list.getSelectedValue()); - } - } - }); - list.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - ATContentStudio.frame.openEditor((GameDataElement)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((GameDataElement)list.getSelectedValue()); - } - } - }); - list.setCellRenderer(new GDERenderer(true, false)); - CollapsiblePanel colPane = new CollapsiblePanel(title); - colPane.setLayout(new JideBoxLayout(colPane, JideBoxLayout.PAGE_AXIS)); - colPane.add(new JScrollPane(list), JideBoxLayout.FIX); - colPane.add(new JPanel(), JideBoxLayout.FIX); - if (gde.getBacklinks() == null || gde.getBacklinks().isEmpty()) { - colPane.collapse(); - } - pane.add(colPane, JideBoxLayout.FIX); - return list; - } - - public static abstract class GDEComboModel extends AbstractListModel implements ComboBoxModel { + @SuppressWarnings("rawtypes") + public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable) { + return addEnumValueBox(pane, label, values, initialValue, writable, new FieldUpdateListener() { + @Override + public void valueChanged(JComponent source, Object value) { + } + }); + } - private static final long serialVersionUID = -5854574666510314715L; - - public Project project; - public E selected; - - public GDEComboModel(Project proj, E initial) { - this.project = proj; - this.selected = initial; - } - - @Override - public abstract int getSize(); + @SuppressWarnings("rawtypes") + public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable, final FieldUpdateListener listener) { + JPanel comboPane = new JPanel(); + comboPane.setLayout(new JideBoxLayout(comboPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel comboLabel = new JLabel(label); + comboPane.add(comboLabel, JideBoxLayout.FIX); + @SuppressWarnings("unchecked") final JComboBox enumValuesCombo = new JComboBox(values); + enumValuesCombo.setEnabled(writable); + enumValuesCombo.setSelectedItem(initialValue); + comboPane.add(enumValuesCombo, JideBoxLayout.VARY); + enumValuesCombo.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + listener.valueChanged(enumValuesCombo, e.getItem()); + } + } + }); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + comboPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(writable); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + enumValuesCombo.setSelectedItem(null); + listener.valueChanged(enumValuesCombo, null); + } + }); - @Override - public E getElementAt(int index) { - if (index == 0) { - return null; - } - return getTypedElementAt(index - 1); - } - - public abstract E getTypedElementAt(int index); - - @SuppressWarnings("unchecked") - @Override - public void setSelectedItem(Object anItem) { - selected = (E) anItem; - } + pane.add(comboPane, JideBoxLayout.FIX); + return enumValuesCombo; + } - @Override - public Object getSelectedItem() { - return selected; - } - - public void itemAdded(E item, int index) { - fireIntervalAdded(this, index, index); - } - - public void itemRemoved(E item, int index) { - fireIntervalRemoved(this, index, index); - } - - } - - public static class GDERenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 6819681566800482793L; + public MyComboBox addNPCBox(JPanel pane, Project proj, String label, NPC npc, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, npc) { + private static final long serialVersionUID = 2638082961277241764L; - private boolean includeType; - private boolean writable; - - public GDERenderer(boolean includeType, boolean writable) { - super(); - this.includeType = includeType; - this.writable = writable; - } - - @SuppressWarnings("rawtypes") - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value == null) { - label.setText("None"+(writable ? ". Click on the button to create one." : "")); - } else { - if (includeType && ((GameDataElement)value).getDataType() != null) { - if (value instanceof QuestStage) { - String text = ((GameDataElement)value).getDesc(); - if (text.length() > 60) { - text = text.substring(0, 57)+"..."; - } - label.setText(((GameDataElement)value).getDataType().toString()+"/"+((Quest)((QuestStage)value).parent).id+"#"+((QuestStage)value).progress+":"+text); - } else { - label.setText(((GameDataElement)value).getDataType().toString()+"/"+((GameDataElement)value).getDesc()); - } - } else { - if (value instanceof QuestStage) { - String text = ((GameDataElement)value).getDesc(); - if (text.length() > 60) { - text = text.substring(0, 57)+"..."; - } - label.setText(text); - } else { - label.setText(((GameDataElement)value).getDesc()); - } - } - if (((GameDataElement)value).getIcon() == null) { - Notification.addError("Unable to find icon for "+((GameDataElement)value).getDesc()); - } else { - label.setIcon(new ImageIcon(((GameDataElement)value).getIcon())); - } - } - return label; - } - - } - - public static class QuestStageComboModel extends AbstractListModel implements ComboBoxModel { + @Override + public NPC getTypedElementAt(int index) { + return project.getNPC(index); + } - private static final long serialVersionUID = -5854574666510314715L; - - public Project project; - public Quest currentQuest; - public QuestStage selected; - - public QuestStageComboModel(Project proj, QuestStage initial, Quest quest) { - this.project = proj; - this.currentQuest = quest; - this.selected = initial; - } - - @Override - public int getSize() { - if (currentQuest == null) return 1; - return currentQuest.stages.size()+1; - } + @Override + public int getSize() { + return project.getNPCCount() + 1; + } + }; + return addGDEBox(pane, label, npc, NPC.class, comboModel, writable, listener); + } - @Override - public QuestStage getElementAt(int index) { - if (index == 0) { - return null; - } - return currentQuest.stages.get(index - 1); - } - - @Override - public void setSelectedItem(Object anItem) { - selected = (QuestStage) anItem; - } + public MyComboBox addActorConditionBox(JPanel pane, Project proj, String label, ActorCondition acond, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, acond) { + private static final long serialVersionUID = 2638082961277241764L; - @Override - public Object getSelectedItem() { - return selected; - } - - public void itemAdded(QuestStage item, int index) { - fireIntervalAdded(this, index, index); - } - - public void itemRemoved(QuestStage item, int index) { - fireIntervalRemoved(this, index, index); - } - - public void changeQuest(Quest newQuest) { - int size = getSize(); - currentQuest = null; - selected = null; - fireIntervalRemoved(this, 1, size); - currentQuest = newQuest; - fireIntervalAdded(this, 1, getSize()); - } - - } - - - public static class GDEBacklinksListModel implements ListenerCollectionModel { - - GameDataElement source; - - public GDEBacklinksListModel(GameDataElement source) { - super(); - this.source = source; - source.addBacklinkListener(new GameDataElement.BacklinksListener() { - @Override - public void backlinkRemoved(GameDataElement gde) { - fireListChanged(); - } - @Override - public void backlinkAdded(GameDataElement gde) { - fireListChanged(); - } - }); - } + @Override + public ActorCondition getTypedElementAt(int index) { + return project.getActorCondition(index); + } - @Override - public Collection getElements() { - return source.getBacklinks(); - } + @Override + public int getSize() { + return project.getActorConditionCount() + 1; + } + }; + return addGDEBox(pane, label, acond, ActorCondition.class, comboModel, writable, listener); + } - List listeners = new CopyOnWriteArrayList(); + public MyComboBox addItemBox(JPanel pane, Project proj, String label, Item item, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, item) { + private static final long serialVersionUID = 2638082961277241764L; - @Override - public List getListeners() { - return listeners; - } + @Override + public Item getTypedElementAt(int index) { + return project.getItem(index); + } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public class MyComboBox extends JComboBox implements ProjectElementListener { - - private static final long serialVersionUID = -4184228604170642567L; - - Class dataType; - - public MyComboBox(Class dataType, ComboBoxModel model) { - super(model); - this.dataType = dataType; - Editor.this.addElementListener(dataType, this); - } - - @Override - public void elementAdded(GameDataElement added, int index) { - ((GDEComboModel)getModel()).itemAdded(added, index); - } + @Override + public int getSize() { + return project.getItemCount() + 1; + } + }; + return addGDEBox(pane, label, item, Item.class, comboModel, writable, listener); + } - @Override - public void elementRemoved(GameDataElement removed, int index) { - ((GDEComboModel)getModel()).itemRemoved(removed, index); - } - - @Override - public Class getDataType() { - return dataType; - } - - } - - public abstract void targetUpdated(); - + public MyComboBox addItemCategoryBox(JPanel pane, Project proj, String label, ItemCategory ic, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, ic) { + private static final long serialVersionUID = 2638082961277241764L; - - transient Map, List> projectElementListeners = new HashMap, List>(); - - public void addElementListener(Class interestingType, ProjectElementListener listener) { - if (projectElementListeners.get(interestingType) == null) { - projectElementListeners.put(interestingType, new ArrayList()); - target.getProject().addElementListener(interestingType, this); - } - projectElementListeners.get(interestingType).add(listener); - } - - public void removeElementListener(ProjectElementListener listener) { - if (listener == null) return; - if (projectElementListeners.get(listener.getDataType()) != null) { - projectElementListeners.get(listener.getDataType()).remove(listener); - if (projectElementListeners.get(listener.getDataType()).isEmpty()) { - target.getProject().removeElementListener(listener.getDataType(), this); - projectElementListeners.remove(listener.getDataType()); - } - } - } - - public void elementAdded(GameDataElement element, int index) { - if (projectElementListeners.get(element.getClass()) != null) { - for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { - l.elementAdded(element, index); - } - } - } + @Override + public ItemCategory getTypedElementAt(int index) { + return project.getItemCategory(index); + } + + @Override + public int getSize() { + return project.getItemCategoryCount() + 1; + } + }; + return addGDEBox(pane, label, ic, ItemCategory.class, comboModel, writable, listener); + } + + public MyComboBox addQuestBox(JPanel pane, Project proj, String label, Quest quest, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, quest) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public Quest getTypedElementAt(int index) { + return project.getQuest(index); + } + + @Override + public int getSize() { + return project.getQuestCount() + 1; + } + }; + return addGDEBox(pane, label, quest, Quest.class, comboModel, writable, listener); + } + + public MyComboBox addDroplistBox(JPanel pane, Project proj, String label, Droplist droplist, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, droplist) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public Droplist getTypedElementAt(int index) { + return project.getDroplist(index); + } + + @Override + public int getSize() { + return project.getDroplistCount() + 1; + } + }; + return addGDEBox(pane, label, droplist, Droplist.class, comboModel, writable, listener); + } + + public MyComboBox addDialogueBox(JPanel pane, Project proj, String label, Dialogue dialogue, boolean writable, final FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, dialogue) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public Dialogue getTypedElementAt(int index) { + return project.getDialogue(index); + } + + @Override + public int getSize() { + return project.getDialogueCount() + 1; + } + }; + return addGDEBox(pane, label, dialogue, Dialogue.class, comboModel, writable, listener); + } + + public MyComboBox addMapBox(JPanel pane, Project proj, String label, TMXMap map, boolean writable, final FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, map) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public TMXMap getTypedElementAt(int index) { + return project.getMap(index); + } + + @Override + public int getSize() { + return project.getMapCount() + 1; + } + }; + return addGDEBox(pane, label, map, TMXMap.class, comboModel, writable, listener); + } + + @SuppressWarnings("unchecked") + public MyComboBox addGDEBox(JPanel pane, String label, GameDataElement gde, final Class dataClass, final GDEComboModel comboModel, final boolean writable, final FieldUpdateListener listener) { + JPanel gdePane = new JPanel(); + gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); + JLabel gdeLabel = new JLabel(label); + gdePane.add(gdeLabel, JideBoxLayout.FIX); + final MyComboBox gdeBox = new MyComboBox(dataClass, comboModel); + gdeBox.setRenderer(new GDERenderer(false, writable)); + new ComboBoxSearchable(gdeBox) { + @Override + protected String convertElementToString(Object object) { + if (object == null) return "none"; + else return ((GameDataElement) object).getDesc(); + } + }; + gdeBox.setEnabled(writable); + gdePane.add(gdeBox, JideBoxLayout.VARY); + final JButton goToGde = new JButton((Icon) ((gde != null) ? new ImageIcon(gde.getIcon()) : (writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null))); + goToGde.setEnabled(gde != null || writable); + goToGde.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + GameDataElement selected = ((GameDataElement) comboModel.getSelectedItem()); + if (selected != null) { + ATContentStudio.frame.openEditor(((GameDataElement) comboModel.getSelectedItem())); + ATContentStudio.frame.selectInTree((GameDataElement) comboModel.getSelectedItem()); + } else if (writable) { + JSONCreationWizard wizard = new JSONCreationWizard(((GameDataElement) target).getProject(), dataClass); + wizard.addCreationListener(new JSONCreationWizard.CreationCompletedListener() { + + @Override + public void elementCreated(JSONElement created) { + gdeBox.setSelectedItem(created); + } + }); + wizard.setVisible(true); + } + } + }); + gdePane.add(goToGde, JideBoxLayout.FIX); + gdeBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (gdeBox.getModel().getSelectedItem() == null) { + goToGde.setIcon((writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null)); + goToGde.setEnabled(writable); + } else { + goToGde.setIcon(new ImageIcon(((GameDataElement) comboModel.getSelectedItem()).getIcon())); + goToGde.setEnabled(true); + } + listener.valueChanged(gdeBox, gdeBox.getModel().getSelectedItem()); + } + }); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + gdePane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(writable); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + gdeBox.setSelectedItem(null); + } + }); + pane.add(gdePane, JideBoxLayout.FIX); + + return gdeBox; + } + + public JComboBox addQuestStageBox(JPanel pane, Project proj, String label, Integer initialValue, boolean writable, final FieldUpdateListener listener, Quest quest, @SuppressWarnings("rawtypes") final JComboBox questSelectionBox) { + JPanel gdePane = new JPanel(); + gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); + JLabel gdeLabel = new JLabel(label); + gdePane.add(gdeLabel, JideBoxLayout.FIX); + + QuestStage initial = null; + if (quest != null) { + initial = quest.getStage(initialValue); + } + final QuestStageComboModel comboModel = new QuestStageComboModel(proj, initial, quest); + final JComboBox combo = new JComboBox(comboModel); + combo.setRenderer(new GDERenderer(false, writable)); + new ComboBoxSearchable(combo) { + @Override + protected String convertElementToString(Object object) { + if (object == null) return "none"; + else return ((GameDataElement) object).getDesc(); + } + }; + questSelectionBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (comboModel.selected != null) { + Editor.this.target.removeBacklink(comboModel.selected); + } + Quest newQuest = (Quest) questSelectionBox.getSelectedItem(); + comboModel.changeQuest(newQuest); + combo.revalidate(); + } + }); + combo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(combo, comboModel.selected == null ? null : comboModel.selected.progress); + } + }); + + + combo.setEnabled(writable); + gdePane.add(combo, JideBoxLayout.VARY); + + pane.add(gdePane, JideBoxLayout.FIX); + + return combo; + } + + + @SuppressWarnings({"rawtypes"}) + public JList addBacklinksList(JPanel pane, GameDataElement gde) { + return addBacklinksList(pane, gde, "Elements linking to this one"); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public JList addBacklinksList(JPanel pane, GameDataElement gde, String title) { + final JList list = new JList(new GDEBacklinksListModel(gde)); + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); + } + } + }); + list.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); + } + } + }); + list.setCellRenderer(new GDERenderer(true, false)); + CollapsiblePanel colPane = new CollapsiblePanel(title); + colPane.setLayout(new JideBoxLayout(colPane, JideBoxLayout.PAGE_AXIS)); + colPane.add(new JScrollPane(list), JideBoxLayout.FIX); + colPane.add(new JPanel(), JideBoxLayout.FIX); + if (gde.getBacklinks() == null || gde.getBacklinks().isEmpty()) { + colPane.collapse(); + } + pane.add(colPane, JideBoxLayout.FIX); + return list; + } + + public static abstract class GDEComboModel extends AbstractListModel implements ComboBoxModel { + + private static final long serialVersionUID = -5854574666510314715L; + + public Project project; + public E selected; + + public GDEComboModel(Project proj, E initial) { + this.project = proj; + this.selected = initial; + } + + @Override + public abstract int getSize(); + + @Override + public E getElementAt(int index) { + if (index == 0) { + return null; + } + return getTypedElementAt(index - 1); + } + + public abstract E getTypedElementAt(int index); + + @SuppressWarnings("unchecked") + @Override + public void setSelectedItem(Object anItem) { + selected = (E) anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + + public void itemAdded(E item, int index) { + fireIntervalAdded(this, index, index); + } + + public void itemRemoved(E item, int index) { + fireIntervalRemoved(this, index, index); + } + + } + + public static class GDERenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 6819681566800482793L; + + private boolean includeType; + private boolean writable; + + public GDERenderer(boolean includeType, boolean writable) { + super(); + this.includeType = includeType; + this.writable = writable; + } + + @SuppressWarnings("rawtypes") + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value == null) { + label.setText("None" + (writable ? ". Click on the button to create one." : "")); + } else { + if (includeType && ((GameDataElement) value).getDataType() != null) { + if (value instanceof QuestStage) { + String text = ((GameDataElement) value).getDesc(); + if (text.length() > 60) { + text = text.substring(0, 57) + "..."; + } + label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((Quest) ((QuestStage) value).parent).id + "#" + ((QuestStage) value).progress + ":" + text); + } else { + label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((GameDataElement) value).getDesc()); + } + } else { + if (value instanceof QuestStage) { + String text = ((GameDataElement) value).getDesc(); + if (text.length() > 60) { + text = text.substring(0, 57) + "..."; + } + label.setText(text); + } else { + label.setText(((GameDataElement) value).getDesc()); + } + } + if (((GameDataElement) value).getIcon() == null) { + Notification.addError("Unable to find icon for " + ((GameDataElement) value).getDesc()); + } else { + label.setIcon(new ImageIcon(((GameDataElement) value).getIcon())); + } + } + return label; + } + + } + + public static class QuestStageComboModel extends AbstractListModel implements ComboBoxModel { + + private static final long serialVersionUID = -5854574666510314715L; + + public Project project; + public Quest currentQuest; + public QuestStage selected; + + public QuestStageComboModel(Project proj, QuestStage initial, Quest quest) { + this.project = proj; + this.currentQuest = quest; + this.selected = initial; + } + + @Override + public int getSize() { + if (currentQuest == null) return 1; + return currentQuest.stages.size() + 1; + } + + @Override + public QuestStage getElementAt(int index) { + if (index == 0) { + return null; + } + return currentQuest.stages.get(index - 1); + } + + @Override + public void setSelectedItem(Object anItem) { + selected = (QuestStage) anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + + public void itemAdded(QuestStage item, int index) { + fireIntervalAdded(this, index, index); + } + + public void itemRemoved(QuestStage item, int index) { + fireIntervalRemoved(this, index, index); + } + + public void changeQuest(Quest newQuest) { + int size = getSize(); + currentQuest = null; + selected = null; + fireIntervalRemoved(this, 1, size); + currentQuest = newQuest; + fireIntervalAdded(this, 1, getSize()); + } + + } + + + public static class GDEBacklinksListModel implements ListenerCollectionModel { + + GameDataElement source; + + public GDEBacklinksListModel(GameDataElement source) { + super(); + this.source = source; + source.addBacklinkListener(new GameDataElement.BacklinksListener() { + @Override + public void backlinkRemoved(GameDataElement gde) { + fireListChanged(); + } + + @Override + public void backlinkAdded(GameDataElement gde) { + fireListChanged(); + } + }); + } + + @Override + public Collection getElements() { + return source.getBacklinks(); + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public List getListeners() { + return listeners; + } + + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public class MyComboBox extends JComboBox implements ProjectElementListener { + + private static final long serialVersionUID = -4184228604170642567L; + + Class dataType; + + public MyComboBox(Class dataType, ComboBoxModel model) { + super(model); + this.dataType = dataType; + Editor.this.addElementListener(dataType, this); + } + + @Override + public void elementAdded(GameDataElement added, int index) { + ((GDEComboModel) getModel()).itemAdded(added, index); + } + + @Override + public void elementRemoved(GameDataElement removed, int index) { + ((GDEComboModel) getModel()).itemRemoved(removed, index); + } + + @Override + public Class getDataType() { + return dataType; + } + + } + + public abstract void targetUpdated(); + + + transient Map, List> projectElementListeners = new HashMap, List>(); + + public void addElementListener(Class interestingType, ProjectElementListener listener) { + if (projectElementListeners.get(interestingType) == null) { + projectElementListeners.put(interestingType, new ArrayList()); + target.getProject().addElementListener(interestingType, this); + } + projectElementListeners.get(interestingType).add(listener); + } + + public void removeElementListener(ProjectElementListener listener) { + if (listener == null) return; + if (projectElementListeners.get(listener.getDataType()) != null) { + projectElementListeners.get(listener.getDataType()).remove(listener); + if (projectElementListeners.get(listener.getDataType()).isEmpty()) { + target.getProject().removeElementListener(listener.getDataType(), this); + projectElementListeners.remove(listener.getDataType()); + } + } + } + + public void elementAdded(GameDataElement element, int index) { + if (projectElementListeners.get(element.getClass()) != null) { + for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { + l.elementAdded(element, index); + } + } + } + + public void elementRemoved(GameDataElement element, int index) { + if (projectElementListeners.get(element.getClass()) != null) { + for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { + l.elementRemoved(element, index); + } + } + } + + public void clearElementListeners() { + for (Class type : projectElementListeners.keySet()) { + target.getProject().removeElementListener(type, this); + } + } + + public Class getDataType() { + return null; + } - public void elementRemoved(GameDataElement element, int index) { - if (projectElementListeners.get(element.getClass()) != null) { - for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { - l.elementRemoved(element, index); - } - } - } - - public void clearElementListeners() { - for (Class type : projectElementListeners.keySet()) { - target.getProject().removeElementListener(type, this); - } - } - - public Class getDataType() { - return null; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/EditorsArea.java b/src/com/gpl/rpg/atcontentstudio/ui/EditorsArea.java index d81aaf7..e815676 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/EditorsArea.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/EditorsArea.java @@ -1,35 +1,13 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.beans.PropertyChangeListener; -import java.util.LinkedHashMap; -import java.util.Map; - -import javax.swing.Action; -import javax.swing.JPanel; - import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; import com.gpl.rpg.atcontentstudio.model.saves.SavedGame; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.ActorConditionEditor; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DialogueEditor; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DroplistEditor; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.ItemCategoryEditor; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.ItemEditor; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.NPCEditor; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.QuestEditor; +import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.*; import com.gpl.rpg.atcontentstudio.ui.map.TMXMapEditor; import com.gpl.rpg.atcontentstudio.ui.map.WorldMapEditor; import com.gpl.rpg.atcontentstudio.ui.saves.SavedGameEditor; @@ -37,162 +15,174 @@ import com.gpl.rpg.atcontentstudio.ui.sprites.SpritesheetEditor; import com.gpl.rpg.atcontentstudio.ui.tools.writermode.WriterModeEditor; import com.jidesoft.swing.JideTabbedPane; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.beans.PropertyChangeListener; +import java.util.LinkedHashMap; +import java.util.Map; + public class EditorsArea extends JPanel { - private static final long serialVersionUID = 8801849846876081538L; + private static final long serialVersionUID = 8801849846876081538L; - private Map editors = new LinkedHashMap(); - private JideTabbedPane tabHolder; - - public EditorsArea() { - super(); - setLayout(new BorderLayout()); - tabHolder = new JideTabbedPane(); - tabHolder.setTabPlacement(JideTabbedPane.TOP); - tabHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); - tabHolder.setUseDefaultShowCloseButtonOnTab(false); - tabHolder.setShowCloseButtonOnTab(true); - tabHolder.setCloseAction(new Action() { - @Override - public void actionPerformed(ActionEvent e) { - closeEditor((Editor) e.getSource()); - } - - @Override - public void setEnabled(boolean b) { - } - @Override - public void removePropertyChangeListener(PropertyChangeListener listener) { - } - @Override - public void putValue(String key, Object value) { - } - @Override - public boolean isEnabled() { - return true; - } - @Override - public Object getValue(String key) { - return null; - } - @Override - public void addPropertyChangeListener(PropertyChangeListener listener) { - } - }); - add(tabHolder, BorderLayout.CENTER); - } - - public void openEditor(Editor e) { - if (!editors.containsKey(e.target) && !editors.containsValue(e)) { - editors.put(e.target, e); - tabHolder.addTab(e.name, e.icon, e); - tabHolder.setSelectedComponent(e); - } - } - - public void closeEditor(Editor e) { - if (editors.containsValue(e)) { - tabHolder.remove(e); - editors.remove(e.target); - e.clearElementListeners(); - } - } + private Map editors = new LinkedHashMap(); + private JideTabbedPane tabHolder; - public void openEditor(JSONElement node) { - if (editors.containsKey(node)) { - tabHolder.setSelectedComponent(editors.get(node)); - return; - } - if (node instanceof Quest) { - openEditor(new QuestEditor((Quest)node)); - } else if (node instanceof Dialogue) { - openEditor(new DialogueEditor((Dialogue) node)); - } else if (node instanceof Droplist) { - openEditor(new DroplistEditor((Droplist) node)); - } else if (node instanceof ActorCondition) { - openEditor(new ActorConditionEditor((ActorCondition) node)); - } else if (node instanceof ItemCategory) { - openEditor(new ItemCategoryEditor((ItemCategory) node)); - } else if (node instanceof Item) { - openEditor(new ItemEditor((Item) node)); - } else if (node instanceof NPC) { - openEditor(new NPCEditor((NPC) node)); - } - } - - public void openEditor(Spritesheet node) { - if (editors.containsKey(node)) { - tabHolder.setSelectedComponent(editors.get(node)); - return; - } - node.link(); - openEditor(new SpritesheetEditor((Spritesheet) node)); - } + public EditorsArea() { + super(); + setLayout(new BorderLayout()); + tabHolder = new JideTabbedPane(); + tabHolder.setTabPlacement(JideTabbedPane.TOP); + tabHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); + tabHolder.setUseDefaultShowCloseButtonOnTab(false); + tabHolder.setShowCloseButtonOnTab(true); + tabHolder.setCloseAction(new Action() { + @Override + public void actionPerformed(ActionEvent e) { + closeEditor((Editor) e.getSource()); + } - public void openEditor(TMXMap node) { - if (editors.containsKey(node)) { - tabHolder.setSelectedComponent(editors.get(node)); - return; - } - node.link(); - openEditor(new TMXMapEditor(node)); - } + @Override + public void setEnabled(boolean b) { + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener listener) { + } + + @Override + public void putValue(String key, Object value) { + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public Object getValue(String key) { + return null; + } + + @Override + public void addPropertyChangeListener(PropertyChangeListener listener) { + } + }); + add(tabHolder, BorderLayout.CENTER); + } + + public void openEditor(Editor e) { + if (!editors.containsKey(e.target) && !editors.containsValue(e)) { + editors.put(e.target, e); + tabHolder.addTab(e.name, e.icon, e); + tabHolder.setSelectedComponent(e); + } + } + + public void closeEditor(Editor e) { + if (editors.containsValue(e)) { + tabHolder.remove(e); + editors.remove(e.target); + e.clearElementListeners(); + } + } + + public void openEditor(JSONElement node) { + if (editors.containsKey(node)) { + tabHolder.setSelectedComponent(editors.get(node)); + return; + } + if (node instanceof Quest) { + openEditor(new QuestEditor((Quest) node)); + } else if (node instanceof Dialogue) { + openEditor(new DialogueEditor((Dialogue) node)); + } else if (node instanceof Droplist) { + openEditor(new DroplistEditor((Droplist) node)); + } else if (node instanceof ActorCondition) { + openEditor(new ActorConditionEditor((ActorCondition) node)); + } else if (node instanceof ItemCategory) { + openEditor(new ItemCategoryEditor((ItemCategory) node)); + } else if (node instanceof Item) { + openEditor(new ItemEditor((Item) node)); + } else if (node instanceof NPC) { + openEditor(new NPCEditor((NPC) node)); + } + } + + public void openEditor(Spritesheet node) { + if (editors.containsKey(node)) { + tabHolder.setSelectedComponent(editors.get(node)); + return; + } + node.link(); + openEditor(new SpritesheetEditor((Spritesheet) node)); + } + + public void openEditor(TMXMap node) { + if (editors.containsKey(node)) { + tabHolder.setSelectedComponent(editors.get(node)); + return; + } + node.link(); + openEditor(new TMXMapEditor(node)); + } - public void openEditor(SavedGame save) { - if (editors.containsKey(save)) { - tabHolder.setSelectedComponent(editors.get(save)); - return; - } - openEditor(new SavedGameEditor(save)); - } + public void openEditor(SavedGame save) { + if (editors.containsKey(save)) { + tabHolder.setSelectedComponent(editors.get(save)); + return; + } + openEditor(new SavedGameEditor(save)); + } - public void openEditor(WorldmapSegment node) { - if (editors.containsKey(node)) { - tabHolder.setSelectedComponent(editors.get(node)); - return; - } - node.link(); - openEditor(new WorldMapEditor(node)); - } - - public void openEditor(WriterModeData node) { - if (editors.containsKey(node)) { - tabHolder.setSelectedComponent(editors.get(node)); - return; - } - node.link(); - openEditor(new WriterModeEditor(node)); - } - - public void closeEditor(ProjectTreeNode node) { - if (editors.containsKey(node)) { - closeEditor(editors.get(node)); - } - } - - public void editorTabChanged(Editor e) { - int index = tabHolder.indexOfComponent(e); - if (index >= 0) { - tabHolder.setTitleAt(index, e.name); - tabHolder.setIconAt(index, e.icon); - } - } + public void openEditor(WorldmapSegment node) { + if (editors.containsKey(node)) { + tabHolder.setSelectedComponent(editors.get(node)); + return; + } + node.link(); + openEditor(new WorldMapEditor(node)); + } - public void editorTabChanged(ProjectTreeNode node) { - if (editors.get(node) != null) { - editors.get(node).targetUpdated(); - editorTabChanged(editors.get(node)); - } - } - - public void showAbout() { - if (editors.containsKey(AboutEditor.instance)) { - tabHolder.setSelectedComponent(AboutEditor.instance); - return; - } - openEditor(AboutEditor.instance); - } + public void openEditor(WriterModeData node) { + if (editors.containsKey(node)) { + tabHolder.setSelectedComponent(editors.get(node)); + return; + } + node.link(); + openEditor(new WriterModeEditor(node)); + } + + public void closeEditor(ProjectTreeNode node) { + if (editors.containsKey(node)) { + closeEditor(editors.get(node)); + } + } + + public void editorTabChanged(Editor e) { + int index = tabHolder.indexOfComponent(e); + if (index >= 0) { + tabHolder.setTitleAt(index, e.name); + tabHolder.setIconAt(index, e.icon); + } + } + + public void editorTabChanged(ProjectTreeNode node) { + if (editors.get(node) != null) { + editors.get(node).targetUpdated(); + editorTabChanged(editors.get(node)); + } + } + + public void showAbout() { + if (editors.containsKey(AboutEditor.instance)) { + tabHolder.setSelectedComponent(AboutEditor.instance); + return; + } + openEditor(AboutEditor.instance); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ExportProjectWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/ExportProjectWizard.java index d4ab03d..bfeba25 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ExportProjectWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ExportProjectWizard.java @@ -1,21 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; - -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; @@ -23,204 +7,211 @@ import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet; import com.gpl.rpg.atcontentstudio.model.sprites.SpriteSheetSet; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; + public class ExportProjectWizard extends JDialog { - private static final long serialVersionUID = -8745083621008868612L; - - JPanel pane; - JLabel errorLabel, fileSelectionLabel; - JRadioButton asZip, overSources; - JComboBox target; - JButton browse; - JButton okButton, cancelButton; - - Project proj; - - public ExportProjectWizard(Project proj) { - - super(ATContentStudio.frame); - setTitle("Export project for inclusion in-game"); - - this.proj = proj; - - pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - errorLabel = new JLabel(); + private static final long serialVersionUID = -8745083621008868612L; - pane.add(errorLabel, JideBoxLayout.FIX); - pane.add(new JLabel("Export this ATCS project..."), JideBoxLayout.FIX); - - ButtonGroup radioGroup = new ButtonGroup(); - - asZip = new JRadioButton("... as a Zip archive"); - radioGroup.add(asZip); - overSources = new JRadioButton("... into a game source folder"); - radioGroup.add(overSources); - overSources.setSelected(true); + JPanel pane; + JLabel errorLabel, fileSelectionLabel; + JRadioButton asZip, overSources; + JComboBox target; + JButton browse; + JButton okButton, cancelButton; - pane.add(asZip, JideBoxLayout.FIX); - pane.add(overSources, JideBoxLayout.FIX); - - ActionListener updateListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateState(); - } - }; - asZip.addActionListener(updateListener); - overSources.addActionListener(updateListener); - - target = new JComboBox(); - target.setEditable(true); - target.addActionListener(updateListener); - browse = new JButton("Browse"); - browse.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser jfc = new JFileChooser(){ - private static final long serialVersionUID = -3001082967957619011L; - @Override - public boolean accept(File f) { - if (asZip.isSelected()) { - if (f.isDirectory() || f.getName().endsWith(".zip") || f.getName().endsWith(".ZIP")) { - return super.accept(f); - } else { - return false; - } - } else { - return f.isDirectory(); - } - } - }; - jfc.setFileSelectionMode(asZip.isSelected() ? JFileChooser.FILES_AND_DIRECTORIES : JFileChooser.DIRECTORIES_ONLY); - jfc.setSelectedFile(new File(target.getSelectedItem() == null ? "" : target.getSelectedItem().toString())); - jfc.setMultiSelectionEnabled(false); - int result = jfc.showOpenDialog(ATContentStudio.frame); - if (result == JFileChooser.APPROVE_OPTION) { - File f = jfc.getSelectedFile(); - if (asZip.isSelected() && !f.getAbsolutePath().substring(f.getAbsolutePath().length() - 4, f.getAbsolutePath().length()).equalsIgnoreCase(".zip")) { - f = new File(f.getAbsolutePath()+".zip"); - } - target.setSelectedItem(f.getAbsolutePath()); - updateState(); - } - } - }); - JPanel fileSelectionPane = new JPanel(); - fileSelectionPane.setLayout(new JideBoxLayout(fileSelectionPane, JideBoxLayout.LINE_AXIS, 6)); - fileSelectionLabel = new JLabel("Zip file: "); - fileSelectionPane.add(fileSelectionLabel, JideBoxLayout.FIX); - fileSelectionPane.add(target, JideBoxLayout.VARY); - fileSelectionPane.add(browse, JideBoxLayout.FIX); - - pane.add(fileSelectionPane, JideBoxLayout.FIX); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - cancelButton = new JButton("Cancel"); - buttonPane.add(cancelButton, JideBoxLayout.FIX); - okButton = new JButton("Ok"); - buttonPane.add(okButton, JideBoxLayout.FIX); - - pane.add(new JPanel(), JideBoxLayout.VARY); - - pane.add(buttonPane, JideBoxLayout.FIX); - - - cancelButton.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - ExportProjectWizard.this.setVisible(false); - ExportProjectWizard.this.dispose(); - } - }); - - okButton.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (asZip.isSelected()) { - ExportProjectWizard.this.proj.exportProjectAsZipPackage(new File(target.getSelectedItem().toString())); - } else { - ExportProjectWizard.this.proj.exportProjectOverGameSource(new File(target.getSelectedItem().toString())); - } - ExportProjectWizard.this.setVisible(false); - ExportProjectWizard.this.dispose(); - } - }); - - updateState(); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - setMinimumSize(new Dimension(500,150)); - pack(); + Project proj; - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - } - - private void updateState() { - if (asZip.isSelected()) { - fileSelectionLabel.setText("Zip file: "); - } else { - fileSelectionLabel.setText("Game source folder: "); - } - - - File f = new File(target.getSelectedItem() == null ? "" : target.getSelectedItem().toString()); - if (asZip.isSelected()) { - if (target.getSelectedItem() == null || target.getSelectedItem().toString().length() <= 0) { - errorLabel.setText("You must select where to save the zip file."); - okButton.setEnabled(false); - } else if (f.isDirectory()) { - errorLabel.setText("The selected target is a directory. It should be a zip file."); - okButton.setEnabled(false); - } else if (!(f.getName().toLowerCase().endsWith(".zip"))) { - errorLabel.setText("The selected target is not a zip file. It should be a zip file."); - okButton.setEnabled(false); - } else if (f.exists()) { - errorLabel.setText("The selected target is an existing zip file. It will be overwritten."); - okButton.setEnabled(true); - } else { - errorLabel.setText("Everything looks good !"); - okButton.setEnabled(true); - } - } else { - if (target.getSelectedItem() == null || target.getSelectedItem().toString().length() <= 0) { - errorLabel.setText("You must select an AT source root folder."); - okButton.setEnabled(false); - } else if (!f.isDirectory() || !f.exists()) { - errorLabel.setText("The selected AT source is not a folder. It should be an existing AT source root folder."); - okButton.setEnabled(false); - } else { - File res = new File(f, GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); - File drawable = new File(f, SpriteSheetSet.DEFAULT_REL_PATH_IN_SOURCE); - File xml = new File(f, TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE); - if (!res.exists()) { - errorLabel.setText("The selected AT source root folder does not contain the \"res\" folder."); - okButton.setEnabled(true); - } else if (!drawable.exists()) { - errorLabel.setText("The selected AT source root folder does not contain the \"drawable\" folder."); - okButton.setEnabled(true); - } else if (!xml.exists()) { - errorLabel.setText("The selected AT source root folder does not contain the \"xml\" folder."); - okButton.setEnabled(true); - } else { - errorLabel.setText("Everything looks good !"); - okButton.setEnabled(true); - } - } - } - revalidate(); - repaint(); + public ExportProjectWizard(Project proj) { + + super(ATContentStudio.frame); + setTitle("Export project for inclusion in-game"); + + this.proj = proj; + + pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + + errorLabel = new JLabel(); + + pane.add(errorLabel, JideBoxLayout.FIX); + pane.add(new JLabel("Export this ATCS project..."), JideBoxLayout.FIX); + + ButtonGroup radioGroup = new ButtonGroup(); + + asZip = new JRadioButton("... as a Zip archive"); + radioGroup.add(asZip); + overSources = new JRadioButton("... into a game source folder"); + radioGroup.add(overSources); + overSources.setSelected(true); + + pane.add(asZip, JideBoxLayout.FIX); + pane.add(overSources, JideBoxLayout.FIX); + + ActionListener updateListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateState(); + } + }; + asZip.addActionListener(updateListener); + overSources.addActionListener(updateListener); + + target = new JComboBox(); + target.setEditable(true); + target.addActionListener(updateListener); + browse = new JButton("Browse"); + browse.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JFileChooser jfc = new JFileChooser() { + private static final long serialVersionUID = -3001082967957619011L; + + @Override + public boolean accept(File f) { + if (asZip.isSelected()) { + if (f.isDirectory() || f.getName().endsWith(".zip") || f.getName().endsWith(".ZIP")) { + return super.accept(f); + } else { + return false; + } + } else { + return f.isDirectory(); + } + } + }; + jfc.setFileSelectionMode(asZip.isSelected() ? JFileChooser.FILES_AND_DIRECTORIES : JFileChooser.DIRECTORIES_ONLY); + jfc.setSelectedFile(new File(target.getSelectedItem() == null ? "" : target.getSelectedItem().toString())); + jfc.setMultiSelectionEnabled(false); + int result = jfc.showOpenDialog(ATContentStudio.frame); + if (result == JFileChooser.APPROVE_OPTION) { + File f = jfc.getSelectedFile(); + if (asZip.isSelected() && !f.getAbsolutePath().substring(f.getAbsolutePath().length() - 4, f.getAbsolutePath().length()).equalsIgnoreCase(".zip")) { + f = new File(f.getAbsolutePath() + ".zip"); + } + target.setSelectedItem(f.getAbsolutePath()); + updateState(); + } + } + }); + JPanel fileSelectionPane = new JPanel(); + fileSelectionPane.setLayout(new JideBoxLayout(fileSelectionPane, JideBoxLayout.LINE_AXIS, 6)); + fileSelectionLabel = new JLabel("Zip file: "); + fileSelectionPane.add(fileSelectionLabel, JideBoxLayout.FIX); + fileSelectionPane.add(target, JideBoxLayout.VARY); + fileSelectionPane.add(browse, JideBoxLayout.FIX); + + pane.add(fileSelectionPane, JideBoxLayout.FIX); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + cancelButton = new JButton("Cancel"); + buttonPane.add(cancelButton, JideBoxLayout.FIX); + okButton = new JButton("Ok"); + buttonPane.add(okButton, JideBoxLayout.FIX); + + pane.add(new JPanel(), JideBoxLayout.VARY); + + pane.add(buttonPane, JideBoxLayout.FIX); + + + cancelButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + ExportProjectWizard.this.setVisible(false); + ExportProjectWizard.this.dispose(); + } + }); + + okButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (asZip.isSelected()) { + ExportProjectWizard.this.proj.exportProjectAsZipPackage(new File(target.getSelectedItem().toString())); + } else { + ExportProjectWizard.this.proj.exportProjectOverGameSource(new File(target.getSelectedItem().toString())); + } + ExportProjectWizard.this.setVisible(false); + ExportProjectWizard.this.dispose(); + } + }); + + updateState(); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + setMinimumSize(new Dimension(500, 150)); + pack(); + + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + } + + private void updateState() { + if (asZip.isSelected()) { + fileSelectionLabel.setText("Zip file: "); + } else { + fileSelectionLabel.setText("Game source folder: "); + } + + + File f = new File(target.getSelectedItem() == null ? "" : target.getSelectedItem().toString()); + if (asZip.isSelected()) { + if (target.getSelectedItem() == null || target.getSelectedItem().toString().length() <= 0) { + errorLabel.setText("You must select where to save the zip file."); + okButton.setEnabled(false); + } else if (f.isDirectory()) { + errorLabel.setText("The selected target is a directory. It should be a zip file."); + okButton.setEnabled(false); + } else if (!(f.getName().toLowerCase().endsWith(".zip"))) { + errorLabel.setText("The selected target is not a zip file. It should be a zip file."); + okButton.setEnabled(false); + } else if (f.exists()) { + errorLabel.setText("The selected target is an existing zip file. It will be overwritten."); + okButton.setEnabled(true); + } else { + errorLabel.setText("Everything looks good !"); + okButton.setEnabled(true); + } + } else { + if (target.getSelectedItem() == null || target.getSelectedItem().toString().length() <= 0) { + errorLabel.setText("You must select an AT source root folder."); + okButton.setEnabled(false); + } else if (!f.isDirectory() || !f.exists()) { + errorLabel.setText("The selected AT source is not a folder. It should be an existing AT source root folder."); + okButton.setEnabled(false); + } else { + File res = new File(f, GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); + File drawable = new File(f, SpriteSheetSet.DEFAULT_REL_PATH_IN_SOURCE); + File xml = new File(f, TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE); + if (!res.exists()) { + errorLabel.setText("The selected AT source root folder does not contain the \"res\" folder."); + okButton.setEnabled(true); + } else if (!drawable.exists()) { + errorLabel.setText("The selected AT source root folder does not contain the \"drawable\" folder."); + okButton.setEnabled(true); + } else if (!xml.exists()) { + errorLabel.setText("The selected AT source root folder does not contain the \"xml\" folder."); + okButton.setEnabled(true); + } else { + errorLabel.setText("Everything looks good !"); + okButton.setEnabled(true); + } + } + } + revalidate(); + repaint(); + + } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/FieldUpdateListener.java b/src/com/gpl/rpg/atcontentstudio/ui/FieldUpdateListener.java index 35df936..7d4064d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/FieldUpdateListener.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/FieldUpdateListener.java @@ -1,9 +1,9 @@ package com.gpl.rpg.atcontentstudio.ui; -import javax.swing.JComponent; +import javax.swing.*; public interface FieldUpdateListener { - public void valueChanged(JComponent source, Object value); - + public void valueChanged(JComponent source, Object value); + } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/IdChangeImpactWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/IdChangeImpactWizard.java index 932966e..cd4aa10 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/IdChangeImpactWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/IdChangeImpactWizard.java @@ -1,100 +1,91 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; -import java.util.Vector; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.jidesoft.swing.JideBoxLayout; -public class IdChangeImpactWizard extends JDialog { - - private static final long serialVersionUID = 8532169707953315739L; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import java.util.Vector; - public static enum Result { - ok, cancel - } - - Result result = null; - - private IdChangeImpactWizard(GameDataElement changing, List toModify, List toAlter) { - super(ATContentStudio.frame, true); - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); - - pane.add(new JLabel("Changing the id for \""+changing.getDesc()+"\" has impacts on your project:"), JideBoxLayout.FIX); - pane.add(new JLabel("The following elements from your project will be modified:"), JideBoxLayout.FIX); - JList modifList = new JList(new Vector(toModify)); - modifList.setCellRenderer(new ChangeImpactListCellRenderer()); - pane.add(new JScrollPane(modifList), JideBoxLayout.FIX); - pane.add(new JLabel("The following elements from the game source will be altered:"), JideBoxLayout.FIX); - JList alterList = new JList(new Vector(toAlter)); - alterList.setCellRenderer(new ChangeImpactListCellRenderer()); - pane.add(new JScrollPane(alterList), JideBoxLayout.FIX); - pane.add(new JLabel("Press Ok to apply the changes, or Cancel to cancel your edition of the object's ID"), JideBoxLayout.FIX); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancelButton = new JButton("Cancel"); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - result = Result.cancel; - dispose(); - } - }); - buttonPane.add(cancelButton, JideBoxLayout.FIX); - JButton okButton = new JButton("Ok"); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - result = Result.ok; - dispose(); - } - }); - buttonPane.add(okButton, JideBoxLayout.FIX); - pane.add(buttonPane, JideBoxLayout.FIX); - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - pack(); - } - - - public static Result showIdChangeImapctWizard(GameDataElement changing, List toModify, List toAlter) { - IdChangeImpactWizard wizard = new IdChangeImpactWizard(changing, toModify, toAlter); - wizard.setVisible(true); - return wizard.result; - } - - public class ChangeImpactListCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 5764079243906396333L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = (JLabel) c; - GameDataElement target = ((GameDataElement)value); - label.setIcon(new ImageIcon(target.getIcon())); - label.setText(target.getDataType().toString()+"/"+target.getDesc()); - } - return c; - } - - } +public class IdChangeImpactWizard extends JDialog { + + private static final long serialVersionUID = 8532169707953315739L; + + public static enum Result { + ok, cancel + } + + Result result = null; + + private IdChangeImpactWizard(GameDataElement changing, List toModify, List toAlter) { + super(ATContentStudio.frame, true); + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); + + pane.add(new JLabel("Changing the id for \"" + changing.getDesc() + "\" has impacts on your project:"), JideBoxLayout.FIX); + pane.add(new JLabel("The following elements from your project will be modified:"), JideBoxLayout.FIX); + JList modifList = new JList(new Vector(toModify)); + modifList.setCellRenderer(new ChangeImpactListCellRenderer()); + pane.add(new JScrollPane(modifList), JideBoxLayout.FIX); + pane.add(new JLabel("The following elements from the game source will be altered:"), JideBoxLayout.FIX); + JList alterList = new JList(new Vector(toAlter)); + alterList.setCellRenderer(new ChangeImpactListCellRenderer()); + pane.add(new JScrollPane(alterList), JideBoxLayout.FIX); + pane.add(new JLabel("Press Ok to apply the changes, or Cancel to cancel your edition of the object's ID"), JideBoxLayout.FIX); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + result = Result.cancel; + dispose(); + } + }); + buttonPane.add(cancelButton, JideBoxLayout.FIX); + JButton okButton = new JButton("Ok"); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + result = Result.ok; + dispose(); + } + }); + buttonPane.add(okButton, JideBoxLayout.FIX); + pane.add(buttonPane, JideBoxLayout.FIX); + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + pack(); + } + + + public static Result showIdChangeImapctWizard(GameDataElement changing, List toModify, List toAlter) { + IdChangeImpactWizard wizard = new IdChangeImpactWizard(changing, toModify, toAlter); + wizard.setVisible(true); + return wizard.result; + } + + public class ChangeImpactListCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 5764079243906396333L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = (JLabel) c; + GameDataElement target = ((GameDataElement) value); + label.setIcon(new ImageIcon(target.getIcon())); + label.setText(target.getDataType().toString() + "/" + target.getDesc()); + } + return c; + } + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/IntegerBasedCheckBox.java b/src/com/gpl/rpg/atcontentstudio/ui/IntegerBasedCheckBox.java index 6d13db8..e073750 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/IntegerBasedCheckBox.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/IntegerBasedCheckBox.java @@ -1,19 +1,19 @@ package com.gpl.rpg.atcontentstudio.ui; -import javax.swing.JCheckBox; +import javax.swing.*; public class IntegerBasedCheckBox extends JCheckBox { - private static final long serialVersionUID = 3941646360487399554L; - - static final Integer one = 1; - - public Integer getIntegerValue() { - return isSelected() ? one : null; - } - - public void setIntegerValue(Integer val) { - setSelected(val != null && val.equals(one)); - } + private static final long serialVersionUID = 3941646360487399554L; + + static final Integer one = 1; + + public Integer getIntegerValue() { + return isSelected() ? one : null; + } + + public void setIntegerValue(Integer val) { + setSelected(val != null && val.equals(one)); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/JMovingIdler.java b/src/com/gpl/rpg/atcontentstudio/ui/JMovingIdler.java index e859721..db54ebb 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/JMovingIdler.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/JMovingIdler.java @@ -1,96 +1,93 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.Color; -import java.awt.GradientPaint; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Paint; - -import javax.swing.JComponent; +import javax.swing.*; +import java.awt.*; public class JMovingIdler extends JComponent { - private static final long serialVersionUID = -2980521421870322717L; - - int position = 0; - boolean destroyed=false, running=false; - Thread moverThread = new Thread(){ - public void run() { - while (!destroyed) { - boolean back = false; - while (running) { - if (back) { - position = --position % 100; - if (position == 0) { - back = false; - } - } else { - position = ++position % 100; - if (position == 99) { - back = true; - } - } - try { - sleep(10); - } catch (InterruptedException e) {} - JMovingIdler.this.revalidate(); - JMovingIdler.this.repaint(); - } - } - } - }; - - public void start() { - if (!moverThread.isAlive()) { - moverThread.start(); - } - running = true; - } - - public void stop() { - running = false; - } - - public void destroy() { - destroyed = true; - running = false; - try { - moverThread.join(); - } catch (InterruptedException e) {} - } - - protected void paintComponent(Graphics g) { - super.paintComponent(g); - Graphics2D g2 = (Graphics2D) g; - int w = this.getWidth(); - int h = this.getHeight(); - - g2.setColor(getBackground()); - g2.fillRect(0,0,w,h); - - int x = w * position / 100; - - Paint p = new GradientPaint(x - (w/8), 0, getBackground(), x , 0, getForeground()); - g2.setPaint(p); - g2.fillRect(Math.max(0,x-(w/8)),0, Math.min(x, w), h); + private static final long serialVersionUID = -2980521421870322717L; + + int position = 0; + boolean destroyed = false, running = false; + Thread moverThread = new Thread() { + public void run() { + while (!destroyed) { + boolean back = false; + while (running) { + if (back) { + position = --position % 100; + if (position == 0) { + back = false; + } + } else { + position = ++position % 100; + if (position == 99) { + back = true; + } + } + try { + sleep(10); + } catch (InterruptedException e) { + } + JMovingIdler.this.revalidate(); + JMovingIdler.this.repaint(); + } + } + } + }; + + public void start() { + if (!moverThread.isAlive()) { + moverThread.start(); + } + running = true; + } + + public void stop() { + running = false; + } + + public void destroy() { + destroyed = true; + running = false; + try { + moverThread.join(); + } catch (InterruptedException e) { + } + } + + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g; + int w = this.getWidth(); + int h = this.getHeight(); + + g2.setColor(getBackground()); + g2.fillRect(0, 0, w, h); + + int x = w * position / 100; + + Paint p = new GradientPaint(x - (w / 8), 0, getBackground(), x, 0, getForeground()); + g2.setPaint(p); + g2.fillRect(Math.max(0, x - (w / 8)), 0, Math.min(x, w), h); + + p = new GradientPaint(x, 0, getForeground(), x + (w / 8), 0, getBackground()); + g2.setPaint(p); + g2.fillRect(Math.max(0, x), 0, Math.min(x + (w / 8), w), h); + + g2.setColor(Color.BLACK); + g2.drawLine(0, 0, 0, h); + g2.drawLine(0, 0, w, 0); + g2.drawLine(w, 0, w, h); + g2.drawLine(0, h, w, h); + } + + @Override + public void setVisible(boolean aFlag) { + super.setVisible(aFlag); + if (!aFlag) destroy(); + } - p = new GradientPaint(x, 0, getForeground(), x + (w/8), 0, getBackground()); - g2.setPaint(p); - g2.fillRect(Math.max(0,x),0, Math.min(x+(w/8), w), h); - - g2.setColor(Color.BLACK); - g2.drawLine(0,0,0,h); - g2.drawLine(0,0,w,0); - g2.drawLine(w,0,w,h); - g2.drawLine(0,h,w,h); - } - - @Override - public void setVisible(boolean aFlag) { - super.setVisible(aFlag); - if (!aFlag) destroy(); - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/JSONCreationWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/JSONCreationWizard.java index aae3579..b6f0ade 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/JSONCreationWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/JSONCreationWizard.java @@ -1,9 +1,20 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Toolkit; +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameDataElement.State; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; +import com.gpl.rpg.atcontentstudio.ui.sprites.SpriteChooser; +import com.jidesoft.swing.JideBoxLayout; + +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.ListDataListener; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; @@ -11,589 +22,560 @@ import java.awt.event.ItemListener; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.ListDataListener; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameDataElement.State; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.sprites.SpriteChooser; -import com.jidesoft.swing.JideBoxLayout; - public class JSONCreationWizard extends JDialog { - private static final long serialVersionUID = -5744628699021314026L; - - public static enum DataType { - none, - actorCondition, - dialogue, - droplist, - item, - itemCategory, - npc, - quest - } - - private JSONElement creation = null; - final JLabel message; - @SuppressWarnings("rawtypes") - final JComboBox dataTypeCombo; - final JTextField idField; - final JTextField nameField; - final JButton ok; - final Project proj; - - public JSONCreationWizard(final Project proj, Class dataClass) { - this(proj); - if (dataClass == ActorCondition.class) { - dataTypeCombo.setSelectedItem(DataType.actorCondition); - } else if (dataClass == Dialogue.class) { - dataTypeCombo.setSelectedItem(DataType.dialogue); - } else if (dataClass == Droplist.class) { - dataTypeCombo.setSelectedItem(DataType.droplist); - } else if (dataClass == Item.class) { - dataTypeCombo.setSelectedItem(DataType.item); - } else if (dataClass == ItemCategory.class) { - dataTypeCombo.setSelectedItem(DataType.itemCategory); - } else if (dataClass == NPC.class) { - dataTypeCombo.setSelectedItem(DataType.npc); - } else if (dataClass == Quest.class) { - dataTypeCombo.setSelectedItem(DataType.quest); - } - dataTypeCombo.setEnabled(false); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public JSONCreationWizard(final Project proj) { - super(ATContentStudio.frame); - this.proj = proj; - setTitle("Create Game Data Element (JSON)"); - - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - pane.add(new JLabel("Create a new game data element."), JideBoxLayout.FIX); - - message = new JLabel("Select a data type below:"); - pane.add(message, JideBoxLayout.FIX); - - dataTypeCombo = new JComboBox(new DataTypeComboModel()); - dataTypeCombo.setRenderer(new DataTypeComboCellRenderer()); - pane.add(dataTypeCombo); - - final JPanel idPane = new JPanel(); - idPane.setLayout(new BorderLayout()); - JLabel idLabel = new JLabel("Internal ID: "); - idPane.add(idLabel, BorderLayout.WEST); - idField = new JTextField(""); - idField.setEditable(true); - idPane.add(idField, BorderLayout.CENTER); - pane.add(idPane, JideBoxLayout.FIX); - - final JPanel namePane = new JPanel(); - namePane.setLayout(new BorderLayout()); - JLabel nameLabel = new JLabel("Display name: "); - namePane.add(nameLabel, BorderLayout.WEST); - nameField = new JTextField(""); - nameField.setEditable(true); - namePane.add(nameField, BorderLayout.CENTER); - pane.add(namePane, JideBoxLayout.FIX); - - final JPanel iconPane = new JPanel(); - iconPane.setLayout(new BorderLayout()); - final JLabel iconLabel = new JLabel("Icon: "); - iconPane.add(iconLabel, BorderLayout.WEST); - final JButton iconButton = new JButton(new ImageIcon(DefaultIcons.getActorConditionImage())); - iconPane.add(iconButton, BorderLayout.CENTER); - pane.add(iconPane, JideBoxLayout.FIX); - iconPane.setVisible(true); - - dataTypeCombo.addItemListener(new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - idPane.setVisible(true); - switch ((DataType)e.getItem()) { - case actorCondition: - iconPane.setVisible(true); - namePane.setVisible(true); - iconButton.setIcon(new ImageIcon(DefaultIcons.getActorConditionImage())); - creation = new ActorCondition(); - break; - case dialogue: - iconPane.setVisible(false); - namePane.setVisible(false); - creation = new Dialogue(); - break; - case droplist: - iconPane.setVisible(false); - namePane.setVisible(false); - creation = new Droplist(); - break; - case item: - iconPane.setVisible(true); - namePane.setVisible(true); - creation = new Item(); - iconButton.setIcon(new ImageIcon(DefaultIcons.getItemImage())); - break; - case itemCategory: - iconPane.setVisible(false); - namePane.setVisible(true); - creation = new ItemCategory(); - break; - case npc: - iconPane.setVisible(true); - namePane.setVisible(true); - creation = new NPC(); - iconButton.setIcon(new ImageIcon(DefaultIcons.getNPCImage())); - break; - case quest: - iconPane.setVisible(false); - namePane.setVisible(true); - creation = new Quest(); - break; - default: - idPane.setVisible(false); - iconPane.setVisible(false); - namePane.setVisible(false); - creation = null; - break; - } - updateStatus(); - idPane.revalidate(); - namePane.revalidate(); - iconPane.revalidate(); - idPane.repaint(); - namePane.repaint(); - iconPane.repaint(); - } - } - }); - - iconButton.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - Spritesheet.Category cat = null; - switch ((DataType)dataTypeCombo.getSelectedItem()) { - case actorCondition: - cat = Spritesheet.Category.actorcondition; - break; - case dialogue: - break; - case droplist: - break; - case item: - cat = Spritesheet.Category.item; - break; - case itemCategory: - break; - case npc: - cat = Spritesheet.Category.monster; - break; - case quest: - break; - default: - break; - - } - if (cat == null) return; - SpriteChooser chooser = SpriteChooser.getChooser(proj, cat); - chooser.setSelectionListener(new SpriteChooser.SelectionListener() { - @Override - public void iconSelected(String selected) { - if (selected != null) { - switch ((DataType)dataTypeCombo.getSelectedItem()) { - case actorCondition: - ((ActorCondition)creation).icon_id = selected; - break; - case item: - ((Item)creation).icon_id = selected; - break; - case npc: - ((NPC)creation).icon_id = selected; - break; - case dialogue: - case droplist: - case itemCategory: - case quest: - default: - break; - - } - iconButton.setIcon(new ImageIcon(proj.getImage(selected))); - iconButton.revalidate(); - iconButton.repaint(); - updateStatus(); - } - } - }); - chooser.setVisible(true); - } - }); - - pane.add(new JPanel(), JideBoxLayout.VARY); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancel = new JButton("Cancel"); - buttonPane.add(cancel, JideBoxLayout.FIX); - ok = new JButton("Ok"); - buttonPane.add(ok, JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - switch ((DataType)dataTypeCombo.getSelectedItem()) { - case actorCondition: - ((ActorCondition)creation).display_name = nameField.getText(); - break; - case item: - ((Item)creation).name = nameField.getText(); - break; - case npc: - ((NPC)creation).name = nameField.getText(); - break; - case dialogue: - case droplist: - break; - case itemCategory: - ((ItemCategory)creation).name = nameField.getText(); - break; - case quest: - ((Quest)creation).name = nameField.getText(); - break; - default: - return; - } - creation.id = idField.getText(); - JSONCreationWizard.this.setVisible(false); - JSONCreationWizard.this.dispose(); - creation.state = State.created; - proj.createElement(creation); - notifyCreated(); - ATContentStudio.frame.selectInTree(creation); - ATContentStudio.frame.openEditor(creation); - } - }); - - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - creation = null; - JSONCreationWizard.this.setVisible(false); - JSONCreationWizard.this.dispose(); - } - }); - - DocumentListener statusUpdater = new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void insertUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void changedUpdate(DocumentEvent e) { - updateStatus(); - } - }; - idField.getDocument().addDocumentListener(statusUpdater); - nameField.getDocument().addDocumentListener(statusUpdater); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - setMinimumSize(new Dimension(350,250)); - idPane.setVisible(false); - iconPane.setVisible(false); - namePane.setVisible(false); - updateStatus(); - pack(); - - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - } - - public void updateStatus() { - boolean trouble = false; - message.setText("Looks OK to me."); - if (creation == null) { - message.setText("Select a data type below:"); - trouble = true; - } else if (idField.getText() == null || idField.getText().length() <= 0) { - message.setText("Internal ID must not be empty."); - trouble = true; - } else { - switch ((DataType)dataTypeCombo.getSelectedItem()) { - case actorCondition: - if(nameField.getText() == null || nameField.getText().length() <= 0) { - message.setText("An actor condition must have a name."); - trouble = true; - } else if (((ActorCondition)creation).icon_id == null) { - message.setText("An actor condition must have an icon."); - trouble = true; - } else if (proj.getActorCondition(idField.getText()) != null) { - if (proj.getActorCondition(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("An actor condition with the same ID was already created in this project."); - trouble = true; - } else if (proj.getActorCondition(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("An actor condition with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getActorCondition(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("An actor condition with the same ID exists in the game. It will be added under \"altered\"."); - } - } - break; - case item: - if(nameField.getText() == null || nameField.getText().length() <= 0) { - message.setText("An item must have a name."); - trouble = true; - } else if (((Item)creation).icon_id == null) { - message.setText("An item must have an icon."); - trouble = true; - } else if (proj.getItem(idField.getText()) != null) { - if (proj.getItem(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("An item with the same ID was already created in this project."); - trouble = true; - } else if (proj.getItem(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("An item with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getItem(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("An item with the same ID exists in the game. It will be added under \"altered\"."); - } - } - break; - case npc: - if(nameField.getText() == null || nameField.getText().length() <= 0) { - message.setText("A NPC must have a name."); - trouble = true; - } else if (((NPC)creation).icon_id == null) { - message.setText("A NPC must have an icon."); - trouble = true; - } else if (proj.getNPC(idField.getText()) != null) { - if (proj.getNPC(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("A NPC with the same ID was already created in this project."); - trouble = true; - } else if (proj.getNPC(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("A NPC with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getNPC(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("A NPC with the same ID exists in the game. It will be added under \"altered\"."); - } - } - break; - case dialogue: - if (proj.getDialogue(idField.getText()) != null) { - if (proj.getDialogue(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("A dialogue with the same ID was already created in this project."); - trouble = true; - } else if (proj.getDialogue(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("A dialogue with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getDialogue(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("A dialogue with the same ID exists in the game. It will be added under \"altered\"."); - } - } - break; - case droplist: - if (proj.getDroplist(idField.getText()) != null) { - if (proj.getDroplist(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("A droplist with the same ID was already created in this project."); - trouble = true; - } else if (proj.getDroplist(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("A droplist with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getDroplist(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("A droplist with the same ID exists in the game. It will be added under \"altered\"."); - } - } - break; - case itemCategory: - if(nameField.getText() == null || nameField.getText().length() <= 0) { - message.setText("An item category must have a name."); - trouble = true; - } else if (proj.getItemCategory(idField.getText()) != null) { - if (proj.getItemCategory(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("An item category with the same ID was already created in this project."); - trouble = true; - } else if (proj.getItemCategory(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("An item category with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getItemCategory(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("An item category with the same ID exists in the game. It will be added under \"altered\"."); - } - } - break; - case quest: - if(nameField.getText() == null || nameField.getText().length() <= 0) { - message.setText("A quest must have a name."); - trouble = true; - } else if (proj.getQuest(idField.getText()) != null) { - if (proj.getQuest(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("A quest with the same ID was already created in this project."); - trouble = true; - } else if (proj.getQuest(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("A quest with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getQuest(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("A quest with the same ID exists in the game. It will be added under \"altered\"."); - } - } - break; - default: - break; - } - } - - ok.setEnabled(!trouble); - - message.revalidate(); - message.repaint(); - } - - public static String dataTypeDesc(DataType type) { - switch (type) { - case actorCondition: - return "Actor Condition"; - case dialogue: - return "Dialogue"; - case droplist: - return "Droplist"; - case item: - return "Item"; - case itemCategory: - return "Item Category"; - case npc: - return "NPC"; - case quest: - return "Quest"; - default: - return "Select below"; - } - } - - @SuppressWarnings("rawtypes") - public static class DataTypeComboModel implements ComboBoxModel { + private static final long serialVersionUID = -5744628699021314026L; - DataType selected = DataType.none; - - @Override - public int getSize() { - return DataType.values().length; - } + public static enum DataType { + none, + actorCondition, + dialogue, + droplist, + item, + itemCategory, + npc, + quest + } - @Override - public Object getElementAt(int index) { - return DataType.values()[index]; - } + private JSONElement creation = null; + final JLabel message; + @SuppressWarnings("rawtypes") + final JComboBox dataTypeCombo; + final JTextField idField; + final JTextField nameField; + final JButton ok; + final Project proj; - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } + public JSONCreationWizard(final Project proj, Class dataClass) { + this(proj); + if (dataClass == ActorCondition.class) { + dataTypeCombo.setSelectedItem(DataType.actorCondition); + } else if (dataClass == Dialogue.class) { + dataTypeCombo.setSelectedItem(DataType.dialogue); + } else if (dataClass == Droplist.class) { + dataTypeCombo.setSelectedItem(DataType.droplist); + } else if (dataClass == Item.class) { + dataTypeCombo.setSelectedItem(DataType.item); + } else if (dataClass == ItemCategory.class) { + dataTypeCombo.setSelectedItem(DataType.itemCategory); + } else if (dataClass == NPC.class) { + dataTypeCombo.setSelectedItem(DataType.npc); + } else if (dataClass == Quest.class) { + dataTypeCombo.setSelectedItem(DataType.quest); + } + dataTypeCombo.setEnabled(false); + } - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } + @SuppressWarnings({"unchecked", "rawtypes"}) + public JSONCreationWizard(final Project proj) { + super(ATContentStudio.frame); + this.proj = proj; + setTitle("Create Game Data Element (JSON)"); - @Override - public void setSelectedItem(Object anItem) { - selected = (DataType) anItem; - } + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - @Override - public Object getSelectedItem() { - return selected; - } - } - - public static class DataTypeComboCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 5621373849299980998L; + pane.add(new JLabel("Create a new game data element."), JideBoxLayout.FIX); - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - ((JLabel)c).setText(JSONCreationWizard.dataTypeDesc((DataType) value)); - switch ((DataType)value) { - case actorCondition: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getActorConditionIcon())); - break; - case dialogue: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getDialogueIcon())); - break; - case droplist: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); - break; - case item: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getItemIcon())); - break; - case itemCategory: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); - break; - case npc: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); - break; - case quest: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getQuestIcon())); - break; - default: - break; - - } - } - return c; - } - } + message = new JLabel("Select a data type below:"); + pane.add(message, JideBoxLayout.FIX); + + dataTypeCombo = new JComboBox(new DataTypeComboModel()); + dataTypeCombo.setRenderer(new DataTypeComboCellRenderer()); + pane.add(dataTypeCombo); + + final JPanel idPane = new JPanel(); + idPane.setLayout(new BorderLayout()); + JLabel idLabel = new JLabel("Internal ID: "); + idPane.add(idLabel, BorderLayout.WEST); + idField = new JTextField(""); + idField.setEditable(true); + idPane.add(idField, BorderLayout.CENTER); + pane.add(idPane, JideBoxLayout.FIX); + + final JPanel namePane = new JPanel(); + namePane.setLayout(new BorderLayout()); + JLabel nameLabel = new JLabel("Display name: "); + namePane.add(nameLabel, BorderLayout.WEST); + nameField = new JTextField(""); + nameField.setEditable(true); + namePane.add(nameField, BorderLayout.CENTER); + pane.add(namePane, JideBoxLayout.FIX); + + final JPanel iconPane = new JPanel(); + iconPane.setLayout(new BorderLayout()); + final JLabel iconLabel = new JLabel("Icon: "); + iconPane.add(iconLabel, BorderLayout.WEST); + final JButton iconButton = new JButton(new ImageIcon(DefaultIcons.getActorConditionImage())); + iconPane.add(iconButton, BorderLayout.CENTER); + pane.add(iconPane, JideBoxLayout.FIX); + iconPane.setVisible(true); + + dataTypeCombo.addItemListener(new ItemListener() { + + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + idPane.setVisible(true); + switch ((DataType) e.getItem()) { + case actorCondition: + iconPane.setVisible(true); + namePane.setVisible(true); + iconButton.setIcon(new ImageIcon(DefaultIcons.getActorConditionImage())); + creation = new ActorCondition(); + break; + case dialogue: + iconPane.setVisible(false); + namePane.setVisible(false); + creation = new Dialogue(); + break; + case droplist: + iconPane.setVisible(false); + namePane.setVisible(false); + creation = new Droplist(); + break; + case item: + iconPane.setVisible(true); + namePane.setVisible(true); + creation = new Item(); + iconButton.setIcon(new ImageIcon(DefaultIcons.getItemImage())); + break; + case itemCategory: + iconPane.setVisible(false); + namePane.setVisible(true); + creation = new ItemCategory(); + break; + case npc: + iconPane.setVisible(true); + namePane.setVisible(true); + creation = new NPC(); + iconButton.setIcon(new ImageIcon(DefaultIcons.getNPCImage())); + break; + case quest: + iconPane.setVisible(false); + namePane.setVisible(true); + creation = new Quest(); + break; + default: + idPane.setVisible(false); + iconPane.setVisible(false); + namePane.setVisible(false); + creation = null; + break; + } + updateStatus(); + idPane.revalidate(); + namePane.revalidate(); + iconPane.revalidate(); + idPane.repaint(); + namePane.repaint(); + iconPane.repaint(); + } + } + }); + + iconButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + Spritesheet.Category cat = null; + switch ((DataType) dataTypeCombo.getSelectedItem()) { + case actorCondition: + cat = Spritesheet.Category.actorcondition; + break; + case dialogue: + break; + case droplist: + break; + case item: + cat = Spritesheet.Category.item; + break; + case itemCategory: + break; + case npc: + cat = Spritesheet.Category.monster; + break; + case quest: + break; + default: + break; + + } + if (cat == null) return; + SpriteChooser chooser = SpriteChooser.getChooser(proj, cat); + chooser.setSelectionListener(new SpriteChooser.SelectionListener() { + @Override + public void iconSelected(String selected) { + if (selected != null) { + switch ((DataType) dataTypeCombo.getSelectedItem()) { + case actorCondition: + ((ActorCondition) creation).icon_id = selected; + break; + case item: + ((Item) creation).icon_id = selected; + break; + case npc: + ((NPC) creation).icon_id = selected; + break; + case dialogue: + case droplist: + case itemCategory: + case quest: + default: + break; + + } + iconButton.setIcon(new ImageIcon(proj.getImage(selected))); + iconButton.revalidate(); + iconButton.repaint(); + updateStatus(); + } + } + }); + chooser.setVisible(true); + } + }); + + pane.add(new JPanel(), JideBoxLayout.VARY); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancel = new JButton("Cancel"); + buttonPane.add(cancel, JideBoxLayout.FIX); + ok = new JButton("Ok"); + buttonPane.add(ok, JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + + ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + switch ((DataType) dataTypeCombo.getSelectedItem()) { + case actorCondition: + ((ActorCondition) creation).display_name = nameField.getText(); + break; + case item: + ((Item) creation).name = nameField.getText(); + break; + case npc: + ((NPC) creation).name = nameField.getText(); + break; + case dialogue: + case droplist: + break; + case itemCategory: + ((ItemCategory) creation).name = nameField.getText(); + break; + case quest: + ((Quest) creation).name = nameField.getText(); + break; + default: + return; + } + creation.id = idField.getText(); + JSONCreationWizard.this.setVisible(false); + JSONCreationWizard.this.dispose(); + creation.state = State.created; + proj.createElement(creation); + notifyCreated(); + ATContentStudio.frame.selectInTree(creation); + ATContentStudio.frame.openEditor(creation); + } + }); + + cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + creation = null; + JSONCreationWizard.this.setVisible(false); + JSONCreationWizard.this.dispose(); + } + }); + + DocumentListener statusUpdater = new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateStatus(); + } + }; + idField.getDocument().addDocumentListener(statusUpdater); + nameField.getDocument().addDocumentListener(statusUpdater); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + setMinimumSize(new Dimension(350, 250)); + idPane.setVisible(false); + iconPane.setVisible(false); + namePane.setVisible(false); + updateStatus(); + pack(); + + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + } + + public void updateStatus() { + boolean trouble = false; + message.setText("Looks OK to me."); + if (creation == null) { + message.setText("Select a data type below:"); + trouble = true; + } else if (idField.getText() == null || idField.getText().length() <= 0) { + message.setText("Internal ID must not be empty."); + trouble = true; + } else { + switch ((DataType) dataTypeCombo.getSelectedItem()) { + case actorCondition: + if (nameField.getText() == null || nameField.getText().length() <= 0) { + message.setText("An actor condition must have a name."); + trouble = true; + } else if (((ActorCondition) creation).icon_id == null) { + message.setText("An actor condition must have an icon."); + trouble = true; + } else if (proj.getActorCondition(idField.getText()) != null) { + if (proj.getActorCondition(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("An actor condition with the same ID was already created in this project."); + trouble = true; + } else if (proj.getActorCondition(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("An actor condition with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getActorCondition(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("An actor condition with the same ID exists in the game. It will be added under \"altered\"."); + } + } + break; + case item: + if (nameField.getText() == null || nameField.getText().length() <= 0) { + message.setText("An item must have a name."); + trouble = true; + } else if (((Item) creation).icon_id == null) { + message.setText("An item must have an icon."); + trouble = true; + } else if (proj.getItem(idField.getText()) != null) { + if (proj.getItem(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("An item with the same ID was already created in this project."); + trouble = true; + } else if (proj.getItem(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("An item with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getItem(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("An item with the same ID exists in the game. It will be added under \"altered\"."); + } + } + break; + case npc: + if (nameField.getText() == null || nameField.getText().length() <= 0) { + message.setText("A NPC must have a name."); + trouble = true; + } else if (((NPC) creation).icon_id == null) { + message.setText("A NPC must have an icon."); + trouble = true; + } else if (proj.getNPC(idField.getText()) != null) { + if (proj.getNPC(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("A NPC with the same ID was already created in this project."); + trouble = true; + } else if (proj.getNPC(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("A NPC with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getNPC(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("A NPC with the same ID exists in the game. It will be added under \"altered\"."); + } + } + break; + case dialogue: + if (proj.getDialogue(idField.getText()) != null) { + if (proj.getDialogue(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("A dialogue with the same ID was already created in this project."); + trouble = true; + } else if (proj.getDialogue(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("A dialogue with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getDialogue(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("A dialogue with the same ID exists in the game. It will be added under \"altered\"."); + } + } + break; + case droplist: + if (proj.getDroplist(idField.getText()) != null) { + if (proj.getDroplist(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("A droplist with the same ID was already created in this project."); + trouble = true; + } else if (proj.getDroplist(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("A droplist with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getDroplist(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("A droplist with the same ID exists in the game. It will be added under \"altered\"."); + } + } + break; + case itemCategory: + if (nameField.getText() == null || nameField.getText().length() <= 0) { + message.setText("An item category must have a name."); + trouble = true; + } else if (proj.getItemCategory(idField.getText()) != null) { + if (proj.getItemCategory(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("An item category with the same ID was already created in this project."); + trouble = true; + } else if (proj.getItemCategory(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("An item category with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getItemCategory(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("An item category with the same ID exists in the game. It will be added under \"altered\"."); + } + } + break; + case quest: + if (nameField.getText() == null || nameField.getText().length() <= 0) { + message.setText("A quest must have a name."); + trouble = true; + } else if (proj.getQuest(idField.getText()) != null) { + if (proj.getQuest(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("A quest with the same ID was already created in this project."); + trouble = true; + } else if (proj.getQuest(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("A quest with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getQuest(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("A quest with the same ID exists in the game. It will be added under \"altered\"."); + } + } + break; + default: + break; + } + } + + ok.setEnabled(!trouble); + + message.revalidate(); + message.repaint(); + } + + public static String dataTypeDesc(DataType type) { + switch (type) { + case actorCondition: + return "Actor Condition"; + case dialogue: + return "Dialogue"; + case droplist: + return "Droplist"; + case item: + return "Item"; + case itemCategory: + return "Item Category"; + case npc: + return "NPC"; + case quest: + return "Quest"; + default: + return "Select below"; + } + } + + @SuppressWarnings("rawtypes") + public static class DataTypeComboModel implements ComboBoxModel { + + DataType selected = DataType.none; + + @Override + public int getSize() { + return DataType.values().length; + } + + @Override + public Object getElementAt(int index) { + return DataType.values()[index]; + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addListDataListener(ListDataListener l) { + listeners.add(l); + } + + @Override + public void removeListDataListener(ListDataListener l) { + listeners.remove(l); + } + + @Override + public void setSelectedItem(Object anItem) { + selected = (DataType) anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + } + + public static class DataTypeComboCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 5621373849299980998L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + ((JLabel) c).setText(JSONCreationWizard.dataTypeDesc((DataType) value)); + switch ((DataType) value) { + case actorCondition: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getActorConditionIcon())); + break; + case dialogue: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getDialogueIcon())); + break; + case droplist: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); + break; + case item: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getItemIcon())); + break; + case itemCategory: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); + break; + case npc: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); + break; + case quest: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getQuestIcon())); + break; + default: + break; + + } + } + return c; + } + } + + public static interface CreationCompletedListener { + public void elementCreated(JSONElement created); + } + + private List listeners = new CopyOnWriteArrayList(); + + public void addCreationListener(CreationCompletedListener l) { + listeners.add(l); + } + + public void notifyCreated() { + for (CreationCompletedListener l : listeners) { + l.elementCreated(creation); + } + } - public static interface CreationCompletedListener { - public void elementCreated(JSONElement created); - } - - private List listeners = new CopyOnWriteArrayList(); - - public void addCreationListener(CreationCompletedListener l) { - listeners.add(l); - } - - public void notifyCreated() { - for (CreationCompletedListener l : listeners) { - l.elementCreated(creation); - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java index a391382..1bacd9d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/JSONImportWizard.java @@ -1,9 +1,22 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Toolkit; +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.jidesoft.swing.JideBoxLayout; +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.ListDataListener; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; @@ -18,687 +31,652 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; -import javax.swing.ButtonGroup; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.ListModel; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; - -import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; -import org.fife.ui.rsyntaxtextarea.SyntaxConstants; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.jidesoft.swing.JideBoxLayout; - public class JSONImportWizard extends JDialog { - private static final long serialVersionUID = 661234868711700156L; + private static final long serialVersionUID = 661234868711700156L; - public static enum DataType { - none, - actorCondition, - dialogue, - droplist, - item, - itemCategory, - npc, - quest - } - - Project proj; - - JPanel pane; - JLabel message; - @SuppressWarnings("rawtypes") - JComboBox dataTypeCombo; - JRadioButton importFromFile; - JRadioButton importPasted; - JPanel fileSelectionPane; - JTextField jsonFileName; - JButton browse; - RSyntaxTextArea jsonPasteArea; - JScrollPane scroller; - @SuppressWarnings("rawtypes") - JList createdPreview; - JPanel buttonPane; - JButton ok, cancel; - ActionListener okListener, cancelListener; - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public JSONImportWizard(Project proj) { + public static enum DataType { + none, + actorCondition, + dialogue, + droplist, + item, + itemCategory, + npc, + quest + } - super(ATContentStudio.frame); - setTitle("Import data from JSON"); - - this.proj = proj; - - pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - pane.add(new JLabel("Import data in JSON format."), JideBoxLayout.FIX); - - message = new JLabel(); - - dataTypeCombo = new JComboBox(new DataTypeComboModel()); - dataTypeCombo.setRenderer(new DataTypeComboCellRenderer()); - - dataTypeCombo.addItemListener(new ItemListener() { - - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - checkEnableNext(); - } - } - }); + Project proj; - importPasted = new JRadioButton("Paste JSON text"); - importFromFile = new JRadioButton("Select .json file"); - importPasted.setSelected(true); - ButtonGroup radioGroup = new ButtonGroup(); - radioGroup.add(importPasted); - radioGroup.add(importFromFile); - - importPasted.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (importPasted.isSelected()) { - scroller.setVisible(true); - fileSelectionPane.setVisible(false); - pane.revalidate(); - pane.repaint(); - } - } - }); - importFromFile.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (importFromFile.isSelected()) { - scroller.setVisible(false); - fileSelectionPane.setVisible(true); - pane.revalidate(); - pane.repaint(); - } - } - }); - - jsonFileName = new JTextField(); - jsonFileName.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - checkEnableNext(); - } - @Override - public void insertUpdate(DocumentEvent e) { - checkEnableNext(); - } - @Override - public void changedUpdate(DocumentEvent e) { - checkEnableNext(); - } - }); - browse = new JButton("Browse"); - browse.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser jfc = new JFileChooser(){ - private static final long serialVersionUID = -3001082967957619011L; - @Override - public boolean accept(File f) { - if (f.isDirectory() || f.getName().endsWith(".json") || f.getName().endsWith(".JSON")) { - return super.accept(f); - } else { - return false; - } - } - }; - jfc.setMultiSelectionEnabled(false); - int result = jfc.showOpenDialog(ATContentStudio.frame); - if (result == JFileChooser.APPROVE_OPTION) { - jsonFileName.setText(jfc.getSelectedFile().getAbsolutePath()); - checkEnableNext(); - } - } - }); - fileSelectionPane = new JPanel(); - fileSelectionPane.setLayout(new JideBoxLayout(fileSelectionPane, JideBoxLayout.LINE_AXIS, 6)); - fileSelectionPane.add(new JLabel("JSON File: "), JideBoxLayout.FIX); - fileSelectionPane.add(jsonFileName, JideBoxLayout.VARY); - fileSelectionPane.add(browse, JideBoxLayout.FIX); - - jsonPasteArea = new RSyntaxTextArea(); - jsonPasteArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JSON); - - jsonPasteArea.getDocument().addDocumentListener(new DocumentListener() { - - @Override - public void removeUpdate(DocumentEvent e) { - checkEnableNext(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - checkEnableNext(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - checkEnableNext(); - } - - }); - - - - - buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - cancel = new JButton("Cancel"); - buttonPane.add(cancel, JideBoxLayout.FIX); - ok = new JButton("Next"); - buttonPane.add(ok, JideBoxLayout.FIX); + JPanel pane; + JLabel message; + @SuppressWarnings("rawtypes") + JComboBox dataTypeCombo; + JRadioButton importFromFile; + JRadioButton importPasted; + JPanel fileSelectionPane; + JTextField jsonFileName; + JButton browse; + RSyntaxTextArea jsonPasteArea; + JScrollPane scroller; + @SuppressWarnings("rawtypes") + JList createdPreview; + JPanel buttonPane; + JButton ok, cancel; + ActionListener okListener, cancelListener; - createdPreview = new JList(new GDEListModel(new ArrayList())); - - showFirstScreen(); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - setMinimumSize(new Dimension(450,350)); - pack(); - - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - - } + @SuppressWarnings({"rawtypes", "unchecked"}) + public JSONImportWizard(Project proj) { - private void showFirstScreen() { - pane.removeAll(); - message.setText("Select a data type & paste your JSON data below:"); - pane.add(message, JideBoxLayout.FIX); - pane.add(dataTypeCombo, JideBoxLayout.FIX); - pane.add(importPasted, JideBoxLayout.FIX); - pane.add(importFromFile, JideBoxLayout.FIX); - pane.add(fileSelectionPane, JideBoxLayout.FIX); - scroller = new JScrollPane(jsonPasteArea); - scroller.getVerticalScrollBar().setUnitIncrement(16); - JPanel scrollHolder = new JPanel(); - scrollHolder.setLayout(new BorderLayout()); - scrollHolder.add(scroller, BorderLayout.CENTER); - pane.add(scrollHolder, JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - ok.setText("Next"); - ok.setEnabled(jsonPasteArea.getText() != null && jsonPasteArea.getText().length() > 0 && dataTypeCombo.getSelectedItem() != null && dataTypeCombo.getSelectedItem() != DataType.none); - ok.removeActionListener(okListener); - okListener = new ActionListener() { - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void actionPerformed(ActionEvent e) { - List errors = new ArrayList(); - List warnings = new ArrayList(); - List created = new ArrayList(); - Object jsonParserOutput = null; - try { - if (importPasted.isSelected()) { - jsonParserOutput = new JSONParser().parse(jsonPasteArea.getText()); - } else if (importFromFile.isSelected()) { - jsonParserOutput = new JSONParser().parse(new FileReader(new File(jsonFileName.getText()))); - } - } catch (ParseException e1) { - errors.add("Invalid JSON content: "+e1.getMessage()); - } catch (FileNotFoundException e1) { - errors.add("Unable to access file: "+e1.getMessage()); - } catch (IOException e1) { - errors.add("Error while accessing file: "+e1.getMessage()); - } - if (jsonParserOutput != null) { - List jsonObjects = null; - if (jsonParserOutput instanceof List) { - jsonObjects = (List)jsonParserOutput; - } else if (jsonParserOutput instanceof Map) { - jsonObjects = new ArrayList(); - jsonObjects.add((Map) jsonParserOutput); - } else { - errors.add("Invalid JSON content: neither an array nor an object."); - } - if (jsonObjects != null) { - JSONElement node; - JSONElement existingNode; - int i = 0; - for (Map jsonObject : jsonObjects) { - switch ((DataType)dataTypeCombo.getSelectedItem()) { - case actorCondition: - node = ActorCondition.fromJson(jsonObject); - existingNode = proj.getActorCondition(node.id); - break; - case item: - node = Item.fromJson(jsonObject); - existingNode = proj.getItem(node.id); - break; - case npc: - node = NPC.fromJson(jsonObject); - existingNode = proj.getNPC(node.id); - break; - case dialogue: - node = Dialogue.fromJson(jsonObject); - existingNode = proj.getDialogue(node.id); - break; - case droplist: - node = Droplist.fromJson(jsonObject); - existingNode = proj.getDroplist(node.id); - break; - case itemCategory: - node = ItemCategory.fromJson(jsonObject); - existingNode = proj.getItemCategory(node.id); - break; - case quest: - node = Quest.fromJson(jsonObject); - existingNode = proj.getQuest(node.id); - break; - default: - return; - } - i++; - if (node instanceof JSONElement) { - node.parse(jsonObject); - created.add(node); - if (existingNode != null) { - if (existingNode.getDataType() == GameSource.Type.created) { - errors.add("An item with id "+node.id+" is already created in this project."); - } else if (existingNode.getDataType() == GameSource.Type.altered) { - errors.add("An item with id "+node.id+" is already altered in this project."); - } else { - node.jsonFile = existingNode.jsonFile; - warnings.add("An item with id "+node.id+" exists in the used game source. This one will be inserted as \"altered\""); - } + super(ATContentStudio.frame); + setTitle("Import data from JSON"); + + this.proj = proj; + + pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + + pane.add(new JLabel("Import data in JSON format."), JideBoxLayout.FIX); + + message = new JLabel(); + + dataTypeCombo = new JComboBox(new DataTypeComboModel()); + dataTypeCombo.setRenderer(new DataTypeComboCellRenderer()); + + dataTypeCombo.addItemListener(new ItemListener() { + + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + checkEnableNext(); + } + } + }); + + importPasted = new JRadioButton("Paste JSON text"); + importFromFile = new JRadioButton("Select .json file"); + importPasted.setSelected(true); + ButtonGroup radioGroup = new ButtonGroup(); + radioGroup.add(importPasted); + radioGroup.add(importFromFile); + + importPasted.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (importPasted.isSelected()) { + scroller.setVisible(true); + fileSelectionPane.setVisible(false); + pane.revalidate(); + pane.repaint(); + } + } + }); + importFromFile.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (importFromFile.isSelected()) { + scroller.setVisible(false); + fileSelectionPane.setVisible(true); + pane.revalidate(); + pane.repaint(); + } + } + }); + + jsonFileName = new JTextField(); + jsonFileName.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + checkEnableNext(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + checkEnableNext(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + checkEnableNext(); + } + }); + browse = new JButton("Browse"); + browse.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JFileChooser jfc = new JFileChooser() { + private static final long serialVersionUID = -3001082967957619011L; + + @Override + public boolean accept(File f) { + if (f.isDirectory() || f.getName().endsWith(".json") || f.getName().endsWith(".JSON")) { + return super.accept(f); + } else { + return false; + } + } + }; + jfc.setMultiSelectionEnabled(false); + int result = jfc.showOpenDialog(ATContentStudio.frame); + if (result == JFileChooser.APPROVE_OPTION) { + jsonFileName.setText(jfc.getSelectedFile().getAbsolutePath()); + checkEnableNext(); + } + } + }); + fileSelectionPane = new JPanel(); + fileSelectionPane.setLayout(new JideBoxLayout(fileSelectionPane, JideBoxLayout.LINE_AXIS, 6)); + fileSelectionPane.add(new JLabel("JSON File: "), JideBoxLayout.FIX); + fileSelectionPane.add(jsonFileName, JideBoxLayout.VARY); + fileSelectionPane.add(browse, JideBoxLayout.FIX); + + jsonPasteArea = new RSyntaxTextArea(); + jsonPasteArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JSON); + + jsonPasteArea.getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void removeUpdate(DocumentEvent e) { + checkEnableNext(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + checkEnableNext(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + checkEnableNext(); + } + + }); + + + buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + cancel = new JButton("Cancel"); + buttonPane.add(cancel, JideBoxLayout.FIX); + ok = new JButton("Next"); + buttonPane.add(ok, JideBoxLayout.FIX); + + createdPreview = new JList(new GDEListModel(new ArrayList())); + + showFirstScreen(); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + setMinimumSize(new Dimension(450, 350)); + pack(); + + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + + } + + private void showFirstScreen() { + pane.removeAll(); + message.setText("Select a data type & paste your JSON data below:"); + pane.add(message, JideBoxLayout.FIX); + pane.add(dataTypeCombo, JideBoxLayout.FIX); + pane.add(importPasted, JideBoxLayout.FIX); + pane.add(importFromFile, JideBoxLayout.FIX); + pane.add(fileSelectionPane, JideBoxLayout.FIX); + scroller = new JScrollPane(jsonPasteArea); + scroller.getVerticalScrollBar().setUnitIncrement(16); + JPanel scrollHolder = new JPanel(); + scrollHolder.setLayout(new BorderLayout()); + scrollHolder.add(scroller, BorderLayout.CENTER); + pane.add(scrollHolder, JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + ok.setText("Next"); + ok.setEnabled(jsonPasteArea.getText() != null && jsonPasteArea.getText().length() > 0 && dataTypeCombo.getSelectedItem() != null && dataTypeCombo.getSelectedItem() != DataType.none); + ok.removeActionListener(okListener); + okListener = new ActionListener() { + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void actionPerformed(ActionEvent e) { + List errors = new ArrayList(); + List warnings = new ArrayList(); + List created = new ArrayList(); + Object jsonParserOutput = null; + try { + if (importPasted.isSelected()) { + jsonParserOutput = new JSONParser().parse(jsonPasteArea.getText()); + } else if (importFromFile.isSelected()) { + jsonParserOutput = new JSONParser().parse(new FileReader(new File(jsonFileName.getText()))); + } + } catch (ParseException e1) { + errors.add("Invalid JSON content: " + e1.getMessage()); + } catch (FileNotFoundException e1) { + errors.add("Unable to access file: " + e1.getMessage()); + } catch (IOException e1) { + errors.add("Error while accessing file: " + e1.getMessage()); + } + if (jsonParserOutput != null) { + List jsonObjects = null; + if (jsonParserOutput instanceof List) { + jsonObjects = (List) jsonParserOutput; + } else if (jsonParserOutput instanceof Map) { + jsonObjects = new ArrayList(); + jsonObjects.add((Map) jsonParserOutput); + } else { + errors.add("Invalid JSON content: neither an array nor an object."); + } + if (jsonObjects != null) { + JSONElement node; + JSONElement existingNode; + int i = 0; + for (Map jsonObject : jsonObjects) { + switch ((DataType) dataTypeCombo.getSelectedItem()) { + case actorCondition: + node = ActorCondition.fromJson(jsonObject); + existingNode = proj.getActorCondition(node.id); + break; + case item: + node = Item.fromJson(jsonObject); + existingNode = proj.getItem(node.id); + break; + case npc: + node = NPC.fromJson(jsonObject); + existingNode = proj.getNPC(node.id); + break; + case dialogue: + node = Dialogue.fromJson(jsonObject); + existingNode = proj.getDialogue(node.id); + break; + case droplist: + node = Droplist.fromJson(jsonObject); + existingNode = proj.getDroplist(node.id); + break; + case itemCategory: + node = ItemCategory.fromJson(jsonObject); + existingNode = proj.getItemCategory(node.id); + break; + case quest: + node = Quest.fromJson(jsonObject); + existingNode = proj.getQuest(node.id); + break; + default: + return; + } + i++; + if (node instanceof JSONElement) { + node.parse(jsonObject); + created.add(node); + if (existingNode != null) { + if (existingNode.getDataType() == GameSource.Type.created) { + errors.add("An item with id " + node.id + " is already created in this project."); + } else if (existingNode.getDataType() == GameSource.Type.altered) { + errors.add("An item with id " + node.id + " is already altered in this project."); + } else { + node.jsonFile = existingNode.jsonFile; + warnings.add("An item with id " + node.id + " exists in the used game source. This one will be inserted as \"altered\""); + } } } else { - warnings.add("Failed to load element #"+i); - } - } - } - } - if (errors.isEmpty() && warnings.isEmpty()) { - showImportPreviewScreen(created); - } else if (!errors.isEmpty()) { - showErrorScreen(errors); - } else { - showWarningScreen(warnings, created); - } - } - }; - ok.addActionListener(okListener); - cancel.setText("Cancel"); - cancel.removeActionListener(cancelListener); - cancelListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JSONImportWizard.this.setVisible(false); - JSONImportWizard.this.dispose(); - } - }; - cancel.addActionListener(cancelListener); - if (importPasted.isSelected()) { - scroller.setVisible(true); - fileSelectionPane.setVisible(false); - pane.revalidate(); - pane.repaint(); - } else if (importFromFile.isSelected()) { - scroller.setVisible(false); - fileSelectionPane.setVisible(true); - pane.revalidate(); - pane.repaint(); - } - pane.revalidate(); - pane.repaint(); - } - - private void checkEnableNext() { - if (dataTypeCombo.getSelectedItem() != null && dataTypeCombo.getSelectedItem() != DataType.none) { - if (importPasted.isSelected()) { - ok.setEnabled(jsonPasteArea.getText() != null && jsonPasteArea.getText().length() > 0); - } else if (importFromFile.isSelected()) { - ok.setEnabled(jsonFileName.getText() != null && jsonFileName.getText().length() > 0 && new File(jsonFileName.getText()).exists() && !(new File(jsonFileName.getText()).isDirectory())); - } - } - } + warnings.add("Failed to load element #" + i); + } + } + } + } + if (errors.isEmpty() && warnings.isEmpty()) { + showImportPreviewScreen(created); + } else if (!errors.isEmpty()) { + showErrorScreen(errors); + } else { + showWarningScreen(warnings, created); + } + } + }; + ok.addActionListener(okListener); + cancel.setText("Cancel"); + cancel.removeActionListener(cancelListener); + cancelListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JSONImportWizard.this.setVisible(false); + JSONImportWizard.this.dispose(); + } + }; + cancel.addActionListener(cancelListener); + if (importPasted.isSelected()) { + scroller.setVisible(true); + fileSelectionPane.setVisible(false); + pane.revalidate(); + pane.repaint(); + } else if (importFromFile.isSelected()) { + scroller.setVisible(false); + fileSelectionPane.setVisible(true); + pane.revalidate(); + pane.repaint(); + } + pane.revalidate(); + pane.repaint(); + } - @SuppressWarnings("unchecked") - private void showImportPreviewScreen(final List created) { - pane.removeAll(); - message.setText("The following data has been found. Click \"Ok\" to confirm."); - pane.add(message, JideBoxLayout.FIX); - createdPreview.setModel(new GDEListModel(created)); - createdPreview.setCellRenderer(new GDERenderer(false)); - pane.add(new JScrollPane(createdPreview), JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - ok.setText("Ok"); - ok.removeActionListener(okListener); - okListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - proj.createElements(created); - JSONElement lastNode = created.get(created.size() - 1); - if (lastNode != null) { - // lastNode.save(); - ATContentStudio.frame.selectInTree(lastNode); - } - JSONImportWizard.this.setVisible(false); - JSONImportWizard.this.dispose(); - } - }; - ok.addActionListener(okListener); - cancel.setText("Back"); - cancel.removeActionListener(cancelListener); - cancelListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showFirstScreen(); - } - }; - cancel.addActionListener(cancelListener); - - pane.revalidate(); - pane.repaint(); - } + private void checkEnableNext() { + if (dataTypeCombo.getSelectedItem() != null && dataTypeCombo.getSelectedItem() != DataType.none) { + if (importPasted.isSelected()) { + ok.setEnabled(jsonPasteArea.getText() != null && jsonPasteArea.getText().length() > 0); + } else if (importFromFile.isSelected()) { + ok.setEnabled(jsonFileName.getText() != null && jsonFileName.getText().length() > 0 && new File(jsonFileName.getText()).exists() && !(new File(jsonFileName.getText()).isDirectory())); + } + } + } - @SuppressWarnings("unchecked") - private void showErrorScreen(List errors) { - pane.removeAll(); - message.setText("Failed to import. The following error(s) have been encountered:"); - pane.add(message, JideBoxLayout.FIX); - createdPreview.setModel(new GDEListModel(errors)); - createdPreview.setCellRenderer(new ErrorRenderer()); - pane.add(new JScrollPane(createdPreview), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - cancel.setText("Back"); - cancel.removeActionListener(cancelListener); - cancelListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showFirstScreen(); - } - }; - cancel.addActionListener(cancelListener); - ok.setText("Close"); - ok.removeActionListener(okListener); - okListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JSONImportWizard.this.setVisible(false); - JSONImportWizard.this.dispose(); - } - }; - ok.addActionListener(okListener); - - pane.revalidate(); - pane.repaint(); - } - - @SuppressWarnings("unchecked") - private void showWarningScreen(List warnings, final List created) { - pane.removeAll(); - message.setText("The following warnings(s) were raised while importing:"); - pane.add(message, JideBoxLayout.FIX); - createdPreview.setModel(new GDEListModel(warnings)); - createdPreview.setCellRenderer(new WarningRenderer()); - pane.add(new JScrollPane(createdPreview), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); + @SuppressWarnings("unchecked") + private void showImportPreviewScreen(final List created) { + pane.removeAll(); + message.setText("The following data has been found. Click \"Ok\" to confirm."); + pane.add(message, JideBoxLayout.FIX); + createdPreview.setModel(new GDEListModel(created)); + createdPreview.setCellRenderer(new GDERenderer(false)); + pane.add(new JScrollPane(createdPreview), JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + ok.setText("Ok"); + ok.removeActionListener(okListener); + okListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + proj.createElements(created); + JSONElement lastNode = created.get(created.size() - 1); + if (lastNode != null) { + // lastNode.save(); + ATContentStudio.frame.selectInTree(lastNode); + } + JSONImportWizard.this.setVisible(false); + JSONImportWizard.this.dispose(); + } + }; + ok.addActionListener(okListener); + cancel.setText("Back"); + cancel.removeActionListener(cancelListener); + cancelListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + showFirstScreen(); + } + }; + cancel.addActionListener(cancelListener); - ok.setText("Continue anyway"); - ok.removeActionListener(okListener); - okListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - showImportPreviewScreen(created); - } - }; - ok.addActionListener(okListener); - - cancel.setText("Close"); - cancel.removeActionListener(cancelListener); - cancelListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JSONImportWizard.this.setVisible(false); - JSONImportWizard.this.dispose(); - } - }; - cancel.addActionListener(cancelListener); - - pane.revalidate(); - pane.repaint(); - } + pane.revalidate(); + pane.repaint(); + } - public class GDERenderer extends DefaultListCellRenderer { + @SuppressWarnings("unchecked") + private void showErrorScreen(List errors) { + pane.removeAll(); + message.setText("Failed to import. The following error(s) have been encountered:"); + pane.add(message, JideBoxLayout.FIX); + createdPreview.setModel(new GDEListModel(errors)); + createdPreview.setCellRenderer(new ErrorRenderer()); + pane.add(new JScrollPane(createdPreview), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + cancel.setText("Back"); + cancel.removeActionListener(cancelListener); + cancelListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + showFirstScreen(); + } + }; + cancel.addActionListener(cancelListener); + ok.setText("Close"); + ok.removeActionListener(okListener); + okListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JSONImportWizard.this.setVisible(false); + JSONImportWizard.this.dispose(); + } + }; + ok.addActionListener(okListener); - private static final long serialVersionUID = 6819681566800482793L; + pane.revalidate(); + pane.repaint(); + } - private boolean includeType; - - public GDERenderer(boolean includeType) { - super(); - this.includeType = includeType; - - } - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value == null) { - label.setText("none"); - } else { - if (includeType && ((GameDataElement)value).getDataType() != null) { - label.setText(((GameDataElement)value).getDataType().toString()+"/"+((GameDataElement)value).getDesc()); - } else { - label.setText(((GameDataElement)value).getDesc()); - } - switch ((DataType)dataTypeCombo.getSelectedItem()) { - case actorCondition: - label.setIcon(new ImageIcon(proj.getIcon(((ActorCondition)value).icon_id))); - break; - case item: - label.setIcon(new ImageIcon(proj.getIcon(((Item)value).icon_id))); - break; - case npc: - label.setIcon(new ImageIcon(proj.getIcon(((NPC)value).icon_id))); - break; - case dialogue: - label.setIcon(new ImageIcon(((Dialogue)value).getIcon())); - break; - case droplist: - label.setIcon(new ImageIcon(((Droplist)value).getIcon())); - break; - case itemCategory: - label.setIcon(new ImageIcon(((ItemCategory)value).getIcon())); - break; - case quest: - label.setIcon(new ImageIcon(((Quest)value).getIcon())); - break; - default: - Notification.addError("Unable to find icon for "+((GameDataElement)value).getDesc()); - } - } - return label; - } - - } + @SuppressWarnings("unchecked") + private void showWarningScreen(List warnings, final List created) { + pane.removeAll(); + message.setText("The following warnings(s) were raised while importing:"); + pane.add(message, JideBoxLayout.FIX); + createdPreview.setModel(new GDEListModel(warnings)); + createdPreview.setCellRenderer(new WarningRenderer()); + pane.add(new JScrollPane(createdPreview), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); - public static class ErrorRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -4265342800284721660L; - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - ((JLabel)c).setIcon(NotificationsPane.icons.get(Notification.Type.ERROR)); - } - return c; - } - } - + ok.setText("Continue anyway"); + ok.removeActionListener(okListener); + okListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + showImportPreviewScreen(created); + } + }; + ok.addActionListener(okListener); - public static class WarningRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -3836045237946111606L; - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - ((JLabel)c).setIcon(NotificationsPane.icons.get(Notification.Type.WARN)); - } - return c; - } - } - - @SuppressWarnings("rawtypes") - public static class GDEListModel implements ListenerCollectionModel { - - List source; - - public GDEListModel(List source) { - this.source = source; - } - @Override - public Collection getElements() { - return source; - } + cancel.setText("Close"); + cancel.removeActionListener(cancelListener); + cancelListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JSONImportWizard.this.setVisible(false); + JSONImportWizard.this.dispose(); + } + }; + cancel.addActionListener(cancelListener); - List listeners = new CopyOnWriteArrayList(); - @Override - public List getListeners() { - return listeners; - } + pane.revalidate(); + pane.repaint(); + } - } + public class GDERenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 6819681566800482793L; + + private boolean includeType; + + public GDERenderer(boolean includeType) { + super(); + this.includeType = includeType; + + } + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value == null) { + label.setText("none"); + } else { + if (includeType && ((GameDataElement) value).getDataType() != null) { + label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((GameDataElement) value).getDesc()); + } else { + label.setText(((GameDataElement) value).getDesc()); + } + switch ((DataType) dataTypeCombo.getSelectedItem()) { + case actorCondition: + label.setIcon(new ImageIcon(proj.getIcon(((ActorCondition) value).icon_id))); + break; + case item: + label.setIcon(new ImageIcon(proj.getIcon(((Item) value).icon_id))); + break; + case npc: + label.setIcon(new ImageIcon(proj.getIcon(((NPC) value).icon_id))); + break; + case dialogue: + label.setIcon(new ImageIcon(((Dialogue) value).getIcon())); + break; + case droplist: + label.setIcon(new ImageIcon(((Droplist) value).getIcon())); + break; + case itemCategory: + label.setIcon(new ImageIcon(((ItemCategory) value).getIcon())); + break; + case quest: + label.setIcon(new ImageIcon(((Quest) value).getIcon())); + break; + default: + Notification.addError("Unable to find icon for " + ((GameDataElement) value).getDesc()); + } + } + return label; + } + + } + + public static class ErrorRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = -4265342800284721660L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + ((JLabel) c).setIcon(NotificationsPane.icons.get(Notification.Type.ERROR)); + } + return c; + } + } - @SuppressWarnings("rawtypes") - public static class DataTypeComboModel implements ComboBoxModel { + public static class WarningRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = -3836045237946111606L; - DataType selected = DataType.none; + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + ((JLabel) c).setIcon(NotificationsPane.icons.get(Notification.Type.WARN)); + } + return c; + } + } - @Override - public int getSize() { - return DataType.values().length; - } + @SuppressWarnings("rawtypes") + public static class GDEListModel implements ListenerCollectionModel { - @Override - public Object getElementAt(int index) { - return DataType.values()[index]; - } + List source; - List listeners = new CopyOnWriteArrayList(); + public GDEListModel(List source) { + this.source = source; + } - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } + @Override + public Collection getElements() { + return source; + } - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } + List listeners = new CopyOnWriteArrayList(); - @Override - public void setSelectedItem(Object anItem) { - selected = (DataType) anItem; - } + @Override + public List getListeners() { + return listeners; + } - @Override - public Object getSelectedItem() { - return selected; - } - } + } - public static class DataTypeComboCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 5621373849299980998L; - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - ((JLabel)c).setText(dataTypeDesc((DataType) value)); - switch ((DataType)value) { - case actorCondition: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getActorConditionIcon())); - break; - case dialogue: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getDialogueIcon())); - break; - case droplist: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); - break; - case item: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getItemIcon())); - break; - case itemCategory: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); - break; - case npc: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); - break; - case quest: - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getQuestIcon())); - break; - default: - break; + @SuppressWarnings("rawtypes") + public static class DataTypeComboModel implements ComboBoxModel { - } - } - return c; - } - } + DataType selected = DataType.none; + + @Override + public int getSize() { + return DataType.values().length; + } + + @Override + public Object getElementAt(int index) { + return DataType.values()[index]; + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addListDataListener(ListDataListener l) { + listeners.add(l); + } + + @Override + public void removeListDataListener(ListDataListener l) { + listeners.remove(l); + } + + @Override + public void setSelectedItem(Object anItem) { + selected = (DataType) anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + } + + public static class DataTypeComboCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 5621373849299980998L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + ((JLabel) c).setText(dataTypeDesc((DataType) value)); + switch ((DataType) value) { + case actorCondition: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getActorConditionIcon())); + break; + case dialogue: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getDialogueIcon())); + break; + case droplist: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); + break; + case item: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getItemIcon())); + break; + case itemCategory: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getDroplistIcon())); + break; + case npc: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); + break; + case quest: + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getQuestIcon())); + break; + default: + break; + + } + } + return c; + } + } + + public static String dataTypeDesc(DataType type) { + switch (type) { + case actorCondition: + return "Actor Condition"; + case dialogue: + return "Dialogue"; + case droplist: + return "Droplist"; + case item: + return "Item"; + case itemCategory: + return "Item Category"; + case npc: + return "NPC"; + case quest: + return "Quest"; + default: + return "Select below"; + } + } - public static String dataTypeDesc(DataType type) { - switch (type) { - case actorCondition: - return "Actor Condition"; - case dialogue: - return "Dialogue"; - case droplist: - return "Droplist"; - case item: - return "Item"; - case itemCategory: - return "Item Category"; - case npc: - return "NPC"; - case quest: - return "Quest"; - default: - return "Select below"; - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java b/src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java index bc6b3d4..e8bebde 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ListenerCollectionModel.java @@ -16,7 +16,7 @@ public interface ListenerCollectionModel extends ListenerListModel { default E getElementAt(int index) { for (E obj : getElements()) { if (index == 0) return obj; - index --; + index--; } return null; } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java index 9752cae..7baf9b6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java @@ -11,6 +11,7 @@ public interface ListenerListModel extends ListModel { default void notifyListeners(int event, int index0, int index1) { notifyListeners(this, event, index0, index1); } + default void notifyListeners(Object source, int event, int index0, int index1) { for (ListDataListener l : getListeners()) { l.intervalRemoved(new ListDataEvent(source, event, index0, index1)); @@ -26,6 +27,6 @@ public interface ListenerListModel extends ListModel { } default void fireListChanged() { - notifyListeners(ListDataEvent.CONTENTS_CHANGED, 0, getSize() -1); + notifyListeners(ListDataEvent.CONTENTS_CHANGED, 0, getSize() - 1); } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java index c4194e3..e995d3c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java @@ -1,96 +1,88 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.BorderFactory; -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.ListCellRenderer; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.NotificationListener; +import javax.swing.*; +import javax.swing.event.ListDataEvent; +import javax.swing.event.ListDataListener; +import java.awt.*; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; + @SuppressWarnings("rawtypes") public class NotificationsPane extends JList { - private static final long serialVersionUID = -1100364214372392608L; + private static final long serialVersionUID = -1100364214372392608L; - public static final Map icons = new LinkedHashMap(Notification.Type.values().length); - - static { - icons.put(Notification.Type.SUCCESS, new ImageIcon(DefaultIcons.getStatusGreenIcon())); - icons.put(Notification.Type.INFO, new ImageIcon(DefaultIcons.getStatusBlueIcon())); - icons.put(Notification.Type.WARN, new ImageIcon(DefaultIcons.getStatusOrangeIcon())); - icons.put(Notification.Type.ERROR, new ImageIcon(DefaultIcons.getStatusRedIcon())); - } - - - @SuppressWarnings("unchecked") - public NotificationsPane() { - super(); - MyListModel model = new MyListModel(); - setModel(model); - setCellRenderer(new ListCellRenderer(){ - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = new JLabel(); - Font f = label.getFont(); - label.setIcon(NotificationsPane.icons.get(((Notification)value).type)); - label.setText(((Notification)value).text); - if (isSelected) { + public static final Map icons = new LinkedHashMap(Notification.Type.values().length); + + static { + icons.put(Notification.Type.SUCCESS, new ImageIcon(DefaultIcons.getStatusGreenIcon())); + icons.put(Notification.Type.INFO, new ImageIcon(DefaultIcons.getStatusBlueIcon())); + icons.put(Notification.Type.WARN, new ImageIcon(DefaultIcons.getStatusOrangeIcon())); + icons.put(Notification.Type.ERROR, new ImageIcon(DefaultIcons.getStatusRedIcon())); + } + + + @SuppressWarnings("unchecked") + public NotificationsPane() { + super(); + MyListModel model = new MyListModel(); + setModel(model); + setCellRenderer(new ListCellRenderer() { + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = new JLabel(); + Font f = label.getFont(); + label.setIcon(NotificationsPane.icons.get(((Notification) value).type)); + label.setText(((Notification) value).text); + if (isSelected) { // label.setBackground(Color.RED); - label.setBorder(BorderFactory.createLineBorder(Color.BLUE)); + label.setBorder(BorderFactory.createLineBorder(Color.BLUE)); // label.setForeground(Color.WHITE); - } - f = f.deriveFont(10f*ATContentStudio.SCALING); - label.setFont(f); - return label; - } - }); - Notification.addNotificationListener(model); - } + } + f = f.deriveFont(10f * ATContentStudio.SCALING); + label.setFont(f); + return label; + } + }); + Notification.addNotificationListener(model); + } - private class MyListModel implements ListenerListModel, NotificationListener { - - @Override - public Notification getElementAt(int index) { - return Notification.notifs.get(index); - } + private class MyListModel implements ListenerListModel, NotificationListener { - @Override - public List getListeners() { - return listeners; - } + @Override + public Notification getElementAt(int index) { + return Notification.notifs.get(index); + } - @Override - public int getSize() { - return Notification.notifs.size(); - } - - @Override - public void onNewNotification(Notification n) { - notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_ADDED, Notification.notifs.size() - 1 , Notification.notifs.size() - 1); - NotificationsPane.this.ensureIndexIsVisible(Notification.notifs.indexOf(n)); - } - - @Override - public void onListCleared(int i) { - notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_REMOVED, 0 , i); - } - - private List listeners = new CopyOnWriteArrayList(); - } + @Override + public List getListeners() { + return listeners; + } + + @Override + public int getSize() { + return Notification.notifs.size(); + } + + @Override + public void onNewNotification(Notification n) { + notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_ADDED, Notification.notifs.size() - 1, Notification.notifs.size() - 1); + NotificationsPane.this.ensureIndexIsVisible(Notification.notifs.indexOf(n)); + } + + @Override + public void onListCleared(int i) { + notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_REMOVED, 0, i); + } + + private List listeners = new CopyOnWriteArrayList(); + } } \ No newline at end of file diff --git a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java index 32f6289..22c7f40 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java @@ -11,6 +11,7 @@ public abstract class OrderedListenerListModel implements ListenerCollecti protected S source; protected abstract List getItems(); + protected abstract void setItems(List items); public OrderedListenerListModel(S source) { @@ -18,7 +19,7 @@ public abstract class OrderedListenerListModel implements ListenerCollecti } @Override - public Collection getElements(){ + public Collection getElements() { return getItems(); } @@ -33,7 +34,10 @@ public abstract class OrderedListenerListModel implements ListenerCollecti return getItems().set(index, value); } - public void addObject(E item) {addItem(item);} + public void addObject(E item) { + addItem(item); + } + public void addItem(E item) { if (getItems() == null) { setItems(new ArrayList()); @@ -43,7 +47,10 @@ public abstract class OrderedListenerListModel implements ListenerCollecti notifyListeners(ListDataEvent.INTERVAL_ADDED, index, index); } - public void removeObject(E item) {removeItem(item);} + public void removeObject(E item) { + removeItem(item); + } + public void removeItem(E item) { int index = getItems().indexOf(item); getItems().remove(item); @@ -70,13 +77,17 @@ public abstract class OrderedListenerListModel implements ListenerCollecti notifyListeners(ListDataEvent.CONTENTS_CHANGED, index + direction, index); } - public void objectChanged(E item) {itemChanged(item);} + public void objectChanged(E item) { + itemChanged(item); + } + public void itemChanged(E item) { int index = getItems().indexOf(item); - notifyListeners( ListDataEvent.CONTENTS_CHANGED, index, index); + notifyListeners(ListDataEvent.CONTENTS_CHANGED, index, index); } private List listeners = new CopyOnWriteArrayList(); + public List getListeners() { return listeners; } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/OverlayIcon.java b/src/com/gpl/rpg/atcontentstudio/ui/OverlayIcon.java index 292738d..f0dddc1 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/OverlayIcon.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/OverlayIcon.java @@ -1,35 +1,32 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Image; - -import javax.swing.Icon; +import javax.swing.*; +import java.awt.*; public class OverlayIcon implements Icon { - - private Image background; - private Image overlay; - - public OverlayIcon(Image background, Image overlay) { - this.background = background; - this.overlay = overlay; - } - - @Override - public void paintIcon(Component c, Graphics g, int x, int y) { - g.drawImage(background, x, y, null); - g.drawImage(overlay, x, y, null); - } - @Override - public int getIconWidth() { - return Math.max(background.getWidth(null), overlay.getWidth(null)); - } + private Image background; + private Image overlay; - @Override - public int getIconHeight() { - return Math.max(background.getHeight(null), overlay.getHeight(null)); - } + public OverlayIcon(Image background, Image overlay) { + this.background = background; + this.overlay = overlay; + } + + @Override + public void paintIcon(Component c, Graphics g, int x, int y) { + g.drawImage(background, x, y, null); + g.drawImage(overlay, x, y, null); + } + + @Override + public int getIconWidth() { + return Math.max(background.getWidth(null), overlay.getWidth(null)); + } + + @Override + public int getIconHeight() { + return Math.max(background.getHeight(null), overlay.getHeight(null)); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java index dcdff60..618fc5c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ProjectCreationWizard.java @@ -1,31 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.ComboBoxModel; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.ListCellRenderer; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.ListDataListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.Project.ResourceSet; @@ -34,291 +8,305 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.model.maps.TMXMapSet; import com.gpl.rpg.atcontentstudio.model.sprites.SpriteSheetSet; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.ListDataListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class ProjectCreationWizard extends JDialog { - private static final long serialVersionUID = -2854969975146867119L; + private static final long serialVersionUID = -2854969975146867119L; - final JTextField projectNameField; - final JComboBox atSourceSelectionCombo; - final JComboBox resourceSetToUse; + final JTextField projectNameField; + final JComboBox atSourceSelectionCombo; + final JComboBox resourceSetToUse; - final JButton browse; - final JButton okButton; - final JButton cancelButton; - - final JLabel errorLabel; - - public ProjectCreationWizard() { - super(ATContentStudio.frame); - setTitle("Create project"); - projectNameField = new JTextField(); - atSourceSelectionCombo = new JComboBox(); - resourceSetToUse = new JComboBox(new ComboBoxModel() { + final JButton browse; + final JButton okButton; + final JButton cancelButton; - Project.ResourceSet selected = Project.ResourceSet.gameData; - - @Override - public int getSize() { - return Project.ResourceSet.values().length; - } + final JLabel errorLabel; - @Override - public ResourceSet getElementAt(int index) { - return Project.ResourceSet.values()[index]; - } + public ProjectCreationWizard() { + super(ATContentStudio.frame); + setTitle("Create project"); + projectNameField = new JTextField(); + atSourceSelectionCombo = new JComboBox(); + resourceSetToUse = new JComboBox(new ComboBoxModel() { - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } + Project.ResourceSet selected = Project.ResourceSet.gameData; - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } + @Override + public int getSize() { + return Project.ResourceSet.values().length; + } - @Override - public void setSelectedItem(Object anItem) { - selected = (ResourceSet) anItem; - } + @Override + public ResourceSet getElementAt(int index) { + return Project.ResourceSet.values()[index]; + } - @Override - public Object getSelectedItem() { - return selected; - } - - }); - resourceSetToUse.setRenderer(new ListCellRenderer() { - @Override - public Component getListCellRendererComponent( - JList list, ResourceSet value, - int index, boolean isSelected, boolean cellHasFocus) { - switch (value) { - case allFiles: - return new JLabel("All available files"); - case debugData: - return new JLabel("Debug data"); - case gameData: - return new JLabel("Real game data"); - default: - return new JLabel(); - } - - } - }); - browse = new JButton("Browse..."); - okButton = new JButton("Ok"); - cancelButton = new JButton("Cancel"); - errorLabel = new JLabel("Enter the following information about your project."); - - projectNameField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - updateOkButtonEnablement(); - } - @Override - public void insertUpdate(DocumentEvent e) { - updateOkButtonEnablement(); - } - @Override - public void changedUpdate(DocumentEvent e) { - updateOkButtonEnablement(); - } - }); - for (File f : Workspace.activeWorkspace.knownMapSourcesFolders) { - atSourceSelectionCombo.addItem(f.getAbsolutePath()); - } - atSourceSelectionCombo.setEditable(true); - atSourceSelectionCombo.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateOkButtonEnablement(); - } - }); - browse.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser chooser = new JFileChooser(); - boolean keepTrying = true; - if (atSourceSelectionCombo.getSelectedItem() != null && ((String)atSourceSelectionCombo.getSelectedItem()).length() > 0) { - File f = new File((String)atSourceSelectionCombo.getSelectedItem()); - if (f.exists()) { - chooser.setCurrentDirectory(f); - keepTrying = false; - } - } - if (keepTrying && Workspace.activeWorkspace.knownMapSourcesFolders != null && !Workspace.activeWorkspace.knownMapSourcesFolders.isEmpty()) { - chooser.setCurrentDirectory(Workspace.activeWorkspace.knownMapSourcesFolders.iterator().next()); - } - chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - int result = chooser.showOpenDialog(ProjectCreationWizard.this); - if (result == JFileChooser.APPROVE_OPTION) { - atSourceSelectionCombo.setSelectedItem(chooser.getSelectedFile().getAbsolutePath()); - updateOkButtonEnablement(); - } - } - }); - okButton.setEnabled(false); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - File atSourceFolder = new File((String) atSourceSelectionCombo.getSelectedItem()); - if (!Workspace.activeWorkspace.knownMapSourcesFolders.contains(atSourceFolder)) { - Workspace.activeWorkspace.knownMapSourcesFolders.add(atSourceFolder); - } - Workspace.createProject(projectNameField.getText(), atSourceFolder, (Project.ResourceSet)resourceSetToUse.getSelectedItem()); - ProjectCreationWizard.this.dispose(); - } - }); - - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ProjectCreationWizard.this.dispose(); - } - }); - - JPanel panel = new JPanel(); - panel.setLayout(new GridBagLayout()); - GridBagConstraints c =new GridBagConstraints(); - - c.anchor = GridBagConstraints.NORTHWEST; - c.fill = GridBagConstraints.BOTH; - c.gridheight = 1; - c.gridwidth = 3; - c.gridx = 1; - c.gridy = 1; - c.weightx = 100; - c.weighty = 100; - panel.add(errorLabel, c); - - c.gridy++; - c.gridx = 1; - c.gridwidth = 1; - c.weightx = 20; - panel.add(new JLabel("Project name: "), c); - - c.gridx++; - c.gridwidth = 2; - c.weightx = 80; - panel.add(projectNameField, c); - - c.gridy++; - c.gridx = 1; - c.gridwidth = 1; - c.weightx = 20; - panel.add(new JLabel("AT Source: "), c); + List listeners = new CopyOnWriteArrayList(); - c.gridx++; - c.weightx = 60; - panel.add(atSourceSelectionCombo, c); - - c.gridx++; - c.weightx = 20; - panel.add(browse, c); - - c.gridy++; - c.gridx = 1; - c.gridwidth = 1; - c.weightx = 20; - panel.add(new JLabel("Resource set: "), c); + @Override + public void addListDataListener(ListDataListener l) { + listeners.add(l); + } - c.gridx++; - c.weightx = 80; - c.gridwidth = 2; - panel.add(resourceSetToUse, c); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new GridBagLayout()); - GridBagConstraints c2 = new GridBagConstraints(); - c2.fill = GridBagConstraints.HORIZONTAL; + @Override + public void removeListDataListener(ListDataListener l) { + listeners.remove(l); + } + + @Override + public void setSelectedItem(Object anItem) { + selected = (ResourceSet) anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + + }); + resourceSetToUse.setRenderer(new ListCellRenderer() { + @Override + public Component getListCellRendererComponent( + JList list, ResourceSet value, + int index, boolean isSelected, boolean cellHasFocus) { + switch (value) { + case allFiles: + return new JLabel("All available files"); + case debugData: + return new JLabel("Debug data"); + case gameData: + return new JLabel("Real game data"); + default: + return new JLabel(); + } + + } + }); + browse = new JButton("Browse..."); + okButton = new JButton("Ok"); + cancelButton = new JButton("Cancel"); + errorLabel = new JLabel("Enter the following information about your project."); + + projectNameField.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + updateOkButtonEnablement(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + updateOkButtonEnablement(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateOkButtonEnablement(); + } + }); + for (File f : Workspace.activeWorkspace.knownMapSourcesFolders) { + atSourceSelectionCombo.addItem(f.getAbsolutePath()); + } + atSourceSelectionCombo.setEditable(true); + atSourceSelectionCombo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateOkButtonEnablement(); + } + }); + browse.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JFileChooser chooser = new JFileChooser(); + boolean keepTrying = true; + if (atSourceSelectionCombo.getSelectedItem() != null && ((String) atSourceSelectionCombo.getSelectedItem()).length() > 0) { + File f = new File((String) atSourceSelectionCombo.getSelectedItem()); + if (f.exists()) { + chooser.setCurrentDirectory(f); + keepTrying = false; + } + } + if (keepTrying && Workspace.activeWorkspace.knownMapSourcesFolders != null && !Workspace.activeWorkspace.knownMapSourcesFolders.isEmpty()) { + chooser.setCurrentDirectory(Workspace.activeWorkspace.knownMapSourcesFolders.iterator().next()); + } + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + int result = chooser.showOpenDialog(ProjectCreationWizard.this); + if (result == JFileChooser.APPROVE_OPTION) { + atSourceSelectionCombo.setSelectedItem(chooser.getSelectedFile().getAbsolutePath()); + updateOkButtonEnablement(); + } + } + }); + okButton.setEnabled(false); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + File atSourceFolder = new File((String) atSourceSelectionCombo.getSelectedItem()); + if (!Workspace.activeWorkspace.knownMapSourcesFolders.contains(atSourceFolder)) { + Workspace.activeWorkspace.knownMapSourcesFolders.add(atSourceFolder); + } + Workspace.createProject(projectNameField.getText(), atSourceFolder, (Project.ResourceSet) resourceSetToUse.getSelectedItem()); + ProjectCreationWizard.this.dispose(); + } + }); + + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ProjectCreationWizard.this.dispose(); + } + }); + + JPanel panel = new JPanel(); + panel.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + c.anchor = GridBagConstraints.NORTHWEST; + c.fill = GridBagConstraints.BOTH; + c.gridheight = 1; + c.gridwidth = 3; + c.gridx = 1; + c.gridy = 1; + c.weightx = 100; + c.weighty = 100; + panel.add(errorLabel, c); + + c.gridy++; + c.gridx = 1; + c.gridwidth = 1; + c.weightx = 20; + panel.add(new JLabel("Project name: "), c); + + c.gridx++; + c.gridwidth = 2; + c.weightx = 80; + panel.add(projectNameField, c); + + c.gridy++; + c.gridx = 1; + c.gridwidth = 1; + c.weightx = 20; + panel.add(new JLabel("AT Source: "), c); + + c.gridx++; + c.weightx = 60; + panel.add(atSourceSelectionCombo, c); + + c.gridx++; + c.weightx = 20; + panel.add(browse, c); + + c.gridy++; + c.gridx = 1; + c.gridwidth = 1; + c.weightx = 20; + panel.add(new JLabel("Resource set: "), c); + + c.gridx++; + c.weightx = 80; + c.gridwidth = 2; + panel.add(resourceSetToUse, c); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new GridBagLayout()); + GridBagConstraints c2 = new GridBagConstraints(); + c2.fill = GridBagConstraints.HORIZONTAL; c2.gridx = 1; - c2.weightx = 80; - buttonPane.add(new JLabel(), c2); + c2.weightx = 80; + buttonPane.add(new JLabel(), c2); - c2.gridx++; - c2.weightx = 10; - c.fill = GridBagConstraints.NONE; - buttonPane.add(cancelButton, c2); - - c2.gridx++; - c2.weightx = 10; - buttonPane.add(okButton, c2); - - c.gridy++; - c.fill = GridBagConstraints.HORIZONTAL; - c.gridwidth = 3; - panel.add(buttonPane, c); - - updateOkButtonEnablement(); - - setContentPane(panel); - - pack(); - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - } + c2.gridx++; + c2.weightx = 10; + c.fill = GridBagConstraints.NONE; + buttonPane.add(cancelButton, c2); + + c2.gridx++; + c2.weightx = 10; + buttonPane.add(okButton, c2); + + c.gridy++; + c.fill = GridBagConstraints.HORIZONTAL; + c.gridwidth = 3; + panel.add(buttonPane, c); + + updateOkButtonEnablement(); + + setContentPane(panel); + + pack(); + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + } - protected void updateOkButtonEnablement() { - if (projectNameField.getText() == null || projectNameField.getText().length() <= 0) { - errorLabel.setText("Select a project name."); - this.okButton.setEnabled(false); - return; - } - if (atSourceSelectionCombo.getSelectedItem() == null || ((String)atSourceSelectionCombo.getSelectedItem()).length() <= 0) { - errorLabel.setText("Select an AT source root folder."); - this.okButton.setEnabled(false); - return; - } - File projFolder = new File(Workspace.activeWorkspace.baseFolder, projectNameField.getText()+File.separator); - File sourceFolder = new File((String) atSourceSelectionCombo.getSelectedItem()); - if (projFolder.exists()) { - errorLabel.setText("A project with this name already exists."); - this.okButton.setEnabled(false); - return; - } else { - try { - projFolder.getCanonicalPath(); - } catch (IOException ioe) { - errorLabel.setText(""+projectNameField.getText()+" is not a valid project name."); - this.okButton.setEnabled(false); - return; - } - } - if (!sourceFolder.exists()) { - errorLabel.setText("The selected AT source root folder does not exist."); - this.okButton.setEnabled(false); - return; - } else { - File res = new File(sourceFolder, GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); - if (!res.exists()) { - errorLabel.setText("The selected AT source root folder does not contain the \"res\" folder."); - this.okButton.setEnabled(false); - return; - } - File drawable = new File(sourceFolder, SpriteSheetSet.DEFAULT_REL_PATH_IN_SOURCE); - if (!drawable.exists()) { - errorLabel.setText("The selected AT source root folder does not contain the \"drawable\" folder."); - this.okButton.setEnabled(false); - return; - } - File xml = new File(sourceFolder, TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE); - if (!xml.exists()) { - errorLabel.setText("The selected AT source root folder does not contain the \"xml\" folder."); - this.okButton.setEnabled(false); - return; - } - } - if (!projFolder.exists() && sourceFolder.exists()) { - errorLabel.setText("Everything looks good !"); - this.okButton.setEnabled(true); - return; - } - } - + protected void updateOkButtonEnablement() { + if (projectNameField.getText() == null || projectNameField.getText().length() <= 0) { + errorLabel.setText("Select a project name."); + this.okButton.setEnabled(false); + return; + } + if (atSourceSelectionCombo.getSelectedItem() == null || ((String) atSourceSelectionCombo.getSelectedItem()).length() <= 0) { + errorLabel.setText("Select an AT source root folder."); + this.okButton.setEnabled(false); + return; + } + File projFolder = new File(Workspace.activeWorkspace.baseFolder, projectNameField.getText() + File.separator); + File sourceFolder = new File((String) atSourceSelectionCombo.getSelectedItem()); + if (projFolder.exists()) { + errorLabel.setText("A project with this name already exists."); + this.okButton.setEnabled(false); + return; + } else { + try { + projFolder.getCanonicalPath(); + } catch (IOException ioe) { + errorLabel.setText("" + projectNameField.getText() + " is not a valid project name."); + this.okButton.setEnabled(false); + return; + } + } + if (!sourceFolder.exists()) { + errorLabel.setText("The selected AT source root folder does not exist."); + this.okButton.setEnabled(false); + return; + } else { + File res = new File(sourceFolder, GameDataSet.DEFAULT_REL_PATH_IN_SOURCE); + if (!res.exists()) { + errorLabel.setText("The selected AT source root folder does not contain the \"res\" folder."); + this.okButton.setEnabled(false); + return; + } + File drawable = new File(sourceFolder, SpriteSheetSet.DEFAULT_REL_PATH_IN_SOURCE); + if (!drawable.exists()) { + errorLabel.setText("The selected AT source root folder does not contain the \"drawable\" folder."); + this.okButton.setEnabled(false); + return; + } + File xml = new File(sourceFolder, TMXMapSet.DEFAULT_REL_PATH_IN_SOURCE); + if (!xml.exists()) { + errorLabel.setText("The selected AT source root folder does not contain the \"xml\" folder."); + this.okButton.setEnabled(false); + return; + } + } + if (!projFolder.exists() && sourceFolder.exists()) { + errorLabel.setText("Everything looks good !"); + this.okButton.setEnabled(true); + return; + } + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java b/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java index 4b050aa..7b2513a 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java @@ -1,34 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Image; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JSeparator; -import javax.swing.JTree; -import javax.swing.event.TreeModelEvent; -import javax.swing.event.TreeModelListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; - import com.gpl.rpg.andorstrainer.AndorsTrainer; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; @@ -42,240 +13,255 @@ import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData; import com.jidesoft.swing.TreeSearchable; +import javax.swing.*; +import javax.swing.event.TreeModelEvent; +import javax.swing.event.TreeModelListener; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; +import java.awt.*; +import java.awt.event.*; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class ProjectsTree extends JPanel { - private static final long serialVersionUID = 6332593891796576708L; + private static final long serialVersionUID = 6332593891796576708L; - private JTree projectsTree; - - private JPopupMenu popupMenu; - - private Thread konamiTimeout = null; - private boolean exit = false; - private int timeout = 200; - private Integer[] konamiBuffer = new Integer[]{null, null, null, null, null, null, null, null, null, null}; - private boolean konamiCodeEntered = false; - - public ProjectsTree() { - super(); - setLayout(new BorderLayout()); - projectsTree = new JTree(new ProjectsTreeModel()); - new TreeSearchable(projectsTree){ - @Override - protected String convertElementToString(Object object) { - return ((ProjectTreeNode)((TreePath)object).getLastPathComponent()).getDesc(); - } - }; - add(projectsTree, BorderLayout.CENTER); - projectsTree.setRootVisible(false); - projectsTree.setShowsRootHandles(true); - projectsTree.setExpandsSelectedPaths(true); - - popupMenu = new JPopupMenu(); - makePopupMenu(); - - projectsTree.setCellRenderer(new ProjectsTreeCellRenderer()); - projectsTree.addKeyListener(new KeyAdapter() { - @Override - public void keyReleased(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - if (projectsTree.getSelectionPath() != null) { - itemAction((ProjectTreeNode) projectsTree.getSelectionPath().getLastPathComponent()); - } - } else { - if (konamiTimeout == null) { - startKonamiCount(); - } - int i = 0; - while (i < konamiBuffer.length && konamiBuffer[i] != null) { - i++; - } - if (i < konamiBuffer.length) { - konamiBuffer[i] = e.getKeyCode(); - if (!compareBuffers()) { - exit = true; - } else { - resetTimeout(); - } - } - } - } - }); - projectsTree.addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (e.isPopupTrigger()) { - popupActivated(e); - } else if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) { - TreePath path = projectsTree.getPathForLocation (e.getX(), e.getY()); - projectsTree.setSelectionPath(path); - if (path != null) { - itemAction((ProjectTreeNode) path.getLastPathComponent()); - } - } - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.isPopupTrigger()) { - popupActivated(e); - } - } - }); - - addMouseListener(new MouseAdapter() { - @Override - public void mousePressed(MouseEvent e) { - if (e.isPopupTrigger()) { - popupActivated(e); - } - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.isPopupTrigger()) { - popupActivated(e); - } - } - }); - projectsTree.addTreeSelectionListener(new TreeSelectionListener() { - @Override - public void valueChanged(TreeSelectionEvent e) { + private JTree projectsTree; + + private JPopupMenu popupMenu; + + private Thread konamiTimeout = null; + private boolean exit = false; + private int timeout = 200; + private Integer[] konamiBuffer = new Integer[]{null, null, null, null, null, null, null, null, null, null}; + private boolean konamiCodeEntered = false; + + public ProjectsTree() { + super(); + setLayout(new BorderLayout()); + projectsTree = new JTree(new ProjectsTreeModel()); + new TreeSearchable(projectsTree) { + @Override + protected String convertElementToString(Object object) { + return ((ProjectTreeNode) ((TreePath) object).getLastPathComponent()).getDesc(); + } + }; + add(projectsTree, BorderLayout.CENTER); + projectsTree.setRootVisible(false); + projectsTree.setShowsRootHandles(true); + projectsTree.setExpandsSelectedPaths(true); + + popupMenu = new JPopupMenu(); + makePopupMenu(); + + projectsTree.setCellRenderer(new ProjectsTreeCellRenderer()); + projectsTree.addKeyListener(new KeyAdapter() { + @Override + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + if (projectsTree.getSelectionPath() != null) { + itemAction((ProjectTreeNode) projectsTree.getSelectionPath().getLastPathComponent()); + } + } else { + if (konamiTimeout == null) { + startKonamiCount(); + } + int i = 0; + while (i < konamiBuffer.length && konamiBuffer[i] != null) { + i++; + } + if (i < konamiBuffer.length) { + konamiBuffer[i] = e.getKeyCode(); + if (!compareBuffers()) { + exit = true; + } else { + resetTimeout(); + } + } + } + } + }); + projectsTree.addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (e.isPopupTrigger()) { + popupActivated(e); + } else if (e.getClickCount() == 2 && e.getButton() == MouseEvent.BUTTON1) { + TreePath path = projectsTree.getPathForLocation(e.getX(), e.getY()); + projectsTree.setSelectionPath(path); + if (path != null) { + itemAction((ProjectTreeNode) path.getLastPathComponent()); + } + } + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) { + popupActivated(e); + } + } + }); + + addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + if (e.isPopupTrigger()) { + popupActivated(e); + } + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.isPopupTrigger()) { + popupActivated(e); + } + } + }); + projectsTree.addTreeSelectionListener(new TreeSelectionListener() { + @Override + public void valueChanged(TreeSelectionEvent e) { // List newPaths = new ArrayList(); // for (TreePath path : e.getPaths()) { // if (e.isAddedPath(path)) newPaths.add(path); // } - if (e.getPath() == null) { - ATContentStudio.frame.actions.selectionChanged(null, projectsTree.getSelectionPaths()); - } else { - ATContentStudio.frame.actions.selectionChanged((ProjectTreeNode) e.getPath().getLastPathComponent(), projectsTree.getSelectionPaths()); - } - } - }); - - } - - public void makePopupMenu() { - popupMenu.removeAll(); - - if (ATContentStudio.frame == null || ATContentStudio.frame.actions == null) return; - WorkspaceActions actions = ATContentStudio.frame.actions; - - boolean addNextSeparator = false; - if (actions.createProject.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.createProject)); - } - if (actions.openProject.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.openProject)); - } - if (actions.closeProject.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.closeProject)); - } - if (actions.deleteProject.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.deleteProject)); - } - if (addNextSeparator) { - popupMenu.add(new JSeparator()); - addNextSeparator = false; - } - - if (actions.saveElement.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.saveElement)); - } - if (actions.deleteSelected.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.deleteSelected)); - } - if (addNextSeparator) { - popupMenu.add(new JSeparator()); - addNextSeparator = false; - } + if (e.getPath() == null) { + ATContentStudio.frame.actions.selectionChanged(null, projectsTree.getSelectionPaths()); + } else { + ATContentStudio.frame.actions.selectionChanged((ProjectTreeNode) e.getPath().getLastPathComponent(), projectsTree.getSelectionPaths()); + } + } + }); - if (actions.createGDE.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.createGDE)); - } - if (actions.importJSON.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.importJSON)); - } - if (actions.createMap.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.createMap)); - } - if (actions.createWorldmap.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.createWorldmap)); - } - if (actions.loadSave.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.loadSave)); - } - if (addNextSeparator) { - popupMenu.add(new JSeparator()); - addNextSeparator = false; - } - + } - if (actions.compareItems.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.compareItems)); - } - if (actions.compareNPCs.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.compareNPCs)); - } - if (actions.runBeanShell.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.runBeanShell)); - } - if (actions.exportProject.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.exportProject)); - } - if (addNextSeparator) { - popupMenu.add(new JSeparator()); - addNextSeparator = false; - } - - if (actions.createWriter.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.createWriter)); - } + public void makePopupMenu() { + popupMenu.removeAll(); + + if (ATContentStudio.frame == null || ATContentStudio.frame.actions == null) return; + WorkspaceActions actions = ATContentStudio.frame.actions; + + boolean addNextSeparator = false; + if (actions.createProject.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.createProject)); + } + if (actions.openProject.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.openProject)); + } + if (actions.closeProject.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.closeProject)); + } + if (actions.deleteProject.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.deleteProject)); + } + if (addNextSeparator) { + popupMenu.add(new JSeparator()); + addNextSeparator = false; + } + + if (actions.saveElement.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.saveElement)); + } + if (actions.deleteSelected.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.deleteSelected)); + } + if (addNextSeparator) { + popupMenu.add(new JSeparator()); + addNextSeparator = false; + } + + if (actions.createGDE.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.createGDE)); + } + if (actions.importJSON.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.importJSON)); + } + if (actions.createMap.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.createMap)); + } + if (actions.createWorldmap.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.createWorldmap)); + } + if (actions.loadSave.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.loadSave)); + } + if (addNextSeparator) { + popupMenu.add(new JSeparator()); + addNextSeparator = false; + } + + + if (actions.compareItems.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.compareItems)); + } + if (actions.compareNPCs.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.compareNPCs)); + } + if (actions.runBeanShell.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.runBeanShell)); + } + if (actions.exportProject.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.exportProject)); + } + if (addNextSeparator) { + popupMenu.add(new JSeparator()); + addNextSeparator = false; + } + + if (actions.createWriter.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.createWriter)); + } // if (actions.testCommitWriter.isEnabled()) { // addNextSeparator = true; // popupMenu.add(new JMenuItem(actions.testCommitWriter)); // } - if (actions.generateWriter.isEnabled()) { - addNextSeparator = true; - popupMenu.add(new JMenuItem(actions.generateWriter)); - } - if (addNextSeparator) { - popupMenu.add(new JSeparator()); - addNextSeparator = false; - } - - if (konamiCodeEntered) { - JMenuItem openTrainer = new JMenuItem("Start Andor's Trainer..."); - popupMenu.add(openTrainer); - popupMenu.addSeparator(); - openTrainer.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - new Thread() { - public void run() { - AndorsTrainer.startApp(false); - } - }.start(); - } - }); - } - + if (actions.generateWriter.isEnabled()) { + addNextSeparator = true; + popupMenu.add(new JMenuItem(actions.generateWriter)); + } + if (addNextSeparator) { + popupMenu.add(new JSeparator()); + addNextSeparator = false; + } + + if (konamiCodeEntered) { + JMenuItem openTrainer = new JMenuItem("Start Andor's Trainer..."); + popupMenu.add(openTrainer); + popupMenu.addSeparator(); + openTrainer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + new Thread() { + public void run() { + AndorsTrainer.startApp(false); + } + }.start(); + } + }); + } + // if (projectsTree.getSelectionPath() == null || projectsTree.getSelectionPath().getLastPathComponent() == null) { // JMenuItem addProject = new JMenuItem("Create project..."); // popupMenu.add(addProject); @@ -564,212 +550,213 @@ public class ProjectsTree extends JPanel { // ATContentStudio.frame.showAbout(); // } // }); - } - - public void popupActivated(MouseEvent e) { - TreePath path = projectsTree.getPathForLocation (e.getX(), e.getY()); - TreePath[] allSelected = projectsTree.getSelectionPaths(); - boolean selectClickedItem = true; - if (allSelected != null) { - for (TreePath selected : allSelected) { - if (selected.equals(path)) { - selectClickedItem = false; - break; - } - } - } - if (selectClickedItem) projectsTree.setSelectionPath(path); - makePopupMenu(); - if (popupMenu.getComponentCount() > 0) { - popupMenu.show(projectsTree, e.getX(), e.getY()); - } - } - - public void itemAction(ProjectTreeNode node) { - if (node instanceof JSONElement) { - ATContentStudio.frame.openEditor((JSONElement)node); - } else if (node instanceof Spritesheet) { - ATContentStudio.frame.openEditor((Spritesheet)node); - } else if (node instanceof TMXMap) { - ATContentStudio.frame.openEditor((TMXMap)node); - } else if (node instanceof WorldmapSegment) { - ATContentStudio.frame.openEditor((WorldmapSegment)node); - } else if (node instanceof WriterModeData) { - ATContentStudio.frame.openEditor((WriterModeData)node); - } else if (node instanceof BookmarkEntry) { - ATContentStudio.frame.openEditor(((BookmarkEntry)node).bookmarkedElement); - } else if (node instanceof SavedGame) { - if (konamiCodeEntered) { - ATContentStudio.frame.openEditor((SavedGame)node); - } - } - } - - public class ProjectsTreeModel implements TreeModel { + } - public ProjectsTreeModel() { - Workspace.activeWorkspace.projectsTreeModel = this; - } - - @Override - public Object getRoot() { - return Workspace.activeWorkspace; - } + public void popupActivated(MouseEvent e) { + TreePath path = projectsTree.getPathForLocation(e.getX(), e.getY()); + TreePath[] allSelected = projectsTree.getSelectionPaths(); + boolean selectClickedItem = true; + if (allSelected != null) { + for (TreePath selected : allSelected) { + if (selected.equals(path)) { + selectClickedItem = false; + break; + } + } + } + if (selectClickedItem) projectsTree.setSelectionPath(path); + makePopupMenu(); + if (popupMenu.getComponentCount() > 0) { + popupMenu.show(projectsTree, e.getX(), e.getY()); + } + } - @Override - public Object getChild(Object parent, int index) { - return ((ProjectTreeNode)parent).getChildAt(index); - } + public void itemAction(ProjectTreeNode node) { + if (node instanceof JSONElement) { + ATContentStudio.frame.openEditor((JSONElement) node); + } else if (node instanceof Spritesheet) { + ATContentStudio.frame.openEditor((Spritesheet) node); + } else if (node instanceof TMXMap) { + ATContentStudio.frame.openEditor((TMXMap) node); + } else if (node instanceof WorldmapSegment) { + ATContentStudio.frame.openEditor((WorldmapSegment) node); + } else if (node instanceof WriterModeData) { + ATContentStudio.frame.openEditor((WriterModeData) node); + } else if (node instanceof BookmarkEntry) { + ATContentStudio.frame.openEditor(((BookmarkEntry) node).bookmarkedElement); + } else if (node instanceof SavedGame) { + if (konamiCodeEntered) { + ATContentStudio.frame.openEditor((SavedGame) node); + } + } + } - @Override - public int getChildCount(Object parent) { - return ((ProjectTreeNode)parent).getChildCount(); - } + public class ProjectsTreeModel implements TreeModel { - @Override - public boolean isLeaf(Object node) { - return ((ProjectTreeNode)node).isLeaf(); - } + public ProjectsTreeModel() { + Workspace.activeWorkspace.projectsTreeModel = this; + } - @Override - public void valueForPathChanged(TreePath path, Object newValue) { - //Unused - } - - public void insertNode(TreePath node) { - for (TreeModelListener l : listeners) { - l.treeNodesInserted(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath().getPath(), new int[]{((ProjectTreeNode)node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode)node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()} )); - } - } - - public void changeNode(TreePath node) { - for (TreeModelListener l : listeners) { - l.treeNodesChanged(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), new int[]{((ProjectTreeNode)node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode)node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()} )); - } - } - - public void removeNode(TreePath node) { - for (TreeModelListener l : listeners) { - l.treeNodesRemoved(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), new int[]{((ProjectTreeNode)node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode)node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()} )); - } - } + @Override + public Object getRoot() { + return Workspace.activeWorkspace; + } - @Override - public int getIndexOfChild(Object parent, Object child) { - return ((ProjectTreeNode)parent).getIndex((ProjectTreeNode) child); - } + @Override + public Object getChild(Object parent, int index) { + return ((ProjectTreeNode) parent).getChildAt(index); + } - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addTreeModelListener(TreeModelListener l) { - listeners.add(l); - } + @Override + public int getChildCount(Object parent) { + return ((ProjectTreeNode) parent).getChildCount(); + } - @Override - public void removeTreeModelListener(TreeModelListener l) { - listeners.remove(l); - } - - } - - public class ProjectsTreeCellRenderer extends DefaultTreeCellRenderer { + @Override + public boolean isLeaf(Object node) { + return ((ProjectTreeNode) node).isLeaf(); + } - private static final long serialVersionUID = 8100380694034797135L; + @Override + public void valueForPathChanged(TreePath path, Object newValue) { + //Unused + } - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { - Component c = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); - - if (c instanceof JLabel) { - JLabel label = (JLabel)c; - String text = ((ProjectTreeNode)value).getDesc(); - if (text != null) label.setText(text); - Image img; - if (leaf) img = ((ProjectTreeNode)value).getLeafIcon(); - else if (expanded) img = ((ProjectTreeNode)value).getOpenIcon(); - else img = ((ProjectTreeNode)value).getClosedIcon(); - - if (img != null) { - label.setIcon(new ImageIcon(img)); - } - } - - return c; - } - } - - public void setSelectedNode(ProjectTreeNode node) { - List path = new ArrayList(); - path.add(node); - TreeNode parent = node.getParent(); - while (parent != null) { - path.add(0, parent); - parent = parent.getParent(); - } - TreePath tp = new TreePath(path.toArray()); - projectsTree.setSelectionPath(tp); - projectsTree.scrollPathToVisible(tp); - } - - protected void startKonamiCount() { - resetTimeout(); - exit = false; - konamiTimeout = new Thread() { - @Override - public void run() { - while (!exit && timeout > 0) { - try { - Thread.sleep(10); - } catch (InterruptedException e) {} - timeout -= 10; - } - konamiTimeout = null; - konamiBuffer = new Integer[]{null, null, null, null, null, null, null, null, null, null}; - } - }; - konamiTimeout.start(); - } - - protected void resetTimeout() { - timeout = 400; - } - - protected boolean compareBuffers() { - if (konamiBuffer[0] == null) return true; - else if (konamiBuffer[0] != KeyEvent.VK_UP) return false; + public void insertNode(TreePath node) { + for (TreeModelListener l : listeners) { + l.treeNodesInserted(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath().getPath(), new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()})); + } + } - if (konamiBuffer[1] == null) return true; - else if (konamiBuffer[1] != KeyEvent.VK_UP) return false; - - if (konamiBuffer[2] == null) return true; - else if (konamiBuffer[2] != KeyEvent.VK_DOWN) return false; - - if (konamiBuffer[3] == null) return true; - else if (konamiBuffer[3] != KeyEvent.VK_DOWN) return false; - - if (konamiBuffer[4] == null) return true; - else if (konamiBuffer[4] != KeyEvent.VK_LEFT) return false; - - if (konamiBuffer[5] == null) return true; - else if (konamiBuffer[5] != KeyEvent.VK_RIGHT) return false; + public void changeNode(TreePath node) { + for (TreeModelListener l : listeners) { + l.treeNodesChanged(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()})); + } + } - if (konamiBuffer[6] == null) return true; - else if (konamiBuffer[6] != KeyEvent.VK_LEFT) return false; - - if (konamiBuffer[7] == null) return true; - else if (konamiBuffer[7] != KeyEvent.VK_RIGHT) return false; + public void removeNode(TreePath node) { + for (TreeModelListener l : listeners) { + l.treeNodesRemoved(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()})); + } + } - if (konamiBuffer[8] == null) return true; - else if (konamiBuffer[8] != KeyEvent.VK_B) return false; - - if (konamiBuffer[9] == null) return true; - else if (konamiBuffer[9] != KeyEvent.VK_A) return false; - - konamiCodeEntered = true; + @Override + public int getIndexOfChild(Object parent, Object child) { + return ((ProjectTreeNode) parent).getIndex((ProjectTreeNode) child); + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addTreeModelListener(TreeModelListener l) { + listeners.add(l); + } + + @Override + public void removeTreeModelListener(TreeModelListener l) { + listeners.remove(l); + } + + } + + public class ProjectsTreeCellRenderer extends DefaultTreeCellRenderer { + + private static final long serialVersionUID = 8100380694034797135L; + + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { + Component c = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); + + if (c instanceof JLabel) { + JLabel label = (JLabel) c; + String text = ((ProjectTreeNode) value).getDesc(); + if (text != null) label.setText(text); + Image img; + if (leaf) img = ((ProjectTreeNode) value).getLeafIcon(); + else if (expanded) img = ((ProjectTreeNode) value).getOpenIcon(); + else img = ((ProjectTreeNode) value).getClosedIcon(); + + if (img != null) { + label.setIcon(new ImageIcon(img)); + } + } + + return c; + } + } + + public void setSelectedNode(ProjectTreeNode node) { + List path = new ArrayList(); + path.add(node); + TreeNode parent = node.getParent(); + while (parent != null) { + path.add(0, parent); + parent = parent.getParent(); + } + TreePath tp = new TreePath(path.toArray()); + projectsTree.setSelectionPath(tp); + projectsTree.scrollPathToVisible(tp); + } + + protected void startKonamiCount() { + resetTimeout(); + exit = false; + konamiTimeout = new Thread() { + @Override + public void run() { + while (!exit && timeout > 0) { + try { + Thread.sleep(10); + } catch (InterruptedException e) { + } + timeout -= 10; + } + konamiTimeout = null; + konamiBuffer = new Integer[]{null, null, null, null, null, null, null, null, null, null}; + } + }; + konamiTimeout.start(); + } + + protected void resetTimeout() { + timeout = 400; + } + + protected boolean compareBuffers() { + if (konamiBuffer[0] == null) return true; + else if (konamiBuffer[0] != KeyEvent.VK_UP) return false; + + if (konamiBuffer[1] == null) return true; + else if (konamiBuffer[1] != KeyEvent.VK_UP) return false; + + if (konamiBuffer[2] == null) return true; + else if (konamiBuffer[2] != KeyEvent.VK_DOWN) return false; + + if (konamiBuffer[3] == null) return true; + else if (konamiBuffer[3] != KeyEvent.VK_DOWN) return false; + + if (konamiBuffer[4] == null) return true; + else if (konamiBuffer[4] != KeyEvent.VK_LEFT) return false; + + if (konamiBuffer[5] == null) return true; + else if (konamiBuffer[5] != KeyEvent.VK_RIGHT) return false; + + if (konamiBuffer[6] == null) return true; + else if (konamiBuffer[6] != KeyEvent.VK_LEFT) return false; + + if (konamiBuffer[7] == null) return true; + else if (konamiBuffer[7] != KeyEvent.VK_RIGHT) return false; + + if (konamiBuffer[8] == null) return true; + else if (konamiBuffer[8] != KeyEvent.VK_B) return false; + + if (konamiBuffer[9] == null) return true; + else if (konamiBuffer[9] != KeyEvent.VK_A) return false; + + konamiCodeEntered = true; + + exit = true; + return true; + } - exit = true; - return true; - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/SaveItemsWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/SaveItemsWizard.java index c9eb525..60a26f4 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/SaveItemsWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/SaveItemsWizard.java @@ -1,27 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.SaveEvent; @@ -29,246 +7,254 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataCategory; import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.List; +import java.util.*; + public class SaveItemsWizard extends JDialog { - private static final long serialVersionUID = -3301878024575930527L; + private static final long serialVersionUID = -3301878024575930527L; - List events; - - @SuppressWarnings("rawtypes") - JList movedToCreated; - @SuppressWarnings("rawtypes") - JList movedToAltered; - @SuppressWarnings("rawtypes") - JList willBeSaved; - - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public SaveItemsWizard(List events, GameDataElement originalRequester) { - super(ATContentStudio.frame); - this.events = events; - final List movedToAlteredList = new ArrayList(); - final List movedToCreatedList = new ArrayList(); - final List alsoSavedList = new ArrayList(); - final List errors = new ArrayList(); - for (SaveEvent event : events) { - if (event.error) { - errors.add(event); - } else { - switch (event.type) { - case alsoSave: - alsoSavedList.add(event); - break; - case moveToAltered: - movedToAlteredList.add(event); - break; - case moveToCreated: - movedToCreatedList.add(event); - break; - } - } - } - - if (!errors.isEmpty()) { - setTitle("Errors in project. Cannot save."); - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - if (originalRequester != null) { - pane.add(new JLabel(" While trying to save: "), JideBoxLayout.FIX); - JLabel origItemDesc = new JLabel(); - origItemDesc.setIcon(new ImageIcon(originalRequester.getIcon())); - origItemDesc.setText(originalRequester.getDataType().toString()+"/"+originalRequester.id); - pane.add(origItemDesc, JideBoxLayout.FIX); - pane.add(new JLabel(" the following errors have been encountered and must be corrected before saving can occur: "), JideBoxLayout.FIX); - } else { - pane.add(new JLabel("After deleting element(s), the following errors have been encountered and must be coorected before saving can occur: "), JideBoxLayout.FIX); - } - - movedToCreated = new JList(errors.toArray()); - movedToCreated.setCellRenderer(new SaveEventsListCellRenderer()); - JPanel movedToCreatedPane = new JPanel(); - movedToCreatedPane.setLayout(new BorderLayout()); - movedToCreatedPane.add(new JScrollPane(movedToCreated), BorderLayout.CENTER); - pane.add(movedToCreatedPane, JideBoxLayout.FLEXIBLE); + List events; - pane.add(new JPanel(), JideBoxLayout.VARY); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancelButton = new JButton("Ok, back to work..."); - buttonPane.add(cancelButton, JideBoxLayout.FIX); - pane.add(buttonPane, JideBoxLayout.FIX); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SaveItemsWizard.this.setVisible(false); - SaveItemsWizard.this.dispose(); - } - }); - + @SuppressWarnings("rawtypes") + JList movedToCreated; + @SuppressWarnings("rawtypes") + JList movedToAltered; + @SuppressWarnings("rawtypes") + JList willBeSaved; - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - } else { - setTitle("Other elements impacted."); - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - if (originalRequester != null) { - pane.add(new JLabel(" While trying to save: "), JideBoxLayout.FIX); - JLabel origItemDesc = new JLabel(); - origItemDesc.setIcon(new ImageIcon(originalRequester.getIcon())); - origItemDesc.setText(originalRequester.getDataType().toString()+"/"+originalRequester.id); - pane.add(origItemDesc, JideBoxLayout.FIX); - pane.add(new JLabel(" the following side-effects have been identified and must be applied to the project before saving: "), JideBoxLayout.FIX); - } else { - pane.add(new JLabel("After deleting element(s), the following side-effects have been identified and must be applied to the project before saving: "), JideBoxLayout.FIX); - } - - if (!movedToCreatedList.isEmpty()) { - movedToCreated = new JList(movedToCreatedList.toArray()); - movedToCreated.setCellRenderer(new SaveEventsListCellRenderer()); - JPanel movedToCreatedPane = new JPanel(); - movedToCreatedPane.setLayout(new BorderLayout()); - movedToCreatedPane.setBorder(BorderFactory.createTitledBorder("The following elements will be moved under the \"Created\" folder and saved:")); - movedToCreatedPane.add(new JScrollPane(movedToCreated), BorderLayout.CENTER); - pane.add(movedToCreatedPane, JideBoxLayout.FLEXIBLE); - } - if (!movedToAlteredList.isEmpty()) { - movedToAltered = new JList(movedToAlteredList.toArray()); - movedToAltered.setCellRenderer(new SaveEventsListCellRenderer()); - JPanel movedToAlteredPane = new JPanel(); - movedToAlteredPane.setLayout(new BorderLayout()); - movedToAlteredPane.setBorder(BorderFactory.createTitledBorder("The following elements will be moved under the \"Altered\" folder and saved:")); - movedToAlteredPane.add(new JScrollPane(movedToAltered), BorderLayout.CENTER); - pane.add(movedToAlteredPane, JideBoxLayout.FLEXIBLE); - } + @SuppressWarnings({"unchecked", "rawtypes"}) + public SaveItemsWizard(List events, GameDataElement originalRequester) { + super(ATContentStudio.frame); + this.events = events; + final List movedToAlteredList = new ArrayList(); + final List movedToCreatedList = new ArrayList(); + final List alsoSavedList = new ArrayList(); + final List errors = new ArrayList(); + for (SaveEvent event : events) { + if (event.error) { + errors.add(event); + } else { + switch (event.type) { + case alsoSave: + alsoSavedList.add(event); + break; + case moveToAltered: + movedToAlteredList.add(event); + break; + case moveToCreated: + movedToCreatedList.add(event); + break; + } + } + } - if (!alsoSavedList.isEmpty()) { - willBeSaved = new JList(alsoSavedList.toArray()); - willBeSaved.setCellRenderer(new SaveEventsListCellRenderer()); - JPanel willBeSavedPane = new JPanel(); - willBeSavedPane.setLayout(new BorderLayout()); - willBeSavedPane.setBorder(BorderFactory.createTitledBorder("The following elements will be saved too:")); - willBeSavedPane.add(new JScrollPane(willBeSaved), BorderLayout.CENTER); - pane.add(willBeSavedPane, JideBoxLayout.FLEXIBLE); - } + if (!errors.isEmpty()) { + setTitle("Errors in project. Cannot save."); + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + if (originalRequester != null) { + pane.add(new JLabel(" While trying to save: "), JideBoxLayout.FIX); + JLabel origItemDesc = new JLabel(); + origItemDesc.setIcon(new ImageIcon(originalRequester.getIcon())); + origItemDesc.setText(originalRequester.getDataType().toString() + "/" + originalRequester.id); + pane.add(origItemDesc, JideBoxLayout.FIX); + pane.add(new JLabel(" the following errors have been encountered and must be corrected before saving can occur: "), JideBoxLayout.FIX); + } else { + pane.add(new JLabel("After deleting element(s), the following errors have been encountered and must be coorected before saving can occur: "), JideBoxLayout.FIX); + } - pane.add(new JPanel(), JideBoxLayout.VARY); + movedToCreated = new JList(errors.toArray()); + movedToCreated.setCellRenderer(new SaveEventsListCellRenderer()); + JPanel movedToCreatedPane = new JPanel(); + movedToCreatedPane.setLayout(new BorderLayout()); + movedToCreatedPane.add(new JScrollPane(movedToCreated), BorderLayout.CENTER); + pane.add(movedToCreatedPane, JideBoxLayout.FLEXIBLE); - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancelButton = new JButton("Cancel"); - buttonPane.add(cancelButton, JideBoxLayout.FIX); - cancelButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SaveItemsWizard.this.setVisible(false); - SaveItemsWizard.this.dispose(); - } - }); - JButton okButton = new JButton("Apply all changes and save"); - buttonPane.add(okButton, JideBoxLayout.FIX); - pane.add(buttonPane, JideBoxLayout.FIX); - okButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { + pane.add(new JPanel(), JideBoxLayout.VARY); - Map, Set> jsonToSave = new IdentityHashMap, Set>(); - for (SaveEvent event : movedToCreatedList) { - if (event.target instanceof JSONElement) { - if (!jsonToSave.containsKey(event.target.getParent())){ - jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); - } - jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement)event.target).jsonFile); + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancelButton = new JButton("Ok, back to work..."); + buttonPane.add(cancelButton, JideBoxLayout.FIX); + pane.add(buttonPane, JideBoxLayout.FIX); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + SaveItemsWizard.this.setVisible(false); + SaveItemsWizard.this.dispose(); + } + }); - event.target.getProject().moveToCreated((JSONElement) event.target); - if (!jsonToSave.containsKey(event.target.getParent())){ - jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); - } - jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement)event.target).jsonFile); - } - //TODO movable maps, when ID is editable. + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); - } - for (SaveEvent event : movedToAlteredList) { - if (event.target instanceof JSONElement) { - if (!jsonToSave.containsKey(event.target.getParent())){ - jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); - } - jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement)event.target).jsonFile); + } else { + setTitle("Other elements impacted."); + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + if (originalRequester != null) { + pane.add(new JLabel(" While trying to save: "), JideBoxLayout.FIX); + JLabel origItemDesc = new JLabel(); + origItemDesc.setIcon(new ImageIcon(originalRequester.getIcon())); + origItemDesc.setText(originalRequester.getDataType().toString() + "/" + originalRequester.id); + pane.add(origItemDesc, JideBoxLayout.FIX); + pane.add(new JLabel(" the following side-effects have been identified and must be applied to the project before saving: "), JideBoxLayout.FIX); + } else { + pane.add(new JLabel("After deleting element(s), the following side-effects have been identified and must be applied to the project before saving: "), JideBoxLayout.FIX); + } - event.target.getProject().moveToAltered((JSONElement) event.target); + if (!movedToCreatedList.isEmpty()) { + movedToCreated = new JList(movedToCreatedList.toArray()); + movedToCreated.setCellRenderer(new SaveEventsListCellRenderer()); + JPanel movedToCreatedPane = new JPanel(); + movedToCreatedPane.setLayout(new BorderLayout()); + movedToCreatedPane.setBorder(BorderFactory.createTitledBorder("The following elements will be moved under the \"Created\" folder and saved:")); + movedToCreatedPane.add(new JScrollPane(movedToCreated), BorderLayout.CENTER); + pane.add(movedToCreatedPane, JideBoxLayout.FLEXIBLE); + } - if (!jsonToSave.containsKey(event.target.getParent())){ - jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); - } - jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement)event.target).jsonFile); - } - //TODO movable maps, when ID is editable. - } - for (SaveEvent event : alsoSavedList) { - if (event.target instanceof JSONElement) { - if (!jsonToSave.containsKey(event.target.getParent())){ - jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); - } - jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement)event.target).jsonFile); - } - } + if (!movedToAlteredList.isEmpty()) { + movedToAltered = new JList(movedToAlteredList.toArray()); + movedToAltered.setCellRenderer(new SaveEventsListCellRenderer()); + JPanel movedToAlteredPane = new JPanel(); + movedToAlteredPane.setLayout(new BorderLayout()); + movedToAlteredPane.setBorder(BorderFactory.createTitledBorder("The following elements will be moved under the \"Altered\" folder and saved:")); + movedToAlteredPane.add(new JScrollPane(movedToAltered), BorderLayout.CENTER); + pane.add(movedToAlteredPane, JideBoxLayout.FLEXIBLE); + } - for (GameDataCategory cat : jsonToSave.keySet()) { - if (jsonToSave.get(cat) != null && !jsonToSave.get(cat).isEmpty()) { - for (File f : jsonToSave.get(cat)) { - cat.save(f); - } - } - } + if (!alsoSavedList.isEmpty()) { + willBeSaved = new JList(alsoSavedList.toArray()); + willBeSaved.setCellRenderer(new SaveEventsListCellRenderer()); + JPanel willBeSavedPane = new JPanel(); + willBeSavedPane.setLayout(new BorderLayout()); + willBeSavedPane.setBorder(BorderFactory.createTitledBorder("The following elements will be saved too:")); + willBeSavedPane.add(new JScrollPane(willBeSaved), BorderLayout.CENTER); + pane.add(willBeSavedPane, JideBoxLayout.FLEXIBLE); + } - for (SaveEvent event : movedToCreatedList) { - ATContentStudio.frame.nodeChanged(event.target); - } - for (SaveEvent event : movedToAlteredList) { - ATContentStudio.frame.nodeChanged(event.target); - } - for (SaveEvent event : alsoSavedList) { - ATContentStudio.frame.nodeChanged(event.target); - } - SaveItemsWizard.this.setVisible(false); - SaveItemsWizard.this.dispose(); - } - }); + pane.add(new JPanel(), JideBoxLayout.VARY); - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancelButton = new JButton("Cancel"); + buttonPane.add(cancelButton, JideBoxLayout.FIX); + cancelButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + SaveItemsWizard.this.setVisible(false); + SaveItemsWizard.this.dispose(); + } + }); + JButton okButton = new JButton("Apply all changes and save"); + buttonPane.add(okButton, JideBoxLayout.FIX); + pane.add(buttonPane, JideBoxLayout.FIX); + okButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + + Map, Set> jsonToSave = new IdentityHashMap, Set>(); + for (SaveEvent event : movedToCreatedList) { + if (event.target instanceof JSONElement) { + if (!jsonToSave.containsKey(event.target.getParent())) { + jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); + } + jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement) event.target).jsonFile); + + event.target.getProject().moveToCreated((JSONElement) event.target); + + if (!jsonToSave.containsKey(event.target.getParent())) { + jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); + } + jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement) event.target).jsonFile); + } + //TODO movable maps, when ID is editable. + + } + for (SaveEvent event : movedToAlteredList) { + if (event.target instanceof JSONElement) { + if (!jsonToSave.containsKey(event.target.getParent())) { + jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); + } + jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement) event.target).jsonFile); + + event.target.getProject().moveToAltered((JSONElement) event.target); + + if (!jsonToSave.containsKey(event.target.getParent())) { + jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); + } + jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement) event.target).jsonFile); + } + //TODO movable maps, when ID is editable. + } + for (SaveEvent event : alsoSavedList) { + if (event.target instanceof JSONElement) { + if (!jsonToSave.containsKey(event.target.getParent())) { + jsonToSave.put((GameDataCategory) event.target.getParent(), new HashSet()); + } + jsonToSave.get((GameDataCategory) event.target.getParent()).add(((JSONElement) event.target).jsonFile); + } + } + + for (GameDataCategory cat : jsonToSave.keySet()) { + if (jsonToSave.get(cat) != null && !jsonToSave.get(cat).isEmpty()) { + for (File f : jsonToSave.get(cat)) { + cat.save(f); + } + } + } + + for (SaveEvent event : movedToCreatedList) { + ATContentStudio.frame.nodeChanged(event.target); + } + for (SaveEvent event : movedToAlteredList) { + ATContentStudio.frame.nodeChanged(event.target); + } + for (SaveEvent event : alsoSavedList) { + ATContentStudio.frame.nodeChanged(event.target); + } + SaveItemsWizard.this.setVisible(false); + SaveItemsWizard.this.dispose(); + } + }); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + } + + pack(); + } + + public class SaveEventsListCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 5764079243906396333L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = (JLabel) c; + SaveEvent event = (SaveEvent) value; + label.setIcon(new ImageIcon(event.target.getIcon())); + if (event.error) { + label.setText(event.target.getDataType().toString() + "/" + event.target.id + ": " + event.errorText); + } else { + label.setText(event.target.getDataType().toString() + "/" + event.target.id); + } + } + return c; + } + + } - } - - pack(); - } - - public class SaveEventsListCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 5764079243906396333L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = (JLabel) c; - SaveEvent event = (SaveEvent) value; - label.setIcon(new ImageIcon(event.target.getIcon())); - if (event.error) { - label.setText(event.target.getDataType().toString()+"/"+event.target.id+": "+event.errorText); - } else { - label.setText(event.target.getDataType().toString()+"/"+event.target.id); - } - } - return c; - } - - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java b/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java index 805afc4..38312d5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java @@ -1,338 +1,300 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.LayoutManager; -import java.awt.Rectangle; - -import javax.swing.JPanel; -import javax.swing.JViewport; -import javax.swing.Scrollable; -import javax.swing.SwingConstants; +import javax.swing.*; +import java.awt.*; public class ScrollablePanel extends JPanel implements Scrollable, SwingConstants { - - private static final long serialVersionUID = 6498229143202972325L; - public enum ScrollableSizeHint - { - NONE, - FIT, - STRETCH; - } + private static final long serialVersionUID = 6498229143202972325L; - public enum IncrementType - { - PERCENT, - PIXELS; - } + public enum ScrollableSizeHint { + NONE, + FIT, + STRETCH; + } - private ScrollableSizeHint scrollableHeight = ScrollableSizeHint.NONE; - private ScrollableSizeHint scrollableWidth = ScrollableSizeHint.NONE; + public enum IncrementType { + PERCENT, + PIXELS; + } - private IncrementInfo horizontalBlock; - private IncrementInfo horizontalUnit; - private IncrementInfo verticalBlock; - private IncrementInfo verticalUnit; + private ScrollableSizeHint scrollableHeight = ScrollableSizeHint.NONE; + private ScrollableSizeHint scrollableWidth = ScrollableSizeHint.NONE; - /** - * Default constructor that uses a FlowLayout - */ - public ScrollablePanel() - { - this( new FlowLayout() ); - } + private IncrementInfo horizontalBlock; + private IncrementInfo horizontalUnit; + private IncrementInfo verticalBlock; + private IncrementInfo verticalUnit; - /** - * Constuctor for specifying the LayoutManager of the panel. - * - * @param layout the LayountManger for the panel - */ - public ScrollablePanel(LayoutManager layout) - { - super( layout ); + /** + * Default constructor that uses a FlowLayout + */ + public ScrollablePanel() { + this(new FlowLayout()); + } - IncrementInfo block = new IncrementInfo(IncrementType.PERCENT, 100); - IncrementInfo unit = new IncrementInfo(IncrementType.PERCENT, 10); + /** + * Constuctor for specifying the LayoutManager of the panel. + * + * @param layout the LayountManger for the panel + */ + public ScrollablePanel(LayoutManager layout) { + super(layout); - setScrollableBlockIncrement(HORIZONTAL, block); - setScrollableBlockIncrement(VERTICAL, block); - setScrollableUnitIncrement(HORIZONTAL, unit); - setScrollableUnitIncrement(VERTICAL, unit); - } + IncrementInfo block = new IncrementInfo(IncrementType.PERCENT, 100); + IncrementInfo unit = new IncrementInfo(IncrementType.PERCENT, 10); - /** - * Get the height ScrollableSizeHint enum - * - * @return the ScrollableSizeHint enum for the height - */ - public ScrollableSizeHint getScrollableHeight() - { - return scrollableHeight; - } + setScrollableBlockIncrement(HORIZONTAL, block); + setScrollableBlockIncrement(VERTICAL, block); + setScrollableUnitIncrement(HORIZONTAL, unit); + setScrollableUnitIncrement(VERTICAL, unit); + } - /** - * Set the ScrollableSizeHint enum for the height. The enum is used to - * determine the boolean value that is returned by the - * getScrollableTracksViewportHeight() method. The valid values are: - * - * ScrollableSizeHint.NONE - return "false", which causes the height - * of the panel to be used when laying out the children - * ScrollableSizeHint.FIT - return "true", which causes the height of - * the viewport to be used when laying out the children - * ScrollableSizeHint.STRETCH - return "true" when the viewport height - * is greater than the height of the panel, "false" otherwise. - * - * @param scrollableHeight as represented by the ScrollableSizeHint enum. - */ - public void setScrollableHeight(ScrollableSizeHint scrollableHeight) - { - this.scrollableHeight = scrollableHeight; - revalidate(); - } + /** + * Get the height ScrollableSizeHint enum + * + * @return the ScrollableSizeHint enum for the height + */ + public ScrollableSizeHint getScrollableHeight() { + return scrollableHeight; + } - /** - * Get the width ScrollableSizeHint enum - * - * @return the ScrollableSizeHint enum for the width - */ - public ScrollableSizeHint getScrollableWidth() - { - return scrollableWidth; - } + /** + * Set the ScrollableSizeHint enum for the height. The enum is used to + * determine the boolean value that is returned by the + * getScrollableTracksViewportHeight() method. The valid values are: + *

+ * ScrollableSizeHint.NONE - return "false", which causes the height + * of the panel to be used when laying out the children + * ScrollableSizeHint.FIT - return "true", which causes the height of + * the viewport to be used when laying out the children + * ScrollableSizeHint.STRETCH - return "true" when the viewport height + * is greater than the height of the panel, "false" otherwise. + * + * @param scrollableHeight as represented by the ScrollableSizeHint enum. + */ + public void setScrollableHeight(ScrollableSizeHint scrollableHeight) { + this.scrollableHeight = scrollableHeight; + revalidate(); + } - /** - * Set the ScrollableSizeHint enum for the width. The enum is used to - * determine the boolean value that is returned by the - * getScrollableTracksViewportWidth() method. The valid values are: - * - * ScrollableSizeHint.NONE - return "false", which causes the width - * of the panel to be used when laying out the children - * ScrollableSizeHint.FIT - return "true", which causes the width of - * the viewport to be used when laying out the children - * ScrollableSizeHint.STRETCH - return "true" when the viewport width - * is greater than the width of the panel, "false" otherwise. - * - * @param scrollableWidth as represented by the ScrollableSizeHint enum. - */ - public void setScrollableWidth(ScrollableSizeHint scrollableWidth) - { - this.scrollableWidth = scrollableWidth; - revalidate(); - } + /** + * Get the width ScrollableSizeHint enum + * + * @return the ScrollableSizeHint enum for the width + */ + public ScrollableSizeHint getScrollableWidth() { + return scrollableWidth; + } - /** - * Get the block IncrementInfo for the specified orientation - * - * @return the block IncrementInfo for the specified orientation - */ - public IncrementInfo getScrollableBlockIncrement(int orientation) - { - return orientation == SwingConstants.HORIZONTAL ? horizontalBlock : verticalBlock; - } + /** + * Set the ScrollableSizeHint enum for the width. The enum is used to + * determine the boolean value that is returned by the + * getScrollableTracksViewportWidth() method. The valid values are: + *

+ * ScrollableSizeHint.NONE - return "false", which causes the width + * of the panel to be used when laying out the children + * ScrollableSizeHint.FIT - return "true", which causes the width of + * the viewport to be used when laying out the children + * ScrollableSizeHint.STRETCH - return "true" when the viewport width + * is greater than the width of the panel, "false" otherwise. + * + * @param scrollableWidth as represented by the ScrollableSizeHint enum. + */ + public void setScrollableWidth(ScrollableSizeHint scrollableWidth) { + this.scrollableWidth = scrollableWidth; + revalidate(); + } - /** - * Specify the information needed to do block scrolling. - * - * @param orientation specify the scrolling orientation. Must be either: - * SwingContants.HORIZONTAL or SwingContants.VERTICAL. - * @paran type specify how the amount parameter in the calculation of - * the scrollable amount. Valid values are: - * IncrementType.PERCENT - treat the amount as a % of the viewport size - * IncrementType.PIXEL - treat the amount as the scrollable amount - * @param amount a value used with the IncrementType to determine the - * scrollable amount - */ - public void setScrollableBlockIncrement(int orientation, IncrementType type, int amount) - { - IncrementInfo info = new IncrementInfo(type, amount); - setScrollableBlockIncrement(orientation, info); - } + /** + * Get the block IncrementInfo for the specified orientation + * + * @return the block IncrementInfo for the specified orientation + */ + public IncrementInfo getScrollableBlockIncrement(int orientation) { + return orientation == SwingConstants.HORIZONTAL ? horizontalBlock : verticalBlock; + } - /** - * Specify the information needed to do block scrolling. - * - * @param orientation specify the scrolling orientation. Must be either: - * SwingContants.HORIZONTAL or SwingContants.VERTICAL. - * @param info An IncrementInfo object containing information of how to - * calculate the scrollable amount. - */ - public void setScrollableBlockIncrement(int orientation, IncrementInfo info) - { - switch(orientation) - { - case SwingConstants.HORIZONTAL: - horizontalBlock = info; - break; - case SwingConstants.VERTICAL: - verticalBlock = info; - break; - default: - throw new IllegalArgumentException("Invalid orientation: " + orientation); - } - } + /** + * Specify the information needed to do block scrolling. + * + * @param orientation specify the scrolling orientation. Must be either: + * SwingContants.HORIZONTAL or SwingContants.VERTICAL. + * @param amount a value used with the IncrementType to determine the + * scrollable amount + * @paran type specify how the amount parameter in the calculation of + * the scrollable amount. Valid values are: + * IncrementType.PERCENT - treat the amount as a % of the viewport size + * IncrementType.PIXEL - treat the amount as the scrollable amount + */ + public void setScrollableBlockIncrement(int orientation, IncrementType type, int amount) { + IncrementInfo info = new IncrementInfo(type, amount); + setScrollableBlockIncrement(orientation, info); + } - /** - * Get the unit IncrementInfo for the specified orientation - * - * @return the unit IncrementInfo for the specified orientation - */ - public IncrementInfo getScrollableUnitIncrement(int orientation) - { - return orientation == SwingConstants.HORIZONTAL ? horizontalUnit : verticalUnit; - } + /** + * Specify the information needed to do block scrolling. + * + * @param orientation specify the scrolling orientation. Must be either: + * SwingContants.HORIZONTAL or SwingContants.VERTICAL. + * @param info An IncrementInfo object containing information of how to + * calculate the scrollable amount. + */ + public void setScrollableBlockIncrement(int orientation, IncrementInfo info) { + switch (orientation) { + case SwingConstants.HORIZONTAL: + horizontalBlock = info; + break; + case SwingConstants.VERTICAL: + verticalBlock = info; + break; + default: + throw new IllegalArgumentException("Invalid orientation: " + orientation); + } + } - /** - * Specify the information needed to do unit scrolling. - * - * @param orientation specify the scrolling orientation. Must be either: - * SwingContants.HORIZONTAL or SwingContants.VERTICAL. - * @paran type specify how the amount parameter in the calculation of - * the scrollable amount. Valid values are: - * IncrementType.PERCENT - treat the amount as a % of the viewport size - * IncrementType.PIXEL - treat the amount as the scrollable amount - * @param amount a value used with the IncrementType to determine the - * scrollable amount - */ - public void setScrollableUnitIncrement(int orientation, IncrementType type, int amount) - { - IncrementInfo info = new IncrementInfo(type, amount); - setScrollableUnitIncrement(orientation, info); - } + /** + * Get the unit IncrementInfo for the specified orientation + * + * @return the unit IncrementInfo for the specified orientation + */ + public IncrementInfo getScrollableUnitIncrement(int orientation) { + return orientation == SwingConstants.HORIZONTAL ? horizontalUnit : verticalUnit; + } - /** - * Specify the information needed to do unit scrolling. - * - * @param orientation specify the scrolling orientation. Must be either: - * SwingContants.HORIZONTAL or SwingContants.VERTICAL. - * @param info An IncrementInfo object containing information of how to - * calculate the scrollable amount. - */ - public void setScrollableUnitIncrement(int orientation, IncrementInfo info) - { - switch(orientation) - { - case SwingConstants.HORIZONTAL: - horizontalUnit = info; - break; - case SwingConstants.VERTICAL: - verticalUnit = info; - break; - default: - throw new IllegalArgumentException("Invalid orientation: " + orientation); - } - } + /** + * Specify the information needed to do unit scrolling. + * + * @param orientation specify the scrolling orientation. Must be either: + * SwingContants.HORIZONTAL or SwingContants.VERTICAL. + * @param amount a value used with the IncrementType to determine the + * scrollable amount + * @paran type specify how the amount parameter in the calculation of + * the scrollable amount. Valid values are: + * IncrementType.PERCENT - treat the amount as a % of the viewport size + * IncrementType.PIXEL - treat the amount as the scrollable amount + */ + public void setScrollableUnitIncrement(int orientation, IncrementType type, int amount) { + IncrementInfo info = new IncrementInfo(type, amount); + setScrollableUnitIncrement(orientation, info); + } - //Implement Scrollable interface + /** + * Specify the information needed to do unit scrolling. + * + * @param orientation specify the scrolling orientation. Must be either: + * SwingContants.HORIZONTAL or SwingContants.VERTICAL. + * @param info An IncrementInfo object containing information of how to + * calculate the scrollable amount. + */ + public void setScrollableUnitIncrement(int orientation, IncrementInfo info) { + switch (orientation) { + case SwingConstants.HORIZONTAL: + horizontalUnit = info; + break; + case SwingConstants.VERTICAL: + verticalUnit = info; + break; + default: + throw new IllegalArgumentException("Invalid orientation: " + orientation); + } + } - public Dimension getPreferredScrollableViewportSize() - { - return getPreferredSize(); - } + //Implement Scrollable interface - public int getScrollableUnitIncrement( - Rectangle visible, int orientation, int direction) - { - switch(orientation) - { - case SwingConstants.HORIZONTAL: - return getScrollableIncrement(horizontalUnit, visible.width); - case SwingConstants.VERTICAL: - return getScrollableIncrement(verticalUnit, visible.height); - default: - throw new IllegalArgumentException("Invalid orientation: " + orientation); - } - } + public Dimension getPreferredScrollableViewportSize() { + return getPreferredSize(); + } - public int getScrollableBlockIncrement( - Rectangle visible, int orientation, int direction) - { - switch(orientation) - { - case SwingConstants.HORIZONTAL: - return getScrollableIncrement(horizontalBlock, visible.width); - case SwingConstants.VERTICAL: - return getScrollableIncrement(verticalBlock, visible.height); - default: - throw new IllegalArgumentException("Invalid orientation: " + orientation); - } - } + public int getScrollableUnitIncrement( + Rectangle visible, int orientation, int direction) { + switch (orientation) { + case SwingConstants.HORIZONTAL: + return getScrollableIncrement(horizontalUnit, visible.width); + case SwingConstants.VERTICAL: + return getScrollableIncrement(verticalUnit, visible.height); + default: + throw new IllegalArgumentException("Invalid orientation: " + orientation); + } + } - protected int getScrollableIncrement(IncrementInfo info, int distance) - { - if (info.getIncrement() == IncrementType.PIXELS) - return info.getAmount(); - else - return distance * info.getAmount() / 100; - } + public int getScrollableBlockIncrement( + Rectangle visible, int orientation, int direction) { + switch (orientation) { + case SwingConstants.HORIZONTAL: + return getScrollableIncrement(horizontalBlock, visible.width); + case SwingConstants.VERTICAL: + return getScrollableIncrement(verticalBlock, visible.height); + default: + throw new IllegalArgumentException("Invalid orientation: " + orientation); + } + } - public boolean getScrollableTracksViewportWidth() - { - if (scrollableWidth == ScrollableSizeHint.NONE) - return false; + protected int getScrollableIncrement(IncrementInfo info, int distance) { + if (info.getIncrement() == IncrementType.PIXELS) + return info.getAmount(); + else + return distance * info.getAmount() / 100; + } - if (scrollableWidth == ScrollableSizeHint.FIT) - return true; + public boolean getScrollableTracksViewportWidth() { + if (scrollableWidth == ScrollableSizeHint.NONE) + return false; - // STRETCH sizing, use the greater of the panel or viewport width + if (scrollableWidth == ScrollableSizeHint.FIT) + return true; - if (getParent() instanceof JViewport) - { - return (((JViewport)getParent()).getWidth() > getPreferredSize().width); - } + // STRETCH sizing, use the greater of the panel or viewport width - return false; - } + if (getParent() instanceof JViewport) { + return (((JViewport) getParent()).getWidth() > getPreferredSize().width); + } - public boolean getScrollableTracksViewportHeight() - { - if (scrollableHeight == ScrollableSizeHint.NONE) - return false; + return false; + } - if (scrollableHeight == ScrollableSizeHint.FIT) - return true; + public boolean getScrollableTracksViewportHeight() { + if (scrollableHeight == ScrollableSizeHint.NONE) + return false; - // STRETCH sizing, use the greater of the panel or viewport height + if (scrollableHeight == ScrollableSizeHint.FIT) + return true; + + // STRETCH sizing, use the greater of the panel or viewport height - if (getParent() instanceof JViewport) - { - return (((JViewport)getParent()).getHeight() > getPreferredSize().height); - } + if (getParent() instanceof JViewport) { + return (((JViewport) getParent()).getHeight() > getPreferredSize().height); + } - return false; - } + return false; + } - /** - * Helper class to hold the information required to calculate the scroll amount. - */ - static class IncrementInfo - { - private IncrementType type; - private int amount; + /** + * Helper class to hold the information required to calculate the scroll amount. + */ + static class IncrementInfo { + private IncrementType type; + private int amount; - public IncrementInfo(IncrementType type, int amount) - { - this.type = type; - this.amount = amount; - } + public IncrementInfo(IncrementType type, int amount) { + this.type = type; + this.amount = amount; + } - public IncrementType getIncrement() - { - return type; - } + public IncrementType getIncrement() { + return type; + } - public int getAmount() - { - return amount; - } + public int getAmount() { + return amount; + } - public String toString() - { - return - "ScrollablePanel[" + - type + ", " + - amount + "]"; - } - } + public String toString() { + return + "ScrollablePanel[" + + type + ", " + + amount + "]"; + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/StudioFrame.java b/src/com/gpl/rpg/atcontentstudio/ui/StudioFrame.java index 25ccaa5..3fa2e14 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/StudioFrame.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/StudioFrame.java @@ -1,29 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; - -import javax.swing.JFrame; -import javax.swing.JList; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.JSplitPane; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.UIManager.LookAndFeelInfo; -import javax.swing.UnsupportedLookAndFeelException; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.ConfigCache; import com.gpl.rpg.atcontentstudio.model.GameDataElement; @@ -36,223 +12,230 @@ import com.gpl.rpg.atcontentstudio.model.saves.SavedGame; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData; +import javax.swing.*; +import javax.swing.UIManager.LookAndFeelInfo; +import java.awt.*; +import java.awt.event.*; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.ArrayList; + public class StudioFrame extends JFrame { - private static final long serialVersionUID = -3391514100319186661L; - - - final ProjectsTree projectTree; - final EditorsArea editors; - - final WorkspaceActions actions = new WorkspaceActions(); - - public StudioFrame(String name) { - super(name); - setIconImage(DefaultIcons.getMainIconImage()); - - final JSplitPane topDown = new JSplitPane(JSplitPane.VERTICAL_SPLIT); - final JSplitPane leftRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); - - @SuppressWarnings("rawtypes") - JList notifs = new NotificationsPane(); - projectTree = new ProjectsTree(); - editors = new EditorsArea(); - - setJMenuBar(new JMenuBar()); - buildMenu(); - - JScrollPane treeScroller = new JScrollPane(projectTree); - treeScroller.getVerticalScrollBar().setUnitIncrement(16); - leftRight.setLeftComponent(treeScroller); - leftRight.setRightComponent(editors); - leftRight.setName("StudioFrame.leftRight"); - topDown.setTopComponent(leftRight); - JScrollPane notifScroller = new JScrollPane(notifs); - notifScroller.getVerticalScrollBar().setUnitIncrement(16); - topDown.setBottomComponent(notifScroller); - topDown.setName("StudioFrame.topDown"); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(topDown, BorderLayout.CENTER); - - addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent e) { - Workspace.activeWorkspace.preferences.windowSize = StudioFrame.this.getSize(); - } - }); - - pack(); - if (Workspace.activeWorkspace.preferences.windowSize != null) { - setSize(Workspace.activeWorkspace.preferences.windowSize); - } else { - setSize(800, 600); - } - - if (Workspace.activeWorkspace.preferences.splittersPositions.get(topDown.getName()) != null) { - topDown.setDividerLocation(Workspace.activeWorkspace.preferences.splittersPositions.get(topDown.getName())); - } else { - topDown.setDividerLocation(0.2); - } - topDown.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - Workspace.activeWorkspace.preferences.splittersPositions.put(topDown.getName(), topDown.getDividerLocation()); - } - }); - if (Workspace.activeWorkspace.preferences.splittersPositions.get(leftRight.getName()) != null) { - leftRight.setDividerLocation(Workspace.activeWorkspace.preferences.splittersPositions.get(leftRight.getName())); - } else { - leftRight.setDividerLocation(0.3); - } - leftRight.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { - @Override - public void propertyChange(PropertyChangeEvent evt) { - Workspace.activeWorkspace.preferences.splittersPositions.put(leftRight.getName(), leftRight.getDividerLocation()); - } - }); - - showAbout(); - - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent e) { - Workspace.saveActive(); - actions.exitATCS.actionPerformed(null); - } - }); - } - - private void buildMenu() { - JMenu fileMenu = new JMenu("File"); - fileMenu.add(new JMenuItem(actions.createProject)); - fileMenu.add(new JMenuItem(actions.openProject)); - fileMenu.add(new JMenuItem(actions.closeProject)); - fileMenu.add(new JMenuItem(actions.deleteProject)); - fileMenu.add(new JSeparator()); - fileMenu.add(new JMenuItem(actions.editWorkspaceSettings)); - fileMenu.add(new JSeparator()); - fileMenu.add(new JMenuItem(actions.exitATCS)); - getJMenuBar().add(fileMenu); - - JMenu projectMenu = new JMenu("Project"); - projectMenu.add(new JMenuItem(actions.saveElement)); - projectMenu.add(new JMenuItem(actions.deleteSelected)); - projectMenu.add(new JSeparator()); - projectMenu.add(new JMenuItem(actions.createGDE)); - projectMenu.add(new JMenuItem(actions.importJSON)); - projectMenu.add(new JMenuItem(actions.createMap)); - projectMenu.add(new JMenuItem(actions.createWorldmap)); - projectMenu.add(new JMenuItem(actions.loadSave)); - getJMenuBar().add(projectMenu); - - JMenu toolsMenu = new JMenu("Tools"); - toolsMenu.add(new JMenuItem(actions.compareItems)); - toolsMenu.add(new JMenuItem(actions.compareNPCs)); - toolsMenu.add(new JSeparator()); - toolsMenu.add(new JMenuItem(actions.runBeanShell)); - toolsMenu.add(new JSeparator()); - toolsMenu.add(new JMenuItem(actions.exportProject)); - getJMenuBar().add(toolsMenu); - - JMenu viewMenu = new JMenu("View"); - JMenu changeLaF = new JMenu("Change Look and Feel"); - for (final LookAndFeelInfo i : UIManager.getInstalledLookAndFeels()) { - final JMenuItem lafItem = new JMenuItem("Switch to "+i.getName()); - changeLaF.add(lafItem); - lafItem.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - try { - UIManager.setLookAndFeel(i.getClassName()); - ATContentStudio.scaleUIFont(); - SwingUtilities.updateComponentTreeUI(ATContentStudio.frame); - ConfigCache.setFavoriteLaFClassName(i.getClassName()); - } catch (ClassNotFoundException e1) { - e1.printStackTrace(); - } catch (InstantiationException e1) { - e1.printStackTrace(); - } catch (IllegalAccessException e1) { - e1.printStackTrace(); - } catch (UnsupportedLookAndFeelException e1) { - e1.printStackTrace(); - } - } - }); - } - viewMenu.add(changeLaF); - viewMenu.add(new JSeparator()); - viewMenu.add(new JMenuItem(actions.showAbout)); - getJMenuBar().add(viewMenu); - } - - public void openEditor(JSONElement node) { - node.link(); - editors.openEditor(node); - } - - public void openEditor(Spritesheet node) { - editors.openEditor(node); - } - - public void openEditor(TMXMap node) { - node.parse(); - editors.openEditor(node); - } - - public void openEditor(WriterModeData node) { - node.link(); - editors.openEditor(node); - } - - - public void openEditor(GameDataElement node) { - if (node instanceof JSONElement) { - openEditor((JSONElement) node); - } else if (node instanceof Spritesheet) { - openEditor((Spritesheet) node); - } else if (node instanceof TMXMap) { - openEditor((TMXMap) node); - } else if (node instanceof WorldmapSegment) { - openEditor((WorldmapSegment) node); - } else if (node instanceof WriterModeData) { - openEditor((WriterModeData) node); - } - } - - public void openEditor(SavedGame save) { - editors.openEditor(save); - } - - public void openEditor(WorldmapSegment node) { - editors.openEditor(node); - } - - public void closeEditor(ProjectTreeNode node) { - editors.closeEditor(node); - } - - public void selectInTree(ProjectTreeNode node) { - projectTree.setSelectedNode(node); - } - - public void editorChanged(Editor e) { - editors.editorTabChanged(e); - } - - public void editorChanged(ProjectTreeNode node) { - editors.editorTabChanged(node); - } - - public void nodeChanged(ProjectTreeNode node) { - node.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(node); - } - - public void showAbout() { - editors.showAbout(); - } + private static final long serialVersionUID = -3391514100319186661L; + + + final ProjectsTree projectTree; + final EditorsArea editors; + + final WorkspaceActions actions = new WorkspaceActions(); + + public StudioFrame(String name) { + super(name); + setIconImage(DefaultIcons.getMainIconImage()); + + final JSplitPane topDown = new JSplitPane(JSplitPane.VERTICAL_SPLIT); + final JSplitPane leftRight = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); + + @SuppressWarnings("rawtypes") + JList notifs = new NotificationsPane(); + projectTree = new ProjectsTree(); + editors = new EditorsArea(); + + setJMenuBar(new JMenuBar()); + buildMenu(); + + JScrollPane treeScroller = new JScrollPane(projectTree); + treeScroller.getVerticalScrollBar().setUnitIncrement(16); + leftRight.setLeftComponent(treeScroller); + leftRight.setRightComponent(editors); + leftRight.setName("StudioFrame.leftRight"); + topDown.setTopComponent(leftRight); + JScrollPane notifScroller = new JScrollPane(notifs); + notifScroller.getVerticalScrollBar().setUnitIncrement(16); + topDown.setBottomComponent(notifScroller); + topDown.setName("StudioFrame.topDown"); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(topDown, BorderLayout.CENTER); + + addComponentListener(new ComponentAdapter() { + @Override + public void componentResized(ComponentEvent e) { + Workspace.activeWorkspace.preferences.windowSize = StudioFrame.this.getSize(); + } + }); + + pack(); + if (Workspace.activeWorkspace.preferences.windowSize != null) { + setSize(Workspace.activeWorkspace.preferences.windowSize); + } else { + setSize(800, 600); + } + + if (Workspace.activeWorkspace.preferences.splittersPositions.get(topDown.getName()) != null) { + topDown.setDividerLocation(Workspace.activeWorkspace.preferences.splittersPositions.get(topDown.getName())); + } else { + topDown.setDividerLocation(0.2); + } + topDown.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent evt) { + Workspace.activeWorkspace.preferences.splittersPositions.put(topDown.getName(), topDown.getDividerLocation()); + } + }); + if (Workspace.activeWorkspace.preferences.splittersPositions.get(leftRight.getName()) != null) { + leftRight.setDividerLocation(Workspace.activeWorkspace.preferences.splittersPositions.get(leftRight.getName())); + } else { + leftRight.setDividerLocation(0.3); + } + leftRight.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent evt) { + Workspace.activeWorkspace.preferences.splittersPositions.put(leftRight.getName(), leftRight.getDividerLocation()); + } + }); + + showAbout(); + + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + Workspace.saveActive(); + actions.exitATCS.actionPerformed(null); + } + }); + } + + private void buildMenu() { + JMenu fileMenu = new JMenu("File"); + fileMenu.add(new JMenuItem(actions.createProject)); + fileMenu.add(new JMenuItem(actions.openProject)); + fileMenu.add(new JMenuItem(actions.closeProject)); + fileMenu.add(new JMenuItem(actions.deleteProject)); + fileMenu.add(new JSeparator()); + fileMenu.add(new JMenuItem(actions.editWorkspaceSettings)); + fileMenu.add(new JSeparator()); + fileMenu.add(new JMenuItem(actions.exitATCS)); + getJMenuBar().add(fileMenu); + + JMenu projectMenu = new JMenu("Project"); + projectMenu.add(new JMenuItem(actions.saveElement)); + projectMenu.add(new JMenuItem(actions.deleteSelected)); + projectMenu.add(new JSeparator()); + projectMenu.add(new JMenuItem(actions.createGDE)); + projectMenu.add(new JMenuItem(actions.importJSON)); + projectMenu.add(new JMenuItem(actions.createMap)); + projectMenu.add(new JMenuItem(actions.createWorldmap)); + projectMenu.add(new JMenuItem(actions.loadSave)); + getJMenuBar().add(projectMenu); + + JMenu toolsMenu = new JMenu("Tools"); + toolsMenu.add(new JMenuItem(actions.compareItems)); + toolsMenu.add(new JMenuItem(actions.compareNPCs)); + toolsMenu.add(new JSeparator()); + toolsMenu.add(new JMenuItem(actions.runBeanShell)); + toolsMenu.add(new JSeparator()); + toolsMenu.add(new JMenuItem(actions.exportProject)); + getJMenuBar().add(toolsMenu); + + JMenu viewMenu = new JMenu("View"); + JMenu changeLaF = new JMenu("Change Look and Feel"); + for (final LookAndFeelInfo i : UIManager.getInstalledLookAndFeels()) { + final JMenuItem lafItem = new JMenuItem("Switch to " + i.getName()); + changeLaF.add(lafItem); + lafItem.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + UIManager.setLookAndFeel(i.getClassName()); + ATContentStudio.scaleUIFont(); + SwingUtilities.updateComponentTreeUI(ATContentStudio.frame); + ConfigCache.setFavoriteLaFClassName(i.getClassName()); + } catch (ClassNotFoundException e1) { + e1.printStackTrace(); + } catch (InstantiationException e1) { + e1.printStackTrace(); + } catch (IllegalAccessException e1) { + e1.printStackTrace(); + } catch (UnsupportedLookAndFeelException e1) { + e1.printStackTrace(); + } + } + }); + } + viewMenu.add(changeLaF); + viewMenu.add(new JSeparator()); + viewMenu.add(new JMenuItem(actions.showAbout)); + getJMenuBar().add(viewMenu); + } + + public void openEditor(JSONElement node) { + node.link(); + editors.openEditor(node); + } + + public void openEditor(Spritesheet node) { + editors.openEditor(node); + } + + public void openEditor(TMXMap node) { + node.parse(); + editors.openEditor(node); + } + + public void openEditor(WriterModeData node) { + node.link(); + editors.openEditor(node); + } + + + public void openEditor(GameDataElement node) { + if (node instanceof JSONElement) { + openEditor((JSONElement) node); + } else if (node instanceof Spritesheet) { + openEditor((Spritesheet) node); + } else if (node instanceof TMXMap) { + openEditor((TMXMap) node); + } else if (node instanceof WorldmapSegment) { + openEditor((WorldmapSegment) node); + } else if (node instanceof WriterModeData) { + openEditor((WriterModeData) node); + } + } + + public void openEditor(SavedGame save) { + editors.openEditor(save); + } + + public void openEditor(WorldmapSegment node) { + editors.openEditor(node); + } + + public void closeEditor(ProjectTreeNode node) { + editors.closeEditor(node); + } + + public void selectInTree(ProjectTreeNode node) { + projectTree.setSelectedNode(node); + } + + public void editorChanged(Editor e) { + editors.editorTabChanged(e); + } + + public void editorChanged(ProjectTreeNode node) { + editors.editorTabChanged(node); + } + + public void nodeChanged(ProjectTreeNode node) { + node.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(node); + } + + public void showAbout() { + editors.showAbout(); + } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/TMXMapCreationWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/TMXMapCreationWizard.java index bc59e26..55f3c26 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/TMXMapCreationWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/TMXMapCreationWizard.java @@ -1,31 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.io.File; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.ButtonGroup; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.event.ListDataListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement.State; import com.gpl.rpg.atcontentstudio.model.GameSource; @@ -33,267 +7,280 @@ import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.ListDataListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class TMXMapCreationWizard extends JDialog { - private static final long serialVersionUID = -474689694453543575L; - private static final String DEFAULT_TEMPLATE = "template.tmx"; - - - private TMXMap creation = null; - final File templateFile; - - final JLabel message; - final JRadioButton useTemplate, copyMap; - final JComboBox templateCombo; - final JTextField idField; - final JButton ok; - final Project proj; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public TMXMapCreationWizard(final Project proj) { - super(ATContentStudio.frame); - this.proj = proj; - templateFile=new File(proj.baseContent.gameMaps.mapFolder, DEFAULT_TEMPLATE); - - setTitle("Create new TMX map"); - - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - pane.add(new JLabel("Create a new TMX map."), JideBoxLayout.FIX); - - message = new JLabel("Enter new map name:"); - pane.add(message, JideBoxLayout.FIX); - - final JPanel idPane = new JPanel(); - idPane.setLayout(new BorderLayout()); - JLabel idLabel = new JLabel("Internal ID: "); - idPane.add(idLabel, BorderLayout.WEST); - idField = new JTextField(""); - idField.setEditable(true); - idPane.add(idField, BorderLayout.CENTER); - pane.add(idPane, JideBoxLayout.FIX); + private static final long serialVersionUID = -474689694453543575L; + private static final String DEFAULT_TEMPLATE = "template.tmx"; - useTemplate = new JRadioButton("Use default template file ("+DEFAULT_TEMPLATE+")"); - useTemplate.setToolTipText(templateFile.getAbsolutePath()); - pane.add(useTemplate, JideBoxLayout.FIX); - copyMap = new JRadioButton("Copy existing map"); - pane.add(copyMap, JideBoxLayout.FIX); - - ButtonGroup radioGroup = new ButtonGroup(); - radioGroup.add(useTemplate); - radioGroup.add(copyMap); - - final JPanel templatePane = new JPanel(); - templatePane.setLayout(new BorderLayout()); - JLabel templateLabel = new JLabel("Template to copy: "); - templatePane.add(templateLabel, BorderLayout.WEST); - templateCombo = new JComboBox(new TemplateComboModel()); - templateCombo.setRenderer(new TemplateComboCellRenderer()); - if (proj.getMap(DEFAULT_TEMPLATE) != null) templateCombo.setSelectedItem(proj.getMap(DEFAULT_TEMPLATE)); - templatePane.add(templateCombo, BorderLayout.CENTER); - pane.add(templatePane, JideBoxLayout.FIX); - pane.add(templateCombo); - - if (templateFile.exists()) { - useTemplate.setSelected(true); - copyMap.setSelected(false); - templateCombo.setEnabled(false); - } else { - useTemplate.setSelected(false); - useTemplate.setEnabled(false); - useTemplate.setToolTipText("Cannot find file "+templateFile.getAbsolutePath()); - templateCombo.setEnabled(true); - copyMap.setSelected(true); - } - - ActionListener radioListener = new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (useTemplate.isSelected()) { - templateCombo.setEnabled(false); - } else if(copyMap.isSelected()) { - templateCombo.setEnabled(true); - } - updateStatus(); - } - }; - useTemplate.addActionListener(radioListener); - copyMap.addActionListener(radioListener); - - templateCombo.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - updateStatus(); - } - }); - - pane.add(new JPanel(), JideBoxLayout.VARY); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancel = new JButton("Cancel"); - buttonPane.add(cancel, JideBoxLayout.FIX); - ok = new JButton("Ok"); - buttonPane.add(ok, JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - - if (copyMap.isSelected()) { - creation = ((TMXMap)templateCombo.getSelectedItem()).clone(); - } else if (useTemplate.isSelected()) { - creation = new TMXMap(proj.createdContent.gameMaps, templateFile); - creation.parse(); - } - creation.id = idField.getText(); - creation.tmxFile = new File(creation.id+".tmx"); - TMXMapCreationWizard.this.setVisible(false); - TMXMapCreationWizard.this.dispose(); - creation.state = State.created; - proj.createElement(creation); - notifyCreated(); - ATContentStudio.frame.selectInTree(creation); - ATContentStudio.frame.openEditor(creation); - } - }); - - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - creation = null; - TMXMapCreationWizard.this.setVisible(false); - TMXMapCreationWizard.this.dispose(); - } - }); - - DocumentListener statusUpdater = new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void insertUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void changedUpdate(DocumentEvent e) { - updateStatus(); - } - }; - idField.getDocument().addDocumentListener(statusUpdater); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - setMinimumSize(new Dimension(350,250)); - updateStatus(); - pack(); - - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - } - - public void updateStatus() { - boolean trouble = false; - message.setText("Looks OK to me."); - if (copyMap.isSelected() && templateCombo.getSelectedItem() == null) { - message.setText("Select a map template below:"); - trouble = true; - } else if (idField.getText() == null || idField.getText().length() <= 0) { - message.setText("Internal ID must not be empty."); - trouble = true; - } else if (proj.getMap(idField.getText()) != null) { - if (proj.getMap(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("A map with the same ID was already created in this project."); - trouble = true; - } else if (proj.getMap(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("A map with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getMap(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("A map with the same ID exists in the game. The new one will be added under \"altered\"."); - } - } - - ok.setEnabled(!trouble); - - message.revalidate(); - message.repaint(); - } - - public static interface CreationCompletedListener { - public void mapCreated(TMXMap created); - } - - private List listeners = new CopyOnWriteArrayList(); - - public void addCreationListener(CreationCompletedListener l) { - listeners.add(l); - } - - public void notifyCreated() { - for (CreationCompletedListener l : listeners) { - l.mapCreated(creation); - } - } - - class TemplateComboModel implements ComboBoxModel { - - Object selected; - @Override - public int getSize() { - return proj.getMapCount(); - } + private TMXMap creation = null; + final File templateFile; - @Override - public TMXMap getElementAt(int index) { - return proj.getMap(index); - } + final JLabel message; + final JRadioButton useTemplate, copyMap; + final JComboBox templateCombo; + final JTextField idField; + final JButton ok; + final Project proj; - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } + @SuppressWarnings({"unchecked", "rawtypes"}) + public TMXMapCreationWizard(final Project proj) { + super(ATContentStudio.frame); + this.proj = proj; + templateFile = new File(proj.baseContent.gameMaps.mapFolder, DEFAULT_TEMPLATE); - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } + setTitle("Create new TMX map"); - @Override - public void setSelectedItem(Object anItem) { - selected = anItem; - } + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - @Override - public Object getSelectedItem() { - return selected; - } - - } - - class TemplateComboCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 5621373849299980998L; + pane.add(new JLabel("Create a new TMX map."), JideBoxLayout.FIX); + + message = new JLabel("Enter new map name:"); + pane.add(message, JideBoxLayout.FIX); + + final JPanel idPane = new JPanel(); + idPane.setLayout(new BorderLayout()); + JLabel idLabel = new JLabel("Internal ID: "); + idPane.add(idLabel, BorderLayout.WEST); + idField = new JTextField(""); + idField.setEditable(true); + idPane.add(idField, BorderLayout.CENTER); + pane.add(idPane, JideBoxLayout.FIX); + + useTemplate = new JRadioButton("Use default template file (" + DEFAULT_TEMPLATE + ")"); + useTemplate.setToolTipText(templateFile.getAbsolutePath()); + pane.add(useTemplate, JideBoxLayout.FIX); + copyMap = new JRadioButton("Copy existing map"); + pane.add(copyMap, JideBoxLayout.FIX); + + ButtonGroup radioGroup = new ButtonGroup(); + radioGroup.add(useTemplate); + radioGroup.add(copyMap); + + final JPanel templatePane = new JPanel(); + templatePane.setLayout(new BorderLayout()); + JLabel templateLabel = new JLabel("Template to copy: "); + templatePane.add(templateLabel, BorderLayout.WEST); + templateCombo = new JComboBox(new TemplateComboModel()); + templateCombo.setRenderer(new TemplateComboCellRenderer()); + if (proj.getMap(DEFAULT_TEMPLATE) != null) templateCombo.setSelectedItem(proj.getMap(DEFAULT_TEMPLATE)); + templatePane.add(templateCombo, BorderLayout.CENTER); + pane.add(templatePane, JideBoxLayout.FIX); + pane.add(templateCombo); + + if (templateFile.exists()) { + useTemplate.setSelected(true); + copyMap.setSelected(false); + templateCombo.setEnabled(false); + } else { + useTemplate.setSelected(false); + useTemplate.setEnabled(false); + useTemplate.setToolTipText("Cannot find file " + templateFile.getAbsolutePath()); + templateCombo.setEnabled(true); + copyMap.setSelected(true); + } + + ActionListener radioListener = new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (useTemplate.isSelected()) { + templateCombo.setEnabled(false); + } else if (copyMap.isSelected()) { + templateCombo.setEnabled(true); + } + updateStatus(); + } + }; + useTemplate.addActionListener(radioListener); + copyMap.addActionListener(radioListener); + + templateCombo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + updateStatus(); + } + }); + + pane.add(new JPanel(), JideBoxLayout.VARY); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancel = new JButton("Cancel"); + buttonPane.add(cancel, JideBoxLayout.FIX); + ok = new JButton("Ok"); + buttonPane.add(ok, JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + + ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + + if (copyMap.isSelected()) { + creation = ((TMXMap) templateCombo.getSelectedItem()).clone(); + } else if (useTemplate.isSelected()) { + creation = new TMXMap(proj.createdContent.gameMaps, templateFile); + creation.parse(); + } + creation.id = idField.getText(); + creation.tmxFile = new File(creation.id + ".tmx"); + TMXMapCreationWizard.this.setVisible(false); + TMXMapCreationWizard.this.dispose(); + creation.state = State.created; + proj.createElement(creation); + notifyCreated(); + ATContentStudio.frame.selectInTree(creation); + ATContentStudio.frame.openEditor(creation); + } + }); + + cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + creation = null; + TMXMapCreationWizard.this.setVisible(false); + TMXMapCreationWizard.this.dispose(); + } + }); + + DocumentListener statusUpdater = new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateStatus(); + } + }; + idField.getDocument().addDocumentListener(statusUpdater); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + setMinimumSize(new Dimension(350, 250)); + updateStatus(); + pack(); + + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + } + + public void updateStatus() { + boolean trouble = false; + message.setText("Looks OK to me."); + if (copyMap.isSelected() && templateCombo.getSelectedItem() == null) { + message.setText("Select a map template below:"); + trouble = true; + } else if (idField.getText() == null || idField.getText().length() <= 0) { + message.setText("Internal ID must not be empty."); + trouble = true; + } else if (proj.getMap(idField.getText()) != null) { + if (proj.getMap(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("A map with the same ID was already created in this project."); + trouble = true; + } else if (proj.getMap(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("A map with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getMap(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("A map with the same ID exists in the game. The new one will be added under \"altered\"."); + } + } + + ok.setEnabled(!trouble); + + message.revalidate(); + message.repaint(); + } + + public static interface CreationCompletedListener { + public void mapCreated(TMXMap created); + } + + private List listeners = new CopyOnWriteArrayList(); + + public void addCreationListener(CreationCompletedListener l) { + listeners.add(l); + } + + public void notifyCreated() { + for (CreationCompletedListener l : listeners) { + l.mapCreated(creation); + } + } + + class TemplateComboModel implements ComboBoxModel { + + Object selected; + + @Override + public int getSize() { + return proj.getMapCount(); + } + + @Override + public TMXMap getElementAt(int index) { + return proj.getMap(index); + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addListDataListener(ListDataListener l) { + listeners.add(l); + } + + @Override + public void removeListDataListener(ListDataListener l) { + listeners.remove(l); + } + + @Override + public void setSelectedItem(Object anItem) { + selected = anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + + } + + class TemplateComboCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 5621373849299980998L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel && value != null) { + ((JLabel) c).setText(((TMXMap) value).getDesc()); + ((JLabel) c).setIcon(new ImageIcon(DefaultIcons.getTiledIconIcon())); + } + return c; + } + } - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel && value != null) { - ((JLabel)c).setText(((TMXMap)value).getDesc()); - ((JLabel)c).setIcon(new ImageIcon(DefaultIcons.getTiledIconIcon())); - } - return c; - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java index d4725f1..4f3c4cc 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java @@ -1,54 +1,51 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Frame; -import java.awt.Toolkit; - -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JOptionPane; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import java.awt.*; + public class WorkerDialog extends JDialog { -private static final long serialVersionUID = 8239669104275145995L; + private static final long serialVersionUID = 8239669104275145995L; - private WorkerDialog(String message, Frame parent) { - super(parent, "Loading..."); - this.setIconImage(DefaultIcons.getMainIconImage()); - this.getContentPane().setLayout(new JideBoxLayout(this.getContentPane(), JideBoxLayout.PAGE_AXIS, 6)); - this.getContentPane().add(new JLabel("Please wait.
"+message+"
"), JideBoxLayout.VARY); - JMovingIdler idler = new JMovingIdler(); - idler.setBackground(Color.WHITE); - idler.setForeground(Color.GREEN); - idler.start(); - this.getContentPane().add(idler, JideBoxLayout.FIX); - this.pack(); - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = this.getSize(); - idler.setPreferredSize(new Dimension(wdim.width, 10)); - this.pack(); - wdim = this.getSize(); - this.setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); - } - - public static void showTaskMessage(String message, Frame parent, Runnable workload) { - showTaskMessage(message, parent, false, workload); - } - - public static void showTaskMessage(final String message, final Frame parent, final boolean showConfirm, final Runnable workload) { - new Thread() { - public void run() { - WorkerDialog info = new WorkerDialog(message, parent); - info.setVisible(true); - workload.run(); - info.dispose(); - if (showConfirm) JOptionPane.showMessageDialog(parent, "Done !"); - }; - }.start(); - } + private WorkerDialog(String message, Frame parent) { + super(parent, "Loading..."); + this.setIconImage(DefaultIcons.getMainIconImage()); + this.getContentPane().setLayout(new JideBoxLayout(this.getContentPane(), JideBoxLayout.PAGE_AXIS, 6)); + this.getContentPane().add(new JLabel("Please wait.
" + message + "
"), JideBoxLayout.VARY); + JMovingIdler idler = new JMovingIdler(); + idler.setBackground(Color.WHITE); + idler.setForeground(Color.GREEN); + idler.start(); + this.getContentPane().add(idler, JideBoxLayout.FIX); + this.pack(); + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = this.getSize(); + idler.setPreferredSize(new Dimension(wdim.width, 10)); + this.pack(); + wdim = this.getSize(); + this.setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); + } + + public static void showTaskMessage(String message, Frame parent, Runnable workload) { + showTaskMessage(message, parent, false, workload); + } + + public static void showTaskMessage(final String message, final Frame parent, final boolean showConfirm, final Runnable workload) { + new Thread() { + public void run() { + WorkerDialog info = new WorkerDialog(message, parent); + info.setVisible(true); + workload.run(); + info.dispose(); + if (showConfirm) + JOptionPane.showMessageDialog(parent, "Done !"); + } + + ; + }.start(); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java index 7f4d10c..4ead144 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java @@ -1,38 +1,8 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.Action; -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.KeyStroke; -import javax.swing.tree.TreePath; - import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.ClosedProject; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.SaveEvent; -import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataCategory; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; +import com.gpl.rpg.atcontentstudio.model.*; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.Worldmap; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; @@ -43,180 +13,216 @@ import com.gpl.rpg.atcontentstudio.ui.tools.BeanShellView; import com.gpl.rpg.atcontentstudio.ui.tools.ItemsTableView; import com.gpl.rpg.atcontentstudio.ui.tools.NPCsTableView; +import javax.swing.*; +import javax.swing.tree.TreePath; +import java.awt.event.ActionEvent; +import java.awt.event.KeyEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; + public class WorkspaceActions { - ProjectTreeNode selectedNode = null; - TreePath[] selectedPaths = null; - - public ATCSAction createProject = new ATCSAction("Create project...", "Opens the project creation wizard") { - public void actionPerformed(ActionEvent e) { - new ProjectCreationWizard().setVisible(true); - }; - }; - + ProjectTreeNode selectedNode = null; + TreePath[] selectedPaths = null; - public ATCSAction closeProject = new ATCSAction("Close project", "Closes the project, unloading all resources from memory") { - public void actionPerformed(ActionEvent e) { - if (!(selectedNode instanceof Project)) return; - Workspace.closeProject((Project) selectedNode); - selectedNode = null; - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode instanceof Project); - }; - }; - + public ATCSAction createProject = new ATCSAction("Create project...", "Opens the project creation wizard") { + public void actionPerformed(ActionEvent e) { + new ProjectCreationWizard().setVisible(true); + } - public ATCSAction openProject = new ATCSAction("Open project", "Opens the project, loading all necessary resources in memory") { - public void actionPerformed(ActionEvent e) { - if (!(selectedNode instanceof ClosedProject)) return; - Workspace.openProject((ClosedProject) selectedNode); - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode instanceof ClosedProject); - }; - }; - - public ATCSAction deleteProject = new ATCSAction("Delete project", "Deletes the project, and all created/altered data, from disk") { - public void actionPerformed(ActionEvent e) { - if (selectedNode instanceof Project) { - if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { - Workspace.deleteProject((Project)selectedNode); - } - } else if (selectedNode instanceof ClosedProject) { - if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { - Workspace.deleteProject((ClosedProject)selectedNode); - } - } - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode instanceof Project || selectedNode instanceof ClosedProject); - }; - }; - - public ATCSAction saveElement = new ATCSAction("Save this element", "Saves the current state of this element on disk"){ - public void actionPerformed(ActionEvent e) { - if (!(selectedNode instanceof GameDataElement)) return; - final GameDataElement node = ((GameDataElement)selectedNode); - if (node.needsSaving()){ - node.save(); - ATContentStudio.frame.nodeChanged(node); - } - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - if (selectedNode instanceof GameDataElement) { - setEnabled(((GameDataElement)selectedNode).needsSaving()); - } else { - setEnabled(false); - } - }; - }; - - public ATCSAction deleteSelected = new ATCSAction("Delete", "Deletes the selected items") { - boolean multiMode = false; - List elementsToDelete = null; - public void init() { - putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); - }; - public void actionPerformed(ActionEvent e) { - if (multiMode) { - if (elementsToDelete == null) return; - final Map, Set> impactedCategories = new IdentityHashMap, Set>(); - for (GameDataElement element : elementsToDelete) { - ATContentStudio.frame.closeEditor(element); - element.childrenRemoved(new ArrayList()); - if (element instanceof JSONElement) { - if (element.getParent() instanceof GameDataCategory) { - @SuppressWarnings("unchecked") - GameDataCategory category = (GameDataCategory) element.getParent(); - category.remove(element); - if (impactedCategories.get(category) == null) { - impactedCategories.put(category, new HashSet()); - } - - GameDataElement newOne = element.getProject().getGameDataElement(((JSONElement)element).getClass(), element.id); - if (element instanceof Quest) { - for (QuestStage oldStage : ((Quest) element).stages) { - QuestStage newStage = newOne != null ? ((Quest) newOne).getStage(oldStage.progress) : null; - for (GameDataElement backlink : oldStage.getBacklinks()) { - backlink.elementChanged(oldStage, newStage); - } - } - } - for (GameDataElement backlink : element.getBacklinks()) { - backlink.elementChanged(element, newOne); - } - impactedCategories.get(category).add(((JSONElement) element).jsonFile); - } - } else if (element instanceof TMXMap) { - ((TMXMap)element).delete(); - GameDataElement newOne = element.getProject().getMap(element.id); - for (GameDataElement backlink : element.getBacklinks()) { - backlink.elementChanged(element, newOne); - } - } else if (element instanceof WriterModeData) { - WriterModeDataSet parent = (WriterModeDataSet) element.getParent(); - parent.writerModeDataList.remove(element); - } else if (element instanceof WorldmapSegment) { - if (element.getParent() instanceof Worldmap) { - ((Worldmap)element.getParent()).remove(element); - element.save(); - for (GameDataElement backlink : element.getBacklinks()) { - backlink.elementChanged(element, element.getProject().getWorldmapSegment(element.id)); - } - } - } - } - new Thread() { - @Override - public void run() { - final List events = new ArrayList(); - List catEvents; - for (GameDataCategory category : impactedCategories.keySet()) { - for (File f : impactedCategories.get(category)) { - catEvents = category.attemptSave(true, f.getName()); - if (catEvents.isEmpty()) { - category.save(f); - } else { - events.addAll(catEvents); - } - } - } - if (!events.isEmpty()) { - new SaveItemsWizard(events, null).setVisible(true); - } - } - }.start(); - } else { - if (!(selectedNode instanceof GameDataElement)) return; - final GameDataElement node = ((GameDataElement)selectedNode); - ATContentStudio.frame.closeEditor(node); - new Thread() { - @Override - public void run() { - node.childrenRemoved(new ArrayList()); - if (node instanceof JSONElement) { - if (node.getParent() instanceof GameDataCategory) { - ((GameDataCategory)node.getParent()).remove(node); - List events = node.attemptSave(); - if (events == null || events.isEmpty()) { - node.save(); - } else { - new SaveItemsWizard(events, null).setVisible(true); - } - GameDataElement newOne = node.getProject().getGameDataElement(((JSONElement)node).getClass(), node.id); - if (node instanceof Quest) { - for (QuestStage oldStage : ((Quest) node).stages) { - QuestStage newStage = newOne != null ? ((Quest) newOne).getStage(oldStage.progress) : null; - for (GameDataElement backlink : oldStage.getBacklinks()) { - backlink.elementChanged(oldStage, newStage); - } - } - } - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, newOne); - } - } + ; + }; + + + public ATCSAction closeProject = new ATCSAction("Close project", "Closes the project, unloading all resources from memory") { + public void actionPerformed(ActionEvent e) { + if (!(selectedNode instanceof Project)) return; + Workspace.closeProject((Project) selectedNode); + selectedNode = null; + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode instanceof Project); + } + + ; + }; + + + public ATCSAction openProject = new ATCSAction("Open project", "Opens the project, loading all necessary resources in memory") { + public void actionPerformed(ActionEvent e) { + if (!(selectedNode instanceof ClosedProject)) return; + Workspace.openProject((ClosedProject) selectedNode); + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode instanceof ClosedProject); + } + + ; + }; + + public ATCSAction deleteProject = new ATCSAction("Delete project", "Deletes the project, and all created/altered data, from disk") { + public void actionPerformed(ActionEvent e) { + if (selectedNode instanceof Project) { + if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { + Workspace.deleteProject((Project) selectedNode); + } + } else if (selectedNode instanceof ClosedProject) { + if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { + Workspace.deleteProject((ClosedProject) selectedNode); + } + } + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode instanceof Project || selectedNode instanceof ClosedProject); + } + + ; + }; + + public ATCSAction saveElement = new ATCSAction("Save this element", "Saves the current state of this element on disk") { + public void actionPerformed(ActionEvent e) { + if (!(selectedNode instanceof GameDataElement)) return; + final GameDataElement node = ((GameDataElement) selectedNode); + if (node.needsSaving()) { + node.save(); + ATContentStudio.frame.nodeChanged(node); + } + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + if (selectedNode instanceof GameDataElement) { + setEnabled(((GameDataElement) selectedNode).needsSaving()); + } else { + setEnabled(false); + } + } + + ; + }; + + public ATCSAction deleteSelected = new ATCSAction("Delete", "Deletes the selected items") { + boolean multiMode = false; + List elementsToDelete = null; + + public void init() { + putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); + } + + ; + + public void actionPerformed(ActionEvent e) { + if (multiMode) { + if (elementsToDelete == null) return; + final Map, Set> impactedCategories = new IdentityHashMap, Set>(); + for (GameDataElement element : elementsToDelete) { + ATContentStudio.frame.closeEditor(element); + element.childrenRemoved(new ArrayList()); + if (element instanceof JSONElement) { + if (element.getParent() instanceof GameDataCategory) { + @SuppressWarnings("unchecked") + GameDataCategory category = (GameDataCategory) element.getParent(); + category.remove(element); + if (impactedCategories.get(category) == null) { + impactedCategories.put(category, new HashSet()); + } + + GameDataElement newOne = element.getProject().getGameDataElement(((JSONElement) element).getClass(), element.id); + if (element instanceof Quest) { + for (QuestStage oldStage : ((Quest) element).stages) { + QuestStage newStage = newOne != null ? ((Quest) newOne).getStage(oldStage.progress) : null; + for (GameDataElement backlink : oldStage.getBacklinks()) { + backlink.elementChanged(oldStage, newStage); + } + } + } + for (GameDataElement backlink : element.getBacklinks()) { + backlink.elementChanged(element, newOne); + } + impactedCategories.get(category).add(((JSONElement) element).jsonFile); + } + } else if (element instanceof TMXMap) { + ((TMXMap) element).delete(); + GameDataElement newOne = element.getProject().getMap(element.id); + for (GameDataElement backlink : element.getBacklinks()) { + backlink.elementChanged(element, newOne); + } + } else if (element instanceof WriterModeData) { + WriterModeDataSet parent = (WriterModeDataSet) element.getParent(); + parent.writerModeDataList.remove(element); + } else if (element instanceof WorldmapSegment) { + if (element.getParent() instanceof Worldmap) { + ((Worldmap) element.getParent()).remove(element); + element.save(); + for (GameDataElement backlink : element.getBacklinks()) { + backlink.elementChanged(element, element.getProject().getWorldmapSegment(element.id)); + } + } + } + } + new Thread() { + @Override + public void run() { + final List events = new ArrayList(); + List catEvents; + for (GameDataCategory category : impactedCategories.keySet()) { + for (File f : impactedCategories.get(category)) { + catEvents = category.attemptSave(true, f.getName()); + if (catEvents.isEmpty()) { + category.save(f); + } else { + events.addAll(catEvents); + } + } + } + if (!events.isEmpty()) { + new SaveItemsWizard(events, null).setVisible(true); + } + } + }.start(); + } else { + if (!(selectedNode instanceof GameDataElement)) return; + final GameDataElement node = ((GameDataElement) selectedNode); + ATContentStudio.frame.closeEditor(node); + new Thread() { + @Override + public void run() { + node.childrenRemoved(new ArrayList()); + if (node instanceof JSONElement) { + if (node.getParent() instanceof GameDataCategory) { + ((GameDataCategory) node.getParent()).remove(node); + List events = node.attemptSave(); + if (events == null || events.isEmpty()) { + node.save(); + } else { + new SaveItemsWizard(events, null).setVisible(true); + } + GameDataElement newOne = node.getProject().getGameDataElement(((JSONElement) node).getClass(), node.id); + if (node instanceof Quest) { + for (QuestStage oldStage : ((Quest) node).stages) { + QuestStage newStage = newOne != null ? ((Quest) newOne).getStage(oldStage.progress) : null; + for (GameDataElement backlink : oldStage.getBacklinks()) { + backlink.elementChanged(oldStage, newStage); + } + } + } + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, newOne); + } + } // ((GameDataCategory)node.getParent()).remove(node); // List events = node.attemptSave(); // if (events == null || events.isEmpty()) { @@ -224,171 +230,198 @@ public class WorkspaceActions { // } else { // new SaveItemsWizard(events, null).setVisible(true); // } - } else if (node instanceof TMXMap) { - ((TMXMap)node).delete(); - GameDataElement newOne = node.getProject().getMap(node.id); - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, newOne); - } - } else if (node instanceof WriterModeData) { - WriterModeDataSet parent = (WriterModeDataSet) node.getParent(); - parent.writerModeDataList.remove(node); - } else if (node instanceof WorldmapSegment) { - if (node.getParent() instanceof Worldmap) { - ((Worldmap)node.getParent()).remove(node); - node.save(); - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, node.getProject().getWorldmapSegment(node.id)); - } - } - } - } - }.start(); - } - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - elementsToDelete = null; - if (selectedPaths != null && selectedPaths.length > 1) { - multiMode = false; - elementsToDelete = new ArrayList(); - for (TreePath selected : selectedPaths) { - if (selected.getLastPathComponent() instanceof GameDataElement && ((GameDataElement)selected.getLastPathComponent()).writable) { - elementsToDelete.add((GameDataElement) selected.getLastPathComponent()); - } - } - multiMode = elementsToDelete.size() > 1; - putValue(Action.NAME, "Delete all selected elements"); - setEnabled(multiMode); - } else if (selectedNode instanceof GameDataElement && ((GameDataElement)selectedNode).writable) { - multiMode = false; - if (selectedNode.getDataType() == GameSource.Type.created) { - putValue(Action.NAME, "Delete this element"); - setEnabled(true); - } else if (selectedNode.getDataType() == GameSource.Type.altered) { - putValue(Action.NAME, "Revert to original"); - setEnabled(true); - } else { - setEnabled(false); - } - } else { - setEnabled(false); - } - }; - }; + } else if (node instanceof TMXMap) { + ((TMXMap) node).delete(); + GameDataElement newOne = node.getProject().getMap(node.id); + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, newOne); + } + } else if (node instanceof WriterModeData) { + WriterModeDataSet parent = (WriterModeDataSet) node.getParent(); + parent.writerModeDataList.remove(node); + } else if (node instanceof WorldmapSegment) { + if (node.getParent() instanceof Worldmap) { + ((Worldmap) node.getParent()).remove(node); + node.save(); + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, node.getProject().getWorldmapSegment(node.id)); + } + } + } + } + }.start(); + } + } - public ATCSAction createGDE = new ATCSAction("Create Game Data Element (JSON)", "Opens the game object creation wizard") { - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - new JSONCreationWizard(selectedNode.getProject()).setVisible(true); - } - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - } - }; - - public ATCSAction createMap = new ATCSAction("Create TMX Map", "Opens the TMX Map creation wizard") { - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - new TMXMapCreationWizard(selectedNode.getProject()).setVisible(true); - } - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - } - }; - - public ATCSAction createWorldmap = new ATCSAction("Create Worldmap segment", "Opens the worldmap segment creation wizard") { - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - new WorldmapCreationWizard(selectedNode.getProject()).setVisible(true); - } - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - } - }; - - public ATCSAction importJSON = new ATCSAction("Import JSON data", "Opens the JSON import wizard") { - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - new JSONImportWizard(selectedNode.getProject()).setVisible(true); - } - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - } - }; - - public ATCSAction loadSave = new ATCSAction("Load saved game...", "Opens the saved game loading wizard"){ - public void actionPerformed(ActionEvent e) { - if(!(selectedNode instanceof Project || selectedNode instanceof SavedGamesSet)) return; - JFileChooser chooser = new JFileChooser("Select an Andor's Trail save file"); - if (chooser.showOpenDialog(ATContentStudio.frame) == JFileChooser.APPROVE_OPTION) { - selectedNode.getProject().addSave(chooser.getSelectedFile()); - selectedNode.getProject().save(); - } - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode instanceof Project || selectedNode instanceof SavedGamesSet); - }; - }; - - public ATCSAction compareItems = new ATCSAction("Items comparator", "Opens an editor showing all the items of the project in a table"){ - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - ATContentStudio.frame.editors.openEditor(new ItemsTableView(selectedNode.getProject())); - } - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - } - }; - - public ATCSAction compareNPCs = new ATCSAction("NPCs comparator", "Opens an editor showing all the NPCs of the project in a table"){ - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - ATContentStudio.frame.editors.openEditor(new NPCsTableView(selectedNode.getProject())); - } - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - } - }; - - public ATCSAction exportProject = new ATCSAction("Export project", "Generates a zip file containing all the created & altered resources of the project, ready to merge with the game source."){ - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - new ExportProjectWizard(selectedNode.getProject()).setVisible(true); - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - }; - }; - - public ATCSAction runBeanShell = new ATCSAction("Run Beanshell console", "Opens a beanshell scripting pad."){ - public void actionPerformed(ActionEvent e) { - new BeanShellView(); - }; - }; - - public ATCSAction showAbout = new ATCSAction("About...", "Displays credits and other informations about ATCS"){ - public void actionPerformed(ActionEvent e) { - ATContentStudio.frame.showAbout(); - }; - }; - - public ATCSAction exitATCS = new ATCSAction("Exit", "Closes the program"){ - public void actionPerformed(ActionEvent e) { - if (Workspace.activeWorkspace.needsSaving()) { - int answer = JOptionPane.showConfirmDialog(ATContentStudio.frame, "There are unsaved changes in your workspace.\nExiting ATCS will discard these changes.\nDo you really want to exit?", "Unsaved changes. Confirm exit.", JOptionPane.YES_NO_OPTION); - if (answer == JOptionPane.YES_OPTION) { - System.exit(0); - } - } else { - System.exit(0); - } - }; - }; - - public ATCSAction createWriter = new ATCSAction("Create dialogue sketch", "Create a dialogue sketch for fast dialogue edition"){ - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null) return; - new WriterSketchCreationWizard(selectedNode.getProject()).setVisible(true); + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + elementsToDelete = null; + if (selectedPaths != null && selectedPaths.length > 1) { + multiMode = false; + elementsToDelete = new ArrayList(); + for (TreePath selected : selectedPaths) { + if (selected.getLastPathComponent() instanceof GameDataElement && ((GameDataElement) selected.getLastPathComponent()).writable) { + elementsToDelete.add((GameDataElement) selected.getLastPathComponent()); + } + } + multiMode = elementsToDelete.size() > 1; + putValue(Action.NAME, "Delete all selected elements"); + setEnabled(multiMode); + } else if (selectedNode instanceof GameDataElement && ((GameDataElement) selectedNode).writable) { + multiMode = false; + if (selectedNode.getDataType() == GameSource.Type.created) { + putValue(Action.NAME, "Delete this element"); + setEnabled(true); + } else if (selectedNode.getDataType() == GameSource.Type.altered) { + putValue(Action.NAME, "Revert to original"); + setEnabled(true); + } else { + setEnabled(false); + } + } else { + setEnabled(false); + } + } + + ; + }; + + public ATCSAction createGDE = new ATCSAction("Create Game Data Element (JSON)", "Opens the game object creation wizard") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + new JSONCreationWizard(selectedNode.getProject()).setVisible(true); + } + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + }; + + public ATCSAction createMap = new ATCSAction("Create TMX Map", "Opens the TMX Map creation wizard") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + new TMXMapCreationWizard(selectedNode.getProject()).setVisible(true); + } + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + }; + + public ATCSAction createWorldmap = new ATCSAction("Create Worldmap segment", "Opens the worldmap segment creation wizard") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + new WorldmapCreationWizard(selectedNode.getProject()).setVisible(true); + } + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + }; + + public ATCSAction importJSON = new ATCSAction("Import JSON data", "Opens the JSON import wizard") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + new JSONImportWizard(selectedNode.getProject()).setVisible(true); + } + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + }; + + public ATCSAction loadSave = new ATCSAction("Load saved game...", "Opens the saved game loading wizard") { + public void actionPerformed(ActionEvent e) { + if (!(selectedNode instanceof Project || selectedNode instanceof SavedGamesSet)) return; + JFileChooser chooser = new JFileChooser("Select an Andor's Trail save file"); + if (chooser.showOpenDialog(ATContentStudio.frame) == JFileChooser.APPROVE_OPTION) { + selectedNode.getProject().addSave(chooser.getSelectedFile()); + selectedNode.getProject().save(); + } + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode instanceof Project || selectedNode instanceof SavedGamesSet); + } + + ; + }; + + public ATCSAction compareItems = new ATCSAction("Items comparator", "Opens an editor showing all the items of the project in a table") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + ATContentStudio.frame.editors.openEditor(new ItemsTableView(selectedNode.getProject())); + } + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + }; + + public ATCSAction compareNPCs = new ATCSAction("NPCs comparator", "Opens an editor showing all the NPCs of the project in a table") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + ATContentStudio.frame.editors.openEditor(new NPCsTableView(selectedNode.getProject())); + } + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + }; + + public ATCSAction exportProject = new ATCSAction("Export project", "Generates a zip file containing all the created & altered resources of the project, ready to merge with the game source.") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + new ExportProjectWizard(selectedNode.getProject()).setVisible(true); + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + + ; + }; + + public ATCSAction runBeanShell = new ATCSAction("Run Beanshell console", "Opens a beanshell scripting pad.") { + public void actionPerformed(ActionEvent e) { + new BeanShellView(); + } + + ; + }; + + public ATCSAction showAbout = new ATCSAction("About...", "Displays credits and other informations about ATCS") { + public void actionPerformed(ActionEvent e) { + ATContentStudio.frame.showAbout(); + } + + ; + }; + + public ATCSAction exitATCS = new ATCSAction("Exit", "Closes the program") { + public void actionPerformed(ActionEvent e) { + if (Workspace.activeWorkspace.needsSaving()) { + int answer = JOptionPane.showConfirmDialog(ATContentStudio.frame, "There are unsaved changes in your workspace.\nExiting ATCS will discard these changes.\nDo you really want to exit?", "Unsaved changes. Confirm exit.", JOptionPane.YES_NO_OPTION); + if (answer == JOptionPane.YES_OPTION) { + System.exit(0); + } + } else { + System.exit(0); + } + } + + ; + }; + + public ATCSAction createWriter = new ATCSAction("Create dialogue sketch", "Create a dialogue sketch for fast dialogue edition") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null) return; + new WriterSketchCreationWizard(selectedNode.getProject()).setVisible(true); // // // if (selectedNode == null || selectedNode.getProject() == null) return; @@ -400,11 +433,14 @@ public class WorkspaceActions { // frame.setMinimumSize(new Dimension(250, 200)); // frame.pack(); // frame.setVisible(true); - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode.getProject() != null); - } - }; + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode.getProject() != null); + } + }; /*public ATCSAction testCommitWriter = new ATCSAction("Export dialogue sketch", "Exports the dialogue sketch as real JSON data dialogues") { public void actionPerformed(ActionEvent e) { @@ -419,122 +455,136 @@ public class WorkspaceActions { setEnabled(selectedNode != null && selectedNode instanceof WriterModeData); } };*/ - - public ATCSAction generateWriter = new ATCSAction("Generate dialogue sketch", "Generates a dialogue sketch from this dialogue and its tree.") { - public void actionPerformed(ActionEvent e) { - if (selectedNode == null || selectedNode.getProject() == null || !(selectedNode instanceof Dialogue)) return; - new WriterSketchCreationWizard(selectedNode.getProject(), (Dialogue)selectedNode).setVisible(true); - - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(selectedNode != null && selectedNode instanceof Dialogue); - } - }; - - public ATCSAction editWorkspaceSettings = new ATCSAction("Edit Workspace Settings", "Change the preferences of this workspace.") { - public void actionPerformed(ActionEvent e) { - new WorkspaceSettingsEditor(Workspace.activeWorkspace.settings); - }; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { - setEnabled(true); - }; - }; - - List actions = new ArrayList(); - - public WorkspaceActions() { - actions.add(createProject); - actions.add(closeProject); - actions.add(openProject); - actions.add(deleteProject); - actions.add(saveElement); - actions.add(deleteSelected); - actions.add(createGDE); - actions.add(createMap); - actions.add(importJSON); - actions.add(loadSave); - actions.add(compareItems); - actions.add(compareNPCs); - actions.add(exportProject); - actions.add(showAbout); - actions.add(exitATCS); - actions.add(createWriter); + + public ATCSAction generateWriter = new ATCSAction("Generate dialogue sketch", "Generates a dialogue sketch from this dialogue and its tree.") { + public void actionPerformed(ActionEvent e) { + if (selectedNode == null || selectedNode.getProject() == null || !(selectedNode instanceof Dialogue)) + return; + new WriterSketchCreationWizard(selectedNode.getProject(), (Dialogue) selectedNode).setVisible(true); + + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(selectedNode != null && selectedNode instanceof Dialogue); + } + }; + + public ATCSAction editWorkspaceSettings = new ATCSAction("Edit Workspace Settings", "Change the preferences of this workspace.") { + public void actionPerformed(ActionEvent e) { + new WorkspaceSettingsEditor(Workspace.activeWorkspace.settings); + } + + ; + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + setEnabled(true); + } + + ; + }; + + List actions = new ArrayList(); + + public WorkspaceActions() { + actions.add(createProject); + actions.add(closeProject); + actions.add(openProject); + actions.add(deleteProject); + actions.add(saveElement); + actions.add(deleteSelected); + actions.add(createGDE); + actions.add(createMap); + actions.add(importJSON); + actions.add(loadSave); + actions.add(compareItems); + actions.add(compareNPCs); + actions.add(exportProject); + actions.add(showAbout); + actions.add(exitATCS); + actions.add(createWriter); // actions.add(testCommitWriter); - actions.add(generateWriter); - actions.add(editWorkspaceSettings); - selectionChanged(null, null); - } - - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths){ - this.selectedNode = selectedNode; - this.selectedPaths = selectedPaths; - synchronized(actions) { - for (ATCSAction action : actions) { - action.selectionChanged(selectedNode, selectedPaths); - } - } - } - - public static class ATCSAction implements Action { + actions.add(generateWriter); + actions.add(editWorkspaceSettings); + selectionChanged(null, null); + } - boolean enabled = true; - - - public ATCSAction(String name, String desc) { - putValue(Action.NAME, name); - putValue(Action.SHORT_DESCRIPTION, desc); - init(); - } - - public void init(){} - - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths){} - - @Override - public void actionPerformed(ActionEvent e) {}; + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + this.selectedNode = selectedNode; + this.selectedPaths = selectedPaths; + synchronized (actions) { + for (ATCSAction action : actions) { + action.selectionChanged(selectedNode, selectedPaths); + } + } + } - public Map values = new LinkedHashMap(); - - @Override - public Object getValue(String key) { - return values.get(key); - } + public static class ATCSAction implements Action { - @Override - public void putValue(String key, Object value) { - PropertyChangeEvent event = new PropertyChangeEvent(this, key, values.get(key), value); - values.put(key, value); - for (PropertyChangeListener l : listeners) { - l.propertyChange(event); - } - } + boolean enabled = true; - @Override - public void setEnabled(boolean b) { - PropertyChangeEvent event = new PropertyChangeEvent(this, "enabled", isEnabled(), b); - enabled = b; - for (PropertyChangeListener l : listeners) { - l.propertyChange(event); - } - } - @Override - public boolean isEnabled() { - return enabled; - } + public ATCSAction(String name, String desc) { + putValue(Action.NAME, name); + putValue(Action.SHORT_DESCRIPTION, desc); + init(); + } - private List listeners = new CopyOnWriteArrayList(); - - @Override - public void addPropertyChangeListener(PropertyChangeListener listener) { - listeners.add(listener); - } + public void init() { + } + + public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { + } + + @Override + public void actionPerformed(ActionEvent e) { + } + + ; + + public Map values = new LinkedHashMap(); + + @Override + public Object getValue(String key) { + return values.get(key); + } + + @Override + public void putValue(String key, Object value) { + PropertyChangeEvent event = new PropertyChangeEvent(this, key, values.get(key), value); + values.put(key, value); + for (PropertyChangeListener l : listeners) { + l.propertyChange(event); + } + } + + @Override + public void setEnabled(boolean b) { + PropertyChangeEvent event = new PropertyChangeEvent(this, "enabled", isEnabled(), b); + enabled = b; + for (PropertyChangeListener l : listeners) { + l.propertyChange(event); + } + } + + @Override + public boolean isEnabled() { + return enabled; + } + + private List listeners = new CopyOnWriteArrayList(); + + @Override + public void addPropertyChangeListener(PropertyChangeListener listener) { + listeners.add(listener); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener listener) { + listeners.remove(listener); + } + + } - @Override - public void removePropertyChangeListener(PropertyChangeListener listener) { - listeners.remove(listener); - } - - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSelector.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSelector.java index e6f3715..b82c34d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSelector.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSelector.java @@ -1,8 +1,10 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; +import com.gpl.rpg.atcontentstudio.ConfigCache; + +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; @@ -10,143 +12,133 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; - -import com.gpl.rpg.atcontentstudio.ConfigCache; - public class WorkspaceSelector extends JFrame { - private static final long serialVersionUID = 7518745499760748574L; - - public String selected = null; - - public WorkspaceSelector() { - super("Select your workspace"); - setIconImage(DefaultIcons.getMainIconImage()); - - //Data - final List workspaces = ConfigCache.getKnownWorkspaces(); - final List wsPaths = new ArrayList(); - - //Active widgets declaration - final JComboBox combo = new JComboBox(); - final JButton browse = new JButton("Browse..."); - final JButton cancel = new JButton("Cancel"); - final JButton ok = new JButton("Ok"); - - //Widgets behavior - combo.setEditable(true); - for (File f : workspaces) { - String path = f.getAbsolutePath(); - wsPaths.add(path); - combo.addItem(path); - } - if (ConfigCache.getLatestWorkspace() != null) { - combo.setSelectedItem(wsPaths.get(workspaces.indexOf(ConfigCache.getLatestWorkspace()))); - } - combo.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (combo.getSelectedItem() != null) { - ok.setEnabled(true); - } - } - }); - - - ok.setEnabled(ConfigCache.getLatestWorkspace() != null); - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - WorkspaceSelector.this.selected = (String) combo.getSelectedItem(); - WorkspaceSelector.this.dispose(); - } - }); - - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - WorkspaceSelector.this.selected = null; - WorkspaceSelector.this.dispose(); - } - }); - - browse.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - JFileChooser fc; - if(workspaces.isEmpty()) { - fc = new JFileChooser(); - } else { - if (ConfigCache.getLatestWorkspace() != null) { - fc = new JFileChooser(ConfigCache.getLatestWorkspace()); - } else { - fc = new JFileChooser(workspaces.get(0)); - } - } - fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); - fc.setMultiSelectionEnabled(false); - fc.setAcceptAllFileFilterUsed(false); - int result = fc.showSaveDialog(WorkspaceSelector.this); - if (result == JFileChooser.APPROVE_OPTION) { - String selected = fc.getSelectedFile().getAbsolutePath(); - for (String s : wsPaths) { - if (s.equals(selected)) { - selected = s; - } - } - combo.setSelectedItem(selected); - } - } - }); - - - //Layout, labels and dialog behavior. - setTitle("Select your workspace"); - - JLabel logoLabel = new JLabel(); - try { - logoLabel = new JLabel(new ImageIcon(ImageIO.read(WorkspaceSelector.class.getResource("/com/gpl/rpg/atcontentstudio/img/atcs_logo_banner.png"))), JLabel.CENTER); - } catch (IOException e1) {} - - JPanel dialogPane = new JPanel(); - dialogPane.setLayout(new BorderLayout()); - - dialogPane.add(logoLabel, BorderLayout.NORTH); - dialogPane.add(new JLabel("Workspace : "), BorderLayout.WEST); - dialogPane.add(combo, BorderLayout.CENTER); - dialogPane.add(browse, BorderLayout.EAST); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.fill = GridBagConstraints.BOTH; - c.anchor = GridBagConstraints.EAST; - c.gridx = 0; - c.gridy = 0; - c.weightx = 1; - buttonPane.add(new JLabel(), c); - - c.fill = GridBagConstraints.VERTICAL; - c.weightx = 0; - c.gridx++; - buttonPane.add(cancel, c); - - c.gridx++; - buttonPane.add(ok, c); - - dialogPane.add(buttonPane, BorderLayout.SOUTH); - - setDefaultCloseOperation(DISPOSE_ON_CLOSE); - setContentPane(dialogPane); - setResizable(false); - } + private static final long serialVersionUID = 7518745499760748574L; + + public String selected = null; + + public WorkspaceSelector() { + super("Select your workspace"); + setIconImage(DefaultIcons.getMainIconImage()); + + //Data + final List workspaces = ConfigCache.getKnownWorkspaces(); + final List wsPaths = new ArrayList(); + + //Active widgets declaration + final JComboBox combo = new JComboBox(); + final JButton browse = new JButton("Browse..."); + final JButton cancel = new JButton("Cancel"); + final JButton ok = new JButton("Ok"); + + //Widgets behavior + combo.setEditable(true); + for (File f : workspaces) { + String path = f.getAbsolutePath(); + wsPaths.add(path); + combo.addItem(path); + } + if (ConfigCache.getLatestWorkspace() != null) { + combo.setSelectedItem(wsPaths.get(workspaces.indexOf(ConfigCache.getLatestWorkspace()))); + } + combo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (combo.getSelectedItem() != null) { + ok.setEnabled(true); + } + } + }); + + + ok.setEnabled(ConfigCache.getLatestWorkspace() != null); + ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + WorkspaceSelector.this.selected = (String) combo.getSelectedItem(); + WorkspaceSelector.this.dispose(); + } + }); + + cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + WorkspaceSelector.this.selected = null; + WorkspaceSelector.this.dispose(); + } + }); + + browse.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + JFileChooser fc; + if (workspaces.isEmpty()) { + fc = new JFileChooser(); + } else { + if (ConfigCache.getLatestWorkspace() != null) { + fc = new JFileChooser(ConfigCache.getLatestWorkspace()); + } else { + fc = new JFileChooser(workspaces.get(0)); + } + } + fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + fc.setMultiSelectionEnabled(false); + fc.setAcceptAllFileFilterUsed(false); + int result = fc.showSaveDialog(WorkspaceSelector.this); + if (result == JFileChooser.APPROVE_OPTION) { + String selected = fc.getSelectedFile().getAbsolutePath(); + for (String s : wsPaths) { + if (s.equals(selected)) { + selected = s; + } + } + combo.setSelectedItem(selected); + } + } + }); + + + //Layout, labels and dialog behavior. + setTitle("Select your workspace"); + + JLabel logoLabel = new JLabel(); + try { + logoLabel = new JLabel(new ImageIcon(ImageIO.read(WorkspaceSelector.class.getResource("/com/gpl/rpg/atcontentstudio/img/atcs_logo_banner.png"))), JLabel.CENTER); + } catch (IOException e1) { + } + + JPanel dialogPane = new JPanel(); + dialogPane.setLayout(new BorderLayout()); + + dialogPane.add(logoLabel, BorderLayout.NORTH); + dialogPane.add(new JLabel("Workspace : "), BorderLayout.WEST); + dialogPane.add(combo, BorderLayout.CENTER); + dialogPane.add(browse, BorderLayout.EAST); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.fill = GridBagConstraints.BOTH; + c.anchor = GridBagConstraints.EAST; + c.gridx = 0; + c.gridy = 0; + c.weightx = 1; + buttonPane.add(new JLabel(), c); + + c.fill = GridBagConstraints.VERTICAL; + c.weightx = 0; + c.gridx++; + buttonPane.add(cancel, c); + + c.gridx++; + buttonPane.add(ok, c); + + dialogPane.add(buttonPane, BorderLayout.SOUTH); + + setDefaultCloseOperation(DISPOSE_ON_CLOSE); + setContentPane(dialogPane); + setResizable(false); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSettingsEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSettingsEditor.java index 95c7ce5..2a9ea4a 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSettingsEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceSettingsEditor.java @@ -1,253 +1,242 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JTextField; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.WorkspaceSettings; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + public class WorkspaceSettingsEditor extends JDialog { - private static final long serialVersionUID = -1326158719217162879L; - - WorkspaceSettings settings; - - JRadioButton useSystemDefaultMapEditorButton, useCustomMapEditorButton; - JTextField mapEditorCommandField; - - JRadioButton useSystemDefaultImageViewerButton, useSystemDefaultImageEditorButton, useCustomImageEditorButton; - JTextField imageEditorCommandField; - - JCheckBox useInternetBox; - JCheckBox translatorModeBox; - JComboBox translatorLanguagesBox; - JCheckBox checkUpdatesBox; - - - - public WorkspaceSettingsEditor(WorkspaceSettings settings) { - super(ATContentStudio.frame, "Workspace settings", true); - setIconImage(DefaultIcons.getMainIconImage()); - - this.settings = settings; - - JPanel pane = new JPanel(); - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - getContentPane().add(buttonPane, BorderLayout.SOUTH); - - - pane.add(getExternalToolsPane(), JideBoxLayout.FIX); - pane.add(getInternetPane(), JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); + private static final long serialVersionUID = -1326158719217162879L; - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton ok = new JButton("Ok"); - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - pushToModel(); - dispose(); - } - }); - buttonPane.add(ok, JideBoxLayout.FIX); - JButton reset = new JButton("Reset to defaults"); - reset.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - resetDefaults(); - } - }); - buttonPane.add(reset, JideBoxLayout.FIX); - JButton cancel = new JButton("Cancel"); - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - dispose(); - } - }); - buttonPane.add(cancel, JideBoxLayout.FIX); - - loadFromModel(); - pack(); - setVisible(true); - - } - - public JPanel getExternalToolsPane() { - CollapsiblePanel pane = new CollapsiblePanel("External tools"); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); - - //Tiled - CollapsiblePanel tiledPane = new CollapsiblePanel("TMX Map viewer/editor"); - tiledPane.setLayout(new JideBoxLayout(tiledPane, JideBoxLayout.PAGE_AXIS)); - ButtonGroup tiledRadioGroup = new ButtonGroup(); - useSystemDefaultMapEditorButton = new JRadioButton("Use system-default TMX Map editor"); - tiledRadioGroup.add(useSystemDefaultMapEditorButton); - tiledPane.add(useSystemDefaultMapEditorButton, JideBoxLayout.FIX); - useCustomMapEditorButton = new JRadioButton("Use custom command to open TMX Map files"); - tiledRadioGroup.add(useCustomMapEditorButton); - tiledPane.add(useCustomMapEditorButton, JideBoxLayout.FIX); - mapEditorCommandField = new JTextField(); - tiledPane.add(mapEditorCommandField, JideBoxLayout.FIX); - ActionListener tiledRadioListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (useSystemDefaultMapEditorButton.equals(e.getSource())) { - mapEditorCommandField.setEnabled(false); - } else if (useCustomMapEditorButton.equals(e.getSource())) { - mapEditorCommandField.setEnabled(true); - } - } - }; - useSystemDefaultMapEditorButton.addActionListener(tiledRadioListener); - useCustomMapEditorButton.addActionListener(tiledRadioListener); - pane.add(tiledPane, JideBoxLayout.FIX); - - //Images - CollapsiblePanel imgPane = new CollapsiblePanel("Image viewer/editor"); - imgPane.setLayout(new JideBoxLayout(imgPane, JideBoxLayout.PAGE_AXIS)); - ButtonGroup imgRadioGroup = new ButtonGroup(); - useSystemDefaultImageViewerButton = new JRadioButton("Use system-default image viewer"); - imgRadioGroup.add(useSystemDefaultImageViewerButton); - imgPane.add(useSystemDefaultImageViewerButton, JideBoxLayout.FIX); - useSystemDefaultImageEditorButton = new JRadioButton("Use system-default image editor"); - imgRadioGroup.add(useSystemDefaultImageEditorButton); - imgPane.add(useSystemDefaultImageEditorButton, JideBoxLayout.FIX); - useCustomImageEditorButton = new JRadioButton("Use custom command to open images"); - imgRadioGroup.add(useCustomImageEditorButton); - imgPane.add(useCustomImageEditorButton, JideBoxLayout.FIX); - imageEditorCommandField = new JTextField(); - imgPane.add(imageEditorCommandField, JideBoxLayout.FIX); - ActionListener imgRadioListener = new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (useSystemDefaultMapEditorButton.equals(e.getSource())) { - imageEditorCommandField.setEnabled(false); - } else if (useSystemDefaultImageViewerButton.equals(e.getSource())) { - imageEditorCommandField.setEnabled(false); - } else if (useCustomImageEditorButton.equals(e.getSource())) { - imageEditorCommandField.setEnabled(true); - } - } - }; - useSystemDefaultImageViewerButton.addActionListener(imgRadioListener); - useSystemDefaultImageEditorButton.addActionListener(imgRadioListener); - useCustomImageEditorButton.addActionListener(imgRadioListener); - pane.add(imgPane, JideBoxLayout.FIX); - - pane.expand(); - return pane; - } - - public JPanel getInternetPane() { - - CollapsiblePanel pane = new CollapsiblePanel("Internet options"); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); - - useInternetBox = new JCheckBox("Allow connecting to internet to retrieve data from weblate and check for updates."); - pane.add(useInternetBox, JideBoxLayout.FIX); - - translatorModeBox = new JCheckBox("Activate translator mode"); - pane.add(translatorModeBox, JideBoxLayout.FIX); - - JPanel langPane = new JPanel(); - langPane.setLayout(new JideBoxLayout(langPane, JideBoxLayout.LINE_AXIS)); - langPane.add(new JLabel("Language code: "), JideBoxLayout.FIX); - translatorLanguagesBox = new JComboBox(WorkspaceSettings.LANGUAGE_LIST); - langPane.add(translatorLanguagesBox); - pane.add(langPane, JideBoxLayout.FIX); + WorkspaceSettings settings; - pane.add(new JLabel("If your language isn't here, complain on the forums at https://andorstrail.com/"), JideBoxLayout.FIX); - - checkUpdatesBox = new JCheckBox("Check for ATCS updates at startup"); - pane.add(checkUpdatesBox, JideBoxLayout.FIX); - - useInternetBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - translatorLanguagesBox.setEnabled(useInternetBox.isSelected() && translatorModeBox.isSelected()); - translatorModeBox.setEnabled(useInternetBox.isSelected()); - checkUpdatesBox.setEnabled(useInternetBox.isSelected()); - } - }); - - translatorModeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - translatorLanguagesBox.setEnabled(translatorModeBox.isSelected()); - } - }); - - - return pane; - } - - public void loadFromModel() { - //Tiled - useSystemDefaultMapEditorButton.setSelected(settings.useSystemDefaultMapEditor.getCurrentValue()); - useCustomMapEditorButton.setSelected(!settings.useSystemDefaultMapEditor.getCurrentValue()); - mapEditorCommandField.setText(settings.mapEditorCommand.getCurrentValue()); - //Images - useSystemDefaultImageViewerButton.setSelected(settings.useSystemDefaultImageViewer.getCurrentValue()); - useSystemDefaultImageEditorButton.setSelected(settings.useSystemDefaultImageEditor.getCurrentValue()); - useCustomImageEditorButton.setSelected(!(settings.useSystemDefaultImageViewer.getCurrentValue() || settings.useSystemDefaultImageEditor.getCurrentValue())); - imageEditorCommandField.setText(settings.imageEditorCommand.getCurrentValue()); - //Internet - useInternetBox.setSelected(settings.useInternet.getCurrentValue()); - if (settings.translatorLanguage.getCurrentValue() != null) { - translatorModeBox.setSelected(true); - translatorLanguagesBox.setSelectedItem(settings.translatorLanguage.getCurrentValue()); - translatorLanguagesBox.setEnabled(useInternetBox.isSelected()); - } else { - translatorModeBox.setSelected(false); - translatorLanguagesBox.setSelectedItem(null); - translatorLanguagesBox.setEnabled(false); - } - translatorModeBox.setEnabled(useInternetBox.isSelected()); - checkUpdatesBox.setSelected(settings.checkUpdates.getCurrentValue()); - checkUpdatesBox.setEnabled(useInternetBox.isSelected()); - } - - public void pushToModel() { - //Tiled - settings.useSystemDefaultMapEditor.setCurrentValue(useSystemDefaultMapEditorButton.isSelected()); - settings.mapEditorCommand.setCurrentValue(mapEditorCommandField.getText()); - //Images - settings.useSystemDefaultImageViewer.setCurrentValue(useSystemDefaultImageViewerButton.isSelected()); - settings.useSystemDefaultImageEditor.setCurrentValue(useSystemDefaultImageEditorButton.isSelected()); - settings.imageEditorCommand.setCurrentValue(imageEditorCommandField.getText()); - //Internet - settings.useInternet.setCurrentValue(useInternetBox.isSelected()); - if (translatorModeBox.isSelected()) { - settings.translatorLanguage.setCurrentValue((String)translatorLanguagesBox.getSelectedItem()); - } else { - settings.translatorLanguage.resetDefault(); - } - settings.checkUpdates.setCurrentValue(checkUpdatesBox.isSelected()); - settings.save(); - } - - public void resetDefaults() { - settings.resetDefault(); - settings.save(); - loadFromModel(); - } + JRadioButton useSystemDefaultMapEditorButton, useCustomMapEditorButton; + JTextField mapEditorCommandField; + + JRadioButton useSystemDefaultImageViewerButton, useSystemDefaultImageEditorButton, useCustomImageEditorButton; + JTextField imageEditorCommandField; + + JCheckBox useInternetBox; + JCheckBox translatorModeBox; + JComboBox translatorLanguagesBox; + JCheckBox checkUpdatesBox; + + + public WorkspaceSettingsEditor(WorkspaceSettings settings) { + super(ATContentStudio.frame, "Workspace settings", true); + setIconImage(DefaultIcons.getMainIconImage()); + + this.settings = settings; + + JPanel pane = new JPanel(); + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); + getContentPane().add(buttonPane, BorderLayout.SOUTH); + + + pane.add(getExternalToolsPane(), JideBoxLayout.FIX); + pane.add(getInternetPane(), JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton ok = new JButton("Ok"); + ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + pushToModel(); + dispose(); + } + }); + buttonPane.add(ok, JideBoxLayout.FIX); + JButton reset = new JButton("Reset to defaults"); + reset.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + resetDefaults(); + } + }); + buttonPane.add(reset, JideBoxLayout.FIX); + JButton cancel = new JButton("Cancel"); + cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + dispose(); + } + }); + buttonPane.add(cancel, JideBoxLayout.FIX); + + loadFromModel(); + pack(); + setVisible(true); + + } + + public JPanel getExternalToolsPane() { + CollapsiblePanel pane = new CollapsiblePanel("External tools"); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); + + //Tiled + CollapsiblePanel tiledPane = new CollapsiblePanel("TMX Map viewer/editor"); + tiledPane.setLayout(new JideBoxLayout(tiledPane, JideBoxLayout.PAGE_AXIS)); + ButtonGroup tiledRadioGroup = new ButtonGroup(); + useSystemDefaultMapEditorButton = new JRadioButton("Use system-default TMX Map editor"); + tiledRadioGroup.add(useSystemDefaultMapEditorButton); + tiledPane.add(useSystemDefaultMapEditorButton, JideBoxLayout.FIX); + useCustomMapEditorButton = new JRadioButton("Use custom command to open TMX Map files"); + tiledRadioGroup.add(useCustomMapEditorButton); + tiledPane.add(useCustomMapEditorButton, JideBoxLayout.FIX); + mapEditorCommandField = new JTextField(); + tiledPane.add(mapEditorCommandField, JideBoxLayout.FIX); + ActionListener tiledRadioListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (useSystemDefaultMapEditorButton.equals(e.getSource())) { + mapEditorCommandField.setEnabled(false); + } else if (useCustomMapEditorButton.equals(e.getSource())) { + mapEditorCommandField.setEnabled(true); + } + } + }; + useSystemDefaultMapEditorButton.addActionListener(tiledRadioListener); + useCustomMapEditorButton.addActionListener(tiledRadioListener); + pane.add(tiledPane, JideBoxLayout.FIX); + + //Images + CollapsiblePanel imgPane = new CollapsiblePanel("Image viewer/editor"); + imgPane.setLayout(new JideBoxLayout(imgPane, JideBoxLayout.PAGE_AXIS)); + ButtonGroup imgRadioGroup = new ButtonGroup(); + useSystemDefaultImageViewerButton = new JRadioButton("Use system-default image viewer"); + imgRadioGroup.add(useSystemDefaultImageViewerButton); + imgPane.add(useSystemDefaultImageViewerButton, JideBoxLayout.FIX); + useSystemDefaultImageEditorButton = new JRadioButton("Use system-default image editor"); + imgRadioGroup.add(useSystemDefaultImageEditorButton); + imgPane.add(useSystemDefaultImageEditorButton, JideBoxLayout.FIX); + useCustomImageEditorButton = new JRadioButton("Use custom command to open images"); + imgRadioGroup.add(useCustomImageEditorButton); + imgPane.add(useCustomImageEditorButton, JideBoxLayout.FIX); + imageEditorCommandField = new JTextField(); + imgPane.add(imageEditorCommandField, JideBoxLayout.FIX); + ActionListener imgRadioListener = new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (useSystemDefaultMapEditorButton.equals(e.getSource())) { + imageEditorCommandField.setEnabled(false); + } else if (useSystemDefaultImageViewerButton.equals(e.getSource())) { + imageEditorCommandField.setEnabled(false); + } else if (useCustomImageEditorButton.equals(e.getSource())) { + imageEditorCommandField.setEnabled(true); + } + } + }; + useSystemDefaultImageViewerButton.addActionListener(imgRadioListener); + useSystemDefaultImageEditorButton.addActionListener(imgRadioListener); + useCustomImageEditorButton.addActionListener(imgRadioListener); + pane.add(imgPane, JideBoxLayout.FIX); + + pane.expand(); + return pane; + } + + public JPanel getInternetPane() { + + CollapsiblePanel pane = new CollapsiblePanel("Internet options"); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); + + useInternetBox = new JCheckBox("Allow connecting to internet to retrieve data from weblate and check for updates."); + pane.add(useInternetBox, JideBoxLayout.FIX); + + translatorModeBox = new JCheckBox("Activate translator mode"); + pane.add(translatorModeBox, JideBoxLayout.FIX); + + JPanel langPane = new JPanel(); + langPane.setLayout(new JideBoxLayout(langPane, JideBoxLayout.LINE_AXIS)); + langPane.add(new JLabel("Language code: "), JideBoxLayout.FIX); + translatorLanguagesBox = new JComboBox(WorkspaceSettings.LANGUAGE_LIST); + langPane.add(translatorLanguagesBox); + pane.add(langPane, JideBoxLayout.FIX); + + pane.add(new JLabel("If your language isn't here, complain on the forums at https://andorstrail.com/"), JideBoxLayout.FIX); + + checkUpdatesBox = new JCheckBox("Check for ATCS updates at startup"); + pane.add(checkUpdatesBox, JideBoxLayout.FIX); + + useInternetBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + translatorLanguagesBox.setEnabled(useInternetBox.isSelected() && translatorModeBox.isSelected()); + translatorModeBox.setEnabled(useInternetBox.isSelected()); + checkUpdatesBox.setEnabled(useInternetBox.isSelected()); + } + }); + + translatorModeBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + translatorLanguagesBox.setEnabled(translatorModeBox.isSelected()); + } + }); + + + return pane; + } + + public void loadFromModel() { + //Tiled + useSystemDefaultMapEditorButton.setSelected(settings.useSystemDefaultMapEditor.getCurrentValue()); + useCustomMapEditorButton.setSelected(!settings.useSystemDefaultMapEditor.getCurrentValue()); + mapEditorCommandField.setText(settings.mapEditorCommand.getCurrentValue()); + //Images + useSystemDefaultImageViewerButton.setSelected(settings.useSystemDefaultImageViewer.getCurrentValue()); + useSystemDefaultImageEditorButton.setSelected(settings.useSystemDefaultImageEditor.getCurrentValue()); + useCustomImageEditorButton.setSelected(!(settings.useSystemDefaultImageViewer.getCurrentValue() || settings.useSystemDefaultImageEditor.getCurrentValue())); + imageEditorCommandField.setText(settings.imageEditorCommand.getCurrentValue()); + //Internet + useInternetBox.setSelected(settings.useInternet.getCurrentValue()); + if (settings.translatorLanguage.getCurrentValue() != null) { + translatorModeBox.setSelected(true); + translatorLanguagesBox.setSelectedItem(settings.translatorLanguage.getCurrentValue()); + translatorLanguagesBox.setEnabled(useInternetBox.isSelected()); + } else { + translatorModeBox.setSelected(false); + translatorLanguagesBox.setSelectedItem(null); + translatorLanguagesBox.setEnabled(false); + } + translatorModeBox.setEnabled(useInternetBox.isSelected()); + checkUpdatesBox.setSelected(settings.checkUpdates.getCurrentValue()); + checkUpdatesBox.setEnabled(useInternetBox.isSelected()); + } + + public void pushToModel() { + //Tiled + settings.useSystemDefaultMapEditor.setCurrentValue(useSystemDefaultMapEditorButton.isSelected()); + settings.mapEditorCommand.setCurrentValue(mapEditorCommandField.getText()); + //Images + settings.useSystemDefaultImageViewer.setCurrentValue(useSystemDefaultImageViewerButton.isSelected()); + settings.useSystemDefaultImageEditor.setCurrentValue(useSystemDefaultImageEditorButton.isSelected()); + settings.imageEditorCommand.setCurrentValue(imageEditorCommandField.getText()); + //Internet + settings.useInternet.setCurrentValue(useInternetBox.isSelected()); + if (translatorModeBox.isSelected()) { + settings.translatorLanguage.setCurrentValue((String) translatorLanguagesBox.getSelectedItem()); + } else { + settings.translatorLanguage.resetDefault(); + } + settings.checkUpdates.setCurrentValue(checkUpdatesBox.isSelected()); + settings.save(); + } + + public void resetDefaults() { + settings.resetDefault(); + settings.save(); + loadFromModel(); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorldmapCreationWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/WorldmapCreationWizard.java index 1e361f6..1813eef 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorldmapCreationWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorldmapCreationWizard.java @@ -1,158 +1,153 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class WorldmapCreationWizard extends JDialog { - private static final long serialVersionUID = 6491044105090917567L; + private static final long serialVersionUID = 6491044105090917567L; - private WorldmapSegment creation = new WorldmapSegment(null, null, null); - - final JLabel message; - final JTextField idField; - final JButton ok; - final Project proj; - - - public WorldmapCreationWizard(final Project proj) { - super(ATContentStudio.frame); - this.proj = proj; - setTitle("Create Worldmap segment"); - - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - pane.add(new JLabel("Create a new worldmap segment."), JideBoxLayout.FIX); - - message = new JLabel("Enter a map segment ID below: "); - pane.add(message, JideBoxLayout.FIX); - - final JPanel idPane = new JPanel(); - idPane.setLayout(new BorderLayout()); - JLabel idLabel = new JLabel("Internal ID: "); - idPane.add(idLabel, BorderLayout.WEST); - idField = new JTextField(""); - idField.setEditable(true); - idPane.add(idField, BorderLayout.CENTER); - pane.add(idPane, JideBoxLayout.FIX); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancel = new JButton("Cancel"); - buttonPane.add(cancel, JideBoxLayout.FIX); - ok = new JButton("Ok"); - buttonPane.add(ok, JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - creation.id = idField.getText(); - WorldmapCreationWizard.this.setVisible(false); - WorldmapCreationWizard.this.dispose(); - proj.createWorldmapSegment(creation); - notifyCreated(); - ATContentStudio.frame.selectInTree(creation); - ATContentStudio.frame.openEditor(creation); - } - }); - - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - creation = null; - WorldmapCreationWizard.this.setVisible(false); - WorldmapCreationWizard.this.dispose(); - } - }); - - DocumentListener statusUpdater = new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void insertUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void changedUpdate(DocumentEvent e) { - updateStatus(); - } - }; - idField.getDocument().addDocumentListener(statusUpdater); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - setMinimumSize(new Dimension(350,120)); - updateStatus(); - pack(); - - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - } - - public void updateStatus() { - boolean trouble = false; - message.setText("Looks OK to me."); - if (idField.getText() == null || idField.getText().length() <= 0) { - message.setText("Internal ID must not be empty."); - trouble = true; - } else if (proj.getWorldmapSegment(idField.getText()) != null) { - if (proj.getWorldmapSegment(idField.getText()).getDataType() == GameSource.Type.created) { - message.setText("A worldmap segment with the same ID was already created in this project."); - trouble = true; - } else if (proj.getWorldmapSegment(idField.getText()).getDataType() == GameSource.Type.altered) { - message.setText("A worldmap segment with the same ID exists in the game and is already altered in this project."); - trouble = true; - } else if (proj.getWorldmapSegment(idField.getText()).getDataType() == GameSource.Type.source) { - message.setText("A worldmap segment with the same ID exists in the game. It will be added under \"altered\"."); - } - } + private WorldmapSegment creation = new WorldmapSegment(null, null, null); - ok.setEnabled(!trouble); - - message.revalidate(); - message.repaint(); - } - - public static interface CreationCompletedListener { - public void segmentCreated(WorldmapSegment created); - } - - private List listeners = new CopyOnWriteArrayList(); - - public void addCreationListener(CreationCompletedListener l) { - listeners.add(l); - } - - public void notifyCreated() { - for (CreationCompletedListener l : listeners) { - l.segmentCreated(creation); - } - } + final JLabel message; + final JTextField idField; + final JButton ok; + final Project proj; + + + public WorldmapCreationWizard(final Project proj) { + super(ATContentStudio.frame); + this.proj = proj; + setTitle("Create Worldmap segment"); + + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + + pane.add(new JLabel("Create a new worldmap segment."), JideBoxLayout.FIX); + + message = new JLabel("Enter a map segment ID below: "); + pane.add(message, JideBoxLayout.FIX); + + final JPanel idPane = new JPanel(); + idPane.setLayout(new BorderLayout()); + JLabel idLabel = new JLabel("Internal ID: "); + idPane.add(idLabel, BorderLayout.WEST); + idField = new JTextField(""); + idField.setEditable(true); + idPane.add(idField, BorderLayout.CENTER); + pane.add(idPane, JideBoxLayout.FIX); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancel = new JButton("Cancel"); + buttonPane.add(cancel, JideBoxLayout.FIX); + ok = new JButton("Ok"); + buttonPane.add(ok, JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + + ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + creation.id = idField.getText(); + WorldmapCreationWizard.this.setVisible(false); + WorldmapCreationWizard.this.dispose(); + proj.createWorldmapSegment(creation); + notifyCreated(); + ATContentStudio.frame.selectInTree(creation); + ATContentStudio.frame.openEditor(creation); + } + }); + + cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + creation = null; + WorldmapCreationWizard.this.setVisible(false); + WorldmapCreationWizard.this.dispose(); + } + }); + + DocumentListener statusUpdater = new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateStatus(); + } + }; + idField.getDocument().addDocumentListener(statusUpdater); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + setMinimumSize(new Dimension(350, 120)); + updateStatus(); + pack(); + + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + } + + public void updateStatus() { + boolean trouble = false; + message.setText("Looks OK to me."); + if (idField.getText() == null || idField.getText().length() <= 0) { + message.setText("Internal ID must not be empty."); + trouble = true; + } else if (proj.getWorldmapSegment(idField.getText()) != null) { + if (proj.getWorldmapSegment(idField.getText()).getDataType() == GameSource.Type.created) { + message.setText("A worldmap segment with the same ID was already created in this project."); + trouble = true; + } else if (proj.getWorldmapSegment(idField.getText()).getDataType() == GameSource.Type.altered) { + message.setText("A worldmap segment with the same ID exists in the game and is already altered in this project."); + trouble = true; + } else if (proj.getWorldmapSegment(idField.getText()).getDataType() == GameSource.Type.source) { + message.setText("A worldmap segment with the same ID exists in the game. It will be added under \"altered\"."); + } + } + + ok.setEnabled(!trouble); + + message.revalidate(); + message.repaint(); + } + + public static interface CreationCompletedListener { + public void segmentCreated(WorldmapSegment created); + } + + private List listeners = new CopyOnWriteArrayList(); + + public void addCreationListener(CreationCompletedListener l) { + listeners.add(l); + } + + public void notifyCreated() { + for (CreationCompletedListener l : listeners) { + l.segmentCreated(creation); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java index ff593ab..0b51a3b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorldmapLabelEditionWizard.java @@ -1,190 +1,185 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class WorldmapLabelEditionWizard extends JDialog { - private static final long serialVersionUID = 4911946705579386332L; + private static final long serialVersionUID = 4911946705579386332L; - final JLabel message; - final JTextField idField; - final JTextField labelField; - final JTextField typeField; - final JButton ok; - final WorldmapSegment segment; - final WorldmapSegment.NamedArea label; - - boolean createMode; - - public WorldmapLabelEditionWizard(WorldmapSegment segment) { - this(segment, new WorldmapSegment.NamedArea(null, null, null), true); - } - - public WorldmapLabelEditionWizard(WorldmapSegment segment, WorldmapSegment.NamedArea label) { - this(segment, label, false); - } - - public WorldmapLabelEditionWizard(WorldmapSegment segment, WorldmapSegment.NamedArea namedArea, boolean createMode) { - super(ATContentStudio.frame); - this.createMode = createMode; - this.segment = segment; - this.label = namedArea; - - setTitle(createMode ? "Create Worldmap Label" : "Edit Worldmap Label"); - - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - pane.add(new JLabel(createMode ? "Create a worldmap label." : "Edit a worldmap label."), JideBoxLayout.FIX); - - message = new JLabel("Enter a label ID below: "); - pane.add(message, JideBoxLayout.FIX); - - final JPanel idPane = new JPanel(); - idPane.setLayout(new BorderLayout()); - JLabel idLabel = new JLabel("Internal ID: "); - idPane.add(idLabel, BorderLayout.WEST); - idField = new JTextField(label.id); - idField.setEditable(true); - idPane.add(idField, BorderLayout.CENTER); - pane.add(idPane, JideBoxLayout.FIX); + final JLabel message; + final JTextField idField; + final JTextField labelField; + final JTextField typeField; + final JButton ok; + final WorldmapSegment segment; + final WorldmapSegment.NamedArea label; - final JPanel labelPane = new JPanel(); - labelPane.setLayout(new BorderLayout()); - JLabel labelLabel = new JLabel("Label: "); - labelPane.add(labelLabel, BorderLayout.WEST); - labelField = new JTextField(label.name); - labelField.setEditable(true); - labelPane.add(labelField, BorderLayout.CENTER); - pane.add(labelPane, JideBoxLayout.FIX); + boolean createMode; - final JPanel typePane = new JPanel(); - typePane.setLayout(new BorderLayout()); - JLabel typeLabel = new JLabel("Type: "); - typePane.add(typeLabel, BorderLayout.WEST); - typeField = new JTextField(label.type); - if (typeField.getText().equals("")) { - typeField.setText("settlement"); - } - typeField.setEditable(true); - typePane.add(typeField, BorderLayout.CENTER); - pane.add(typePane, JideBoxLayout.FIX); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancel = new JButton("Cancel"); - buttonPane.add(cancel, JideBoxLayout.FIX); - ok = new JButton("Ok"); - buttonPane.add(ok, JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - label.id = idField.getText(); - label.name = labelField.getText(); - label.type = labelField.getText(); - WorldmapLabelEditionWizard.this.setVisible(false); - WorldmapLabelEditionWizard.this.dispose(); - if (WorldmapLabelEditionWizard.this.createMode) { - WorldmapLabelEditionWizard.this.segment.labels.put(label.id, label); - } - notifyCreated(); - } - }); - - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - WorldmapLabelEditionWizard.this.setVisible(false); - WorldmapLabelEditionWizard.this.dispose(); - } - }); - - DocumentListener statusUpdater = new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void insertUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void changedUpdate(DocumentEvent e) { - updateStatus(); - } - }; - idField.getDocument().addDocumentListener(statusUpdater); - labelField.getDocument().addDocumentListener(statusUpdater); - typeField.getDocument().addDocumentListener(statusUpdater); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - setMinimumSize(new Dimension(350,170)); - updateStatus(); - pack(); - - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); - } - - public void updateStatus() { - boolean trouble = false; - message.setText("Looks OK to me."); - if (idField.getText() == null || idField.getText().length() <= 0) { - message.setText("Internal ID must not be empty."); - trouble = true; - } else if (segment.labels.get(idField.getText()) != null && segment.labels.get(idField.getText()) != label) { - message.setText("A worldmap label with the same ID already exists in this worldmap."); - trouble = true; - } else if (labelField.getText() == null || labelField.getText().length() <= 0) { - message.setText("Label must not be empty."); - trouble = true; - } + public WorldmapLabelEditionWizard(WorldmapSegment segment) { + this(segment, new WorldmapSegment.NamedArea(null, null, null), true); + } + + public WorldmapLabelEditionWizard(WorldmapSegment segment, WorldmapSegment.NamedArea label) { + this(segment, label, false); + } + + public WorldmapLabelEditionWizard(WorldmapSegment segment, WorldmapSegment.NamedArea namedArea, boolean createMode) { + super(ATContentStudio.frame); + this.createMode = createMode; + this.segment = segment; + this.label = namedArea; + + setTitle(createMode ? "Create Worldmap Label" : "Edit Worldmap Label"); + + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + + pane.add(new JLabel(createMode ? "Create a worldmap label." : "Edit a worldmap label."), JideBoxLayout.FIX); + + message = new JLabel("Enter a label ID below: "); + pane.add(message, JideBoxLayout.FIX); + + final JPanel idPane = new JPanel(); + idPane.setLayout(new BorderLayout()); + JLabel idLabel = new JLabel("Internal ID: "); + idPane.add(idLabel, BorderLayout.WEST); + idField = new JTextField(label.id); + idField.setEditable(true); + idPane.add(idField, BorderLayout.CENTER); + pane.add(idPane, JideBoxLayout.FIX); + + final JPanel labelPane = new JPanel(); + labelPane.setLayout(new BorderLayout()); + JLabel labelLabel = new JLabel("Label: "); + labelPane.add(labelLabel, BorderLayout.WEST); + labelField = new JTextField(label.name); + labelField.setEditable(true); + labelPane.add(labelField, BorderLayout.CENTER); + pane.add(labelPane, JideBoxLayout.FIX); + + final JPanel typePane = new JPanel(); + typePane.setLayout(new BorderLayout()); + JLabel typeLabel = new JLabel("Type: "); + typePane.add(typeLabel, BorderLayout.WEST); + typeField = new JTextField(label.type); + if (typeField.getText().equals("")) { + typeField.setText("settlement"); + } + typeField.setEditable(true); + typePane.add(typeField, BorderLayout.CENTER); + pane.add(typePane, JideBoxLayout.FIX); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancel = new JButton("Cancel"); + buttonPane.add(cancel, JideBoxLayout.FIX); + ok = new JButton("Ok"); + buttonPane.add(ok, JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + + ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + label.id = idField.getText(); + label.name = labelField.getText(); + label.type = labelField.getText(); + WorldmapLabelEditionWizard.this.setVisible(false); + WorldmapLabelEditionWizard.this.dispose(); + if (WorldmapLabelEditionWizard.this.createMode) { + WorldmapLabelEditionWizard.this.segment.labels.put(label.id, label); + } + notifyCreated(); + } + }); + + cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + WorldmapLabelEditionWizard.this.setVisible(false); + WorldmapLabelEditionWizard.this.dispose(); + } + }); + + DocumentListener statusUpdater = new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateStatus(); + } + }; + idField.getDocument().addDocumentListener(statusUpdater); + labelField.getDocument().addDocumentListener(statusUpdater); + typeField.getDocument().addDocumentListener(statusUpdater); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + setMinimumSize(new Dimension(350, 170)); + updateStatus(); + pack(); + + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + } + + public void updateStatus() { + boolean trouble = false; + message.setText("Looks OK to me."); + if (idField.getText() == null || idField.getText().length() <= 0) { + message.setText("Internal ID must not be empty."); + trouble = true; + } else if (segment.labels.get(idField.getText()) != null && segment.labels.get(idField.getText()) != label) { + message.setText("A worldmap label with the same ID already exists in this worldmap."); + trouble = true; + } else if (labelField.getText() == null || labelField.getText().length() <= 0) { + message.setText("Label must not be empty."); + trouble = true; + } // message.setText("This is a Warning example"); - ok.setEnabled(!trouble); - - message.revalidate(); - message.repaint(); - } - - public static interface CreationCompletedListener { - public void labelCreated(WorldmapSegment.NamedArea created); - } - - private List listeners = new CopyOnWriteArrayList(); - - public void addCreationListener(CreationCompletedListener l) { - listeners.add(l); - } - - public void notifyCreated() { - for (CreationCompletedListener l : listeners) { - l.labelCreated(label); - } - } + ok.setEnabled(!trouble); + + message.revalidate(); + message.repaint(); + } + + public static interface CreationCompletedListener { + public void labelCreated(WorldmapSegment.NamedArea created); + } + + private List listeners = new CopyOnWriteArrayList(); + + public void addCreationListener(CreationCompletedListener l) { + listeners.add(l); + } + + public void notifyCreated() { + for (CreationCompletedListener l : listeners) { + l.labelCreated(label); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WriterSketchCreationWizard.java b/src/com/gpl/rpg/atcontentstudio/ui/WriterSketchCreationWizard.java index 56ccf55..b1800d7 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WriterSketchCreationWizard.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WriterSketchCreationWizard.java @@ -1,19 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement.State; import com.gpl.rpg.atcontentstudio.model.Project; @@ -21,124 +7,133 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + public class WriterSketchCreationWizard extends JDialog { - private static final long serialVersionUID = 175788847797352548L; - - private WriterModeData creation = null; - final JLabel message; - final JTextField idField; - final JButton ok; - final Project proj; - - public WriterSketchCreationWizard(Project proj) { - this(proj, null); - } - - public WriterSketchCreationWizard(Project proj, final Dialogue dialogue) { - super(ATContentStudio.frame); - this.proj = proj; - - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - pane.add(new JLabel("Create a new game data element."), JideBoxLayout.FIX); - - message = new JLabel("Select a data type below:"); - pane.add(message, JideBoxLayout.FIX); - - final JPanel idPane = new JPanel(); - idPane.setLayout(new BorderLayout()); - JLabel idLabel = new JLabel("Dialogue ID prefix: "); - idPane.add(idLabel, BorderLayout.WEST); - idField = new JTextField(""); - idField.setEditable(true); - idPane.add(idField, BorderLayout.CENTER); - pane.add(idPane, JideBoxLayout.FIX); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton cancel = new JButton("Cancel"); - buttonPane.add(cancel, JideBoxLayout.FIX); - ok = new JButton("Ok"); - buttonPane.add(ok, JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - - ok.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - WriterSketchCreationWizard.this.setVisible(false); - WriterSketchCreationWizard.this.dispose(); - if (dialogue == null) { - creation = new WriterModeData(idField.getText()); - creation.state = State.created; - } else { - creation = new WriterModeData(idField.getText(), dialogue); - } - WriterSketchCreationWizard.this.proj.createWriterSketch(creation); -// notifyCreated(); - ATContentStudio.frame.selectInTree(creation); - ATContentStudio.frame.openEditor(creation); - } - }); - - cancel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - creation = null; - WriterSketchCreationWizard.this.setVisible(false); - WriterSketchCreationWizard.this.dispose(); - } - }); - - DocumentListener statusUpdater = new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void insertUpdate(DocumentEvent e) { - updateStatus(); - } - @Override - public void changedUpdate(DocumentEvent e) { - updateStatus(); - } - }; - idField.getDocument().addDocumentListener(statusUpdater); - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(pane, BorderLayout.CENTER); - - setMinimumSize(new Dimension(350,250)); - - updateStatus(); - pack(); - - Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); - Dimension wdim = getSize(); - setLocation((sdim.width - wdim.width)/2, (sdim.height - wdim.height)/2); + private static final long serialVersionUID = 175788847797352548L; + + private WriterModeData creation = null; + final JLabel message; + final JTextField idField; + final JButton ok; + final Project proj; + + public WriterSketchCreationWizard(Project proj) { + this(proj, null); + } + + public WriterSketchCreationWizard(Project proj, final Dialogue dialogue) { + super(ATContentStudio.frame); + this.proj = proj; + + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + + pane.add(new JLabel("Create a new game data element."), JideBoxLayout.FIX); + + message = new JLabel("Select a data type below:"); + pane.add(message, JideBoxLayout.FIX); + + final JPanel idPane = new JPanel(); + idPane.setLayout(new BorderLayout()); + JLabel idLabel = new JLabel("Dialogue ID prefix: "); + idPane.add(idLabel, BorderLayout.WEST); + idField = new JTextField(""); + idField.setEditable(true); + idPane.add(idField, BorderLayout.CENTER); + pane.add(idPane, JideBoxLayout.FIX); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS, 6)); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton cancel = new JButton("Cancel"); + buttonPane.add(cancel, JideBoxLayout.FIX); + ok = new JButton("Ok"); + buttonPane.add(ok, JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + + ok.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + WriterSketchCreationWizard.this.setVisible(false); + WriterSketchCreationWizard.this.dispose(); + if (dialogue == null) { + creation = new WriterModeData(idField.getText()); + creation.state = State.created; + } else { + creation = new WriterModeData(idField.getText(), dialogue); + } + WriterSketchCreationWizard.this.proj.createWriterSketch(creation); +// notifyCreated(); + ATContentStudio.frame.selectInTree(creation); + ATContentStudio.frame.openEditor(creation); + } + }); + + cancel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + creation = null; + WriterSketchCreationWizard.this.setVisible(false); + WriterSketchCreationWizard.this.dispose(); + } + }); + + DocumentListener statusUpdater = new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + updateStatus(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateStatus(); + } + }; + idField.getDocument().addDocumentListener(statusUpdater); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(pane, BorderLayout.CENTER); + + setMinimumSize(new Dimension(350, 250)); + + updateStatus(); + pack(); + + Dimension sdim = Toolkit.getDefaultToolkit().getScreenSize(); + Dimension wdim = getSize(); + setLocation((sdim.width - wdim.width) / 2, (sdim.height - wdim.height) / 2); + + } + + + public void updateStatus() { + boolean trouble = false; + message.setText("Looks OK to me."); + if (idField.getText() == null || idField.getText().length() <= 0) { + message.setText("Internal ID must not be empty."); + trouble = true; + } else if (proj.getWriterSketch(idField.getText()) != null) { + message.setText("An item with the same ID was already created in this project."); + trouble = true; + } + + ok.setEnabled(!trouble); + + message.revalidate(); + message.repaint(); + } - } - - - public void updateStatus() { - boolean trouble = false; - message.setText("Looks OK to me."); - if (idField.getText() == null || idField.getText().length() <= 0) { - message.setText("Internal ID must not be empty."); - trouble = true; - } else if (proj.getWriterSketch(idField.getText()) != null) { - message.setText("An item with the same ID was already created in this project."); - trouble = true; - } - - ok.setEnabled(!trouble); - - message.revalidate(); - message.repaint(); - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java index 9d6ef94..03348f0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java @@ -1,15 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.util.ArrayList; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.JTextField; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; @@ -20,530 +10,527 @@ import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import java.util.ArrayList; + public class ActorConditionEditor extends JSONElementEditor { - private static final long serialVersionUID = 799130864545495819L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - - private JButton acIcon; - private JTextField idField; - private JTextField nameField; - private JTextField descriptionField; - @SuppressWarnings("rawtypes") - private JComboBox categoryBox; - private IntegerBasedCheckBox positiveBox; - private IntegerBasedCheckBox stackingBox; - - //private JTextField roundVisualField; - @SuppressWarnings("rawtypes") - private JComboBox roundVisualField; - private JSpinner roundHpMinField; - private JSpinner roundHpMaxField; - private JSpinner roundApMinField; - private JSpinner roundApMaxField; - - //private JTextField fullRoundVisualField; - @SuppressWarnings("rawtypes") - private JComboBox fullRoundVisualField; - private JSpinner fullRoundHpMinField; - private JSpinner fullRoundHpMaxField; - private JSpinner fullRoundApMinField; - private JSpinner fullRoundApMaxField; + private static final long serialVersionUID = 799130864545495819L; - private JSpinner abilityHpField; - private JSpinner abilityApField; - private JSpinner abilityMoveCost; - private JSpinner abilityUseCost; - private JSpinner abilityReequipCost; - private JSpinner abilityAttackCost; - private JSpinner abilityAttackChance; - private JSpinner abilityDamageMinField; - private JSpinner abilityDamageMaxField; - private JSpinner abilityCriticalSkill; - private JSpinner abilityBlockChance; - private JSpinner abilityDamageResistance; - - - public ActorConditionEditor(ActorCondition ac) { - super(ac, ac.getDesc(), ac.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - } - - @Override - public void insertFormViewDataField(JPanel pane) { - final ActorCondition ac = ((ActorCondition)target); + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; - final FieldUpdateListener listener = new ActorConditionFieldUpdater(); - - acIcon = createButtonPane(pane, ac.getProject(), ac, ActorCondition.class, ac.getImage(), Spritesheet.Category.actorcondition, listener); - - idField = addTextField(pane, "Internal ID: ", ac.id, ac.writable, listener); - nameField = addTranslatableTextField(pane, "Display name: ", ac.display_name, ac.writable, listener); - descriptionField = addTranslatableTextField(pane, "Description: ", ac.description, ac.writable, listener); - categoryBox = addEnumValueBox(pane, "Category: ", ActorCondition.ACCategory.values(), ac.category, ac.writable, listener); - positiveBox = addIntegerBasedCheckBox(pane, "Positive", ac.positive, ac.writable, listener); - stackingBox = addIntegerBasedCheckBox(pane, "Stacking", ac.stacking, ac.writable, listener); - - - CollapsiblePanel roundEffectPane = new CollapsiblePanel("Effect every round (6s): "); - roundEffectPane.setLayout(new JideBoxLayout(roundEffectPane, JideBoxLayout.PAGE_AXIS)); - final ActorCondition.RoundEffect roundEffect; - if (ac.round_effect != null) { - roundEffect = ac.round_effect; - } else { - roundEffect = new ActorCondition.RoundEffect(); - } - roundVisualField = addEnumValueBox(roundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), roundEffect.visual_effect, ac.writable, listener);//addTextField(roundEffectPane, "Visual effect ID: ", roundEffect.visual_effect, ac.writable, listener); - roundHpMinField = addIntegerField(roundEffectPane, "HP Bonus Min: ", roundEffect.hp_boost_min, true, ac.writable, listener); - roundHpMaxField = addIntegerField(roundEffectPane, "HP Bonus Max: ", roundEffect.hp_boost_max, true, ac.writable, listener); - roundApMinField = addIntegerField(roundEffectPane, "AP Bonus Min: ", roundEffect.ap_boost_min, true, ac.writable, listener); - roundApMaxField = addIntegerField(roundEffectPane, "AP Bonus Max: ", roundEffect.ap_boost_max, true, ac.writable, listener); - roundEffectPane.setExpanded(ac.round_effect != null); - pane.add(roundEffectPane, JideBoxLayout.FIX); - - - CollapsiblePanel fullRoundEffectPane = new CollapsiblePanel("Effect every full round (25s): "); - fullRoundEffectPane.setLayout(new JideBoxLayout(fullRoundEffectPane, JideBoxLayout.PAGE_AXIS)); - final ActorCondition.RoundEffect fullRoundEffect; - if (ac.full_round_effect != null) { - fullRoundEffect = ac.full_round_effect; - } else { - fullRoundEffect = new ActorCondition.RoundEffect(); - } - fullRoundVisualField = addEnumValueBox(fullRoundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), fullRoundEffect.visual_effect, ac.writable, listener);//addTextField(fullRoundEffectPane, "Visual effect ID: ", fullRoundEffect.visual_effect, ac.writable, listener); - fullRoundHpMinField = addIntegerField(fullRoundEffectPane, "HP Bonus min: ", fullRoundEffect.hp_boost_min, true, ac.writable, listener); - fullRoundHpMaxField = addIntegerField(fullRoundEffectPane, "HP Bonus max: ", fullRoundEffect.hp_boost_max, true, ac.writable, listener); - fullRoundApMinField = addIntegerField(fullRoundEffectPane, "AP Bonus min: ", fullRoundEffect.ap_boost_min, true, ac.writable, listener); - fullRoundApMaxField = addIntegerField(fullRoundEffectPane, "AP Bonus max: ", fullRoundEffect.ap_boost_max, true, ac.writable, listener); - fullRoundEffectPane.setExpanded(ac.full_round_effect != null); - pane.add(fullRoundEffectPane, JideBoxLayout.FIX); - - CollapsiblePanel abilityEffectPane = new CollapsiblePanel("Constant ability effect: "); - abilityEffectPane.setLayout(new JideBoxLayout(abilityEffectPane, JideBoxLayout.PAGE_AXIS)); - ActorCondition.AbilityEffect abilityEffect; - if (ac.constant_ability_effect != null) { - abilityEffect = ac.constant_ability_effect; - } else { - abilityEffect = new ActorCondition.AbilityEffect(); - } - abilityHpField = addIntegerField(abilityEffectPane, "Boost max HP: ", abilityEffect.max_hp_boost, true, ac.writable, listener); - abilityApField = addIntegerField(abilityEffectPane, "Boost max AP: ", abilityEffect.max_ap_boost, true, ac.writable, listener); - abilityDamageMinField = addIntegerField(abilityEffectPane, "Boost min damage: ", abilityEffect.increase_damage_min, true, ac.writable, listener); - abilityDamageMaxField = addIntegerField(abilityEffectPane, "Boost max damage: ", abilityEffect.increase_damage_max, true, ac.writable, listener); - abilityAttackChance = addIntegerField(abilityEffectPane, "Boost attack chance: ", abilityEffect.increase_attack_chance, true, ac.writable, listener); - abilityBlockChance = addIntegerField(abilityEffectPane, "Boost block chance: ", abilityEffect.increase_block_chance, true, ac.writable, listener); - abilityCriticalSkill = addIntegerField(abilityEffectPane, "Boost critical skill: ", abilityEffect.increase_critical_skill, true, ac.writable, listener); - abilityDamageResistance = addIntegerField(abilityEffectPane, "Boost damage resistance: ", abilityEffect.increase_damage_resistance, true, ac.writable, listener); - abilityMoveCost = addIntegerField(abilityEffectPane, "Increase move cost: ", abilityEffect.increase_move_cost, true, ac.writable, listener); - abilityAttackCost = addIntegerField(abilityEffectPane, "Increase attack cost: ", abilityEffect.increase_attack_cost, true, ac.writable, listener); - abilityUseCost = addIntegerField(abilityEffectPane, "Increase item use cost: ", abilityEffect.increase_use_cost, true, ac.writable, listener); - abilityReequipCost = addIntegerField(abilityEffectPane, "Increase reequip cost: ", abilityEffect.increase_reequip_cost, true, ac.writable, listener); - abilityEffectPane.setExpanded(ac.constant_ability_effect != null); - pane.add(abilityEffectPane, JideBoxLayout.FIX); - - } + private JButton acIcon; + private JTextField idField; + private JTextField nameField; + private JTextField descriptionField; + @SuppressWarnings("rawtypes") + private JComboBox categoryBox; + private IntegerBasedCheckBox positiveBox; + private IntegerBasedCheckBox stackingBox; + + //private JTextField roundVisualField; + @SuppressWarnings("rawtypes") + private JComboBox roundVisualField; + private JSpinner roundHpMinField; + private JSpinner roundHpMaxField; + private JSpinner roundApMinField; + private JSpinner roundApMaxField; + + //private JTextField fullRoundVisualField; + @SuppressWarnings("rawtypes") + private JComboBox fullRoundVisualField; + private JSpinner fullRoundHpMinField; + private JSpinner fullRoundHpMaxField; + private JSpinner fullRoundApMinField; + private JSpinner fullRoundApMaxField; + + private JSpinner abilityHpField; + private JSpinner abilityApField; + private JSpinner abilityMoveCost; + private JSpinner abilityUseCost; + private JSpinner abilityReequipCost; + private JSpinner abilityAttackCost; + private JSpinner abilityAttackChance; + private JSpinner abilityDamageMinField; + private JSpinner abilityDamageMaxField; + private JSpinner abilityCriticalSkill; + private JSpinner abilityBlockChance; + private JSpinner abilityDamageResistance; + + + public ActorConditionEditor(ActorCondition ac) { + super(ac, ac.getDesc(), ac.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + } + + @Override + public void insertFormViewDataField(JPanel pane) { + final ActorCondition ac = ((ActorCondition) target); + + final FieldUpdateListener listener = new ActorConditionFieldUpdater(); + + acIcon = createButtonPane(pane, ac.getProject(), ac, ActorCondition.class, ac.getImage(), Spritesheet.Category.actorcondition, listener); + + idField = addTextField(pane, "Internal ID: ", ac.id, ac.writable, listener); + nameField = addTranslatableTextField(pane, "Display name: ", ac.display_name, ac.writable, listener); + descriptionField = addTranslatableTextField(pane, "Description: ", ac.description, ac.writable, listener); + categoryBox = addEnumValueBox(pane, "Category: ", ActorCondition.ACCategory.values(), ac.category, ac.writable, listener); + positiveBox = addIntegerBasedCheckBox(pane, "Positive", ac.positive, ac.writable, listener); + stackingBox = addIntegerBasedCheckBox(pane, "Stacking", ac.stacking, ac.writable, listener); + + + CollapsiblePanel roundEffectPane = new CollapsiblePanel("Effect every round (6s): "); + roundEffectPane.setLayout(new JideBoxLayout(roundEffectPane, JideBoxLayout.PAGE_AXIS)); + final ActorCondition.RoundEffect roundEffect; + if (ac.round_effect != null) { + roundEffect = ac.round_effect; + } else { + roundEffect = new ActorCondition.RoundEffect(); + } + roundVisualField = addEnumValueBox(roundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), roundEffect.visual_effect, ac.writable, listener);//addTextField(roundEffectPane, "Visual effect ID: ", roundEffect.visual_effect, ac.writable, listener); + roundHpMinField = addIntegerField(roundEffectPane, "HP Bonus Min: ", roundEffect.hp_boost_min, true, ac.writable, listener); + roundHpMaxField = addIntegerField(roundEffectPane, "HP Bonus Max: ", roundEffect.hp_boost_max, true, ac.writable, listener); + roundApMinField = addIntegerField(roundEffectPane, "AP Bonus Min: ", roundEffect.ap_boost_min, true, ac.writable, listener); + roundApMaxField = addIntegerField(roundEffectPane, "AP Bonus Max: ", roundEffect.ap_boost_max, true, ac.writable, listener); + roundEffectPane.setExpanded(ac.round_effect != null); + pane.add(roundEffectPane, JideBoxLayout.FIX); + + + CollapsiblePanel fullRoundEffectPane = new CollapsiblePanel("Effect every full round (25s): "); + fullRoundEffectPane.setLayout(new JideBoxLayout(fullRoundEffectPane, JideBoxLayout.PAGE_AXIS)); + final ActorCondition.RoundEffect fullRoundEffect; + if (ac.full_round_effect != null) { + fullRoundEffect = ac.full_round_effect; + } else { + fullRoundEffect = new ActorCondition.RoundEffect(); + } + fullRoundVisualField = addEnumValueBox(fullRoundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), fullRoundEffect.visual_effect, ac.writable, listener);//addTextField(fullRoundEffectPane, "Visual effect ID: ", fullRoundEffect.visual_effect, ac.writable, listener); + fullRoundHpMinField = addIntegerField(fullRoundEffectPane, "HP Bonus min: ", fullRoundEffect.hp_boost_min, true, ac.writable, listener); + fullRoundHpMaxField = addIntegerField(fullRoundEffectPane, "HP Bonus max: ", fullRoundEffect.hp_boost_max, true, ac.writable, listener); + fullRoundApMinField = addIntegerField(fullRoundEffectPane, "AP Bonus min: ", fullRoundEffect.ap_boost_min, true, ac.writable, listener); + fullRoundApMaxField = addIntegerField(fullRoundEffectPane, "AP Bonus max: ", fullRoundEffect.ap_boost_max, true, ac.writable, listener); + fullRoundEffectPane.setExpanded(ac.full_round_effect != null); + pane.add(fullRoundEffectPane, JideBoxLayout.FIX); + + CollapsiblePanel abilityEffectPane = new CollapsiblePanel("Constant ability effect: "); + abilityEffectPane.setLayout(new JideBoxLayout(abilityEffectPane, JideBoxLayout.PAGE_AXIS)); + ActorCondition.AbilityEffect abilityEffect; + if (ac.constant_ability_effect != null) { + abilityEffect = ac.constant_ability_effect; + } else { + abilityEffect = new ActorCondition.AbilityEffect(); + } + abilityHpField = addIntegerField(abilityEffectPane, "Boost max HP: ", abilityEffect.max_hp_boost, true, ac.writable, listener); + abilityApField = addIntegerField(abilityEffectPane, "Boost max AP: ", abilityEffect.max_ap_boost, true, ac.writable, listener); + abilityDamageMinField = addIntegerField(abilityEffectPane, "Boost min damage: ", abilityEffect.increase_damage_min, true, ac.writable, listener); + abilityDamageMaxField = addIntegerField(abilityEffectPane, "Boost max damage: ", abilityEffect.increase_damage_max, true, ac.writable, listener); + abilityAttackChance = addIntegerField(abilityEffectPane, "Boost attack chance: ", abilityEffect.increase_attack_chance, true, ac.writable, listener); + abilityBlockChance = addIntegerField(abilityEffectPane, "Boost block chance: ", abilityEffect.increase_block_chance, true, ac.writable, listener); + abilityCriticalSkill = addIntegerField(abilityEffectPane, "Boost critical skill: ", abilityEffect.increase_critical_skill, true, ac.writable, listener); + abilityDamageResistance = addIntegerField(abilityEffectPane, "Boost damage resistance: ", abilityEffect.increase_damage_resistance, true, ac.writable, listener); + abilityMoveCost = addIntegerField(abilityEffectPane, "Increase move cost: ", abilityEffect.increase_move_cost, true, ac.writable, listener); + abilityAttackCost = addIntegerField(abilityEffectPane, "Increase attack cost: ", abilityEffect.increase_attack_cost, true, ac.writable, listener); + abilityUseCost = addIntegerField(abilityEffectPane, "Increase item use cost: ", abilityEffect.increase_use_cost, true, ac.writable, listener); + abilityReequipCost = addIntegerField(abilityEffectPane, "Increase reequip cost: ", abilityEffect.increase_reequip_cost, true, ac.writable, listener); + abilityEffectPane.setExpanded(ac.constant_ability_effect != null); + pane.add(abilityEffectPane, JideBoxLayout.FIX); + + } + + + //TODO enhancement. Split this in smaller pieces (one for each base field, and one for each "*Effect". later, later.... + public class ActorConditionFieldUpdater implements FieldUpdateListener { + @Override + public void valueChanged(JComponent source, Object value) { + ActorCondition aCond = (ActorCondition) target; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + aCond.id = (String) value; + ActorConditionEditor.this.name = aCond.getDesc(); + aCond.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ActorConditionEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + aCond.display_name = (String) value; + ActorConditionEditor.this.name = aCond.getDesc(); + aCond.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ActorConditionEditor.this); + } else if (source == descriptionField) { + aCond.description = (String) value; + aCond.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ActorConditionEditor.this); + } else if (source == acIcon) { + aCond.icon_id = (String) value; + aCond.childrenChanged(new ArrayList()); + ActorConditionEditor.this.icon = new ImageIcon(aCond.getProject().getIcon((String) value)); + ATContentStudio.frame.editorChanged(ActorConditionEditor.this); + acIcon.setIcon(new ImageIcon(aCond.getProject().getImage((String) value))); + acIcon.revalidate(); + acIcon.repaint(); + } else if (source == positiveBox) { + aCond.positive = (Integer) value; + } else if (source == stackingBox) { + aCond.stacking = (Integer) value; + } else if (source == categoryBox) { + aCond.category = (ActorCondition.ACCategory) value; + } else if (source == roundVisualField) { + if (value == null) { + if (aCond.round_effect != null) { + aCond.round_effect.visual_effect = null; + if (isEmpty(aCond.round_effect)) { + aCond.round_effect = null; + } + } + } else { + if (aCond.round_effect == null) { + aCond.round_effect = new ActorCondition.RoundEffect(); + } + aCond.round_effect.visual_effect = (ActorCondition.VisualEffectID) value; + } + } else if (source == roundHpMinField) { + if (value == null) { + if (aCond.round_effect != null) { + aCond.round_effect.hp_boost_min = null; + if (isEmpty(aCond.round_effect)) { + aCond.round_effect = null; + } + } + } else { + if (aCond.round_effect == null) { + aCond.round_effect = new ActorCondition.RoundEffect(); + } + aCond.round_effect.hp_boost_min = (Integer) value; + } + } else if (source == roundHpMaxField) { + if (value == null) { + if (aCond.round_effect != null) { + aCond.round_effect.hp_boost_max = null; + if (isEmpty(aCond.round_effect)) { + aCond.round_effect = null; + } + } + } else { + if (aCond.round_effect == null) { + aCond.round_effect = new ActorCondition.RoundEffect(); + } + aCond.round_effect.hp_boost_max = (Integer) value; + } + } else if (source == roundApMinField) { + if (value == null) { + if (aCond.round_effect != null) { + aCond.round_effect.ap_boost_min = null; + if (isEmpty(aCond.round_effect)) { + aCond.round_effect = null; + } + } + } else { + if (aCond.round_effect == null) { + aCond.round_effect = new ActorCondition.RoundEffect(); + } + aCond.round_effect.ap_boost_min = (Integer) value; + } + } else if (source == roundApMaxField) { + if (value == null) { + if (aCond.round_effect != null) { + aCond.round_effect.ap_boost_max = null; + if (isEmpty(aCond.round_effect)) { + aCond.round_effect = null; + } + } + } else { + if (aCond.round_effect == null) { + aCond.round_effect = new ActorCondition.RoundEffect(); + } + aCond.round_effect.ap_boost_max = (Integer) value; + } + } else if (source == fullRoundVisualField) { + if (value == null) { + if (aCond.full_round_effect != null) { + aCond.full_round_effect.visual_effect = null; + if (isEmpty(aCond.full_round_effect)) { + aCond.full_round_effect = null; + } + } + } else { + if (aCond.full_round_effect == null) { + aCond.full_round_effect = new ActorCondition.RoundEffect(); + } + aCond.full_round_effect.visual_effect = (ActorCondition.VisualEffectID) value; + } + } else if (source == fullRoundHpMinField) { + if (value == null) { + if (aCond.full_round_effect != null) { + aCond.full_round_effect.hp_boost_min = null; + if (isEmpty(aCond.full_round_effect)) { + aCond.full_round_effect = null; + } + } + } else { + if (aCond.full_round_effect == null) { + aCond.full_round_effect = new ActorCondition.RoundEffect(); + } + aCond.full_round_effect.hp_boost_min = (Integer) value; + } + } else if (source == fullRoundHpMaxField) { + if (value == null) { + if (aCond.full_round_effect != null) { + aCond.full_round_effect.hp_boost_max = null; + if (isEmpty(aCond.full_round_effect)) { + aCond.full_round_effect = null; + } + } + } else { + if (aCond.full_round_effect == null) { + aCond.full_round_effect = new ActorCondition.RoundEffect(); + } + aCond.full_round_effect.hp_boost_max = (Integer) value; + } + } else if (source == fullRoundApMinField) { + if (value == null) { + if (aCond.full_round_effect != null) { + aCond.full_round_effect.ap_boost_min = null; + if (isEmpty(aCond.full_round_effect)) { + aCond.full_round_effect = null; + } + } + } else { + if (aCond.full_round_effect == null) { + aCond.full_round_effect = new ActorCondition.RoundEffect(); + } + aCond.full_round_effect.ap_boost_min = (Integer) value; + } + } else if (source == fullRoundApMaxField) { + if (value == null) { + if (aCond.full_round_effect != null) { + aCond.full_round_effect.ap_boost_max = null; + if (isEmpty(aCond.full_round_effect)) { + aCond.full_round_effect = null; + } + } + } else { + if (aCond.full_round_effect == null) { + aCond.full_round_effect = new ActorCondition.RoundEffect(); + } + aCond.full_round_effect.ap_boost_max = (Integer) value; + } + } else if (source == abilityHpField) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.max_hp_boost = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.max_hp_boost = (Integer) value; + } + } else if (source == abilityApField) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.max_ap_boost = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.max_ap_boost = (Integer) value; + } + } else if (source == abilityMoveCost) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_move_cost = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_move_cost = (Integer) value; + } + } else if (source == abilityUseCost) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_use_cost = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_use_cost = (Integer) value; + } + } else if (source == abilityReequipCost) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_reequip_cost = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_reequip_cost = (Integer) value; + } + } else if (source == abilityAttackCost) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_attack_cost = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_attack_cost = (Integer) value; + } + } else if (source == abilityAttackChance) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_attack_chance = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_attack_chance = (Integer) value; + } + } else if (source == abilityDamageMinField) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_damage_min = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_damage_min = (Integer) value; + } + } else if (source == abilityDamageMaxField) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_damage_max = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_damage_max = (Integer) value; + } + } else if (source == abilityCriticalSkill) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_critical_skill = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_critical_skill = (Integer) value; + } + } else if (source == abilityBlockChance) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_block_chance = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_block_chance = (Integer) value; + } + } else if (source == abilityDamageResistance) { + if (value == null) { + if (aCond.constant_ability_effect != null) { + aCond.constant_ability_effect.increase_damage_resistance = null; + if (isEmpty(aCond.constant_ability_effect)) { + aCond.constant_ability_effect = null; + } + } + } else { + if (aCond.constant_ability_effect == null) { + aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); + } + aCond.constant_ability_effect.increase_damage_resistance = (Integer) value; + } + } + + if (aCond.state != GameDataElement.State.modified) { + aCond.state = GameDataElement.State.modified; + ActorConditionEditor.this.name = aCond.getDesc(); + aCond.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ActorConditionEditor.this); + } + updateJsonViewText(aCond.toJsonString()); + } + + private boolean isEmpty(ActorCondition.RoundEffect round_effect) { + return round_effect == null || ( + round_effect.visual_effect == null && + round_effect.hp_boost_min == null && + round_effect.hp_boost_max == null && + round_effect.ap_boost_min == null && + round_effect.ap_boost_max == null + ); + } + + private boolean isEmpty(ActorCondition.AbilityEffect ability_effect) { + return ability_effect == null || ( + ability_effect.max_hp_boost == null && + ability_effect.max_ap_boost == null && + ability_effect.increase_move_cost == null && + ability_effect.increase_use_cost == null && + ability_effect.increase_reequip_cost == null && + ability_effect.increase_attack_cost == null && + ability_effect.increase_attack_chance == null && + ability_effect.increase_damage_min == null && + ability_effect.increase_damage_max == null && + ability_effect.increase_critical_skill == null && + ability_effect.increase_block_chance == null && + ability_effect.increase_damage_resistance == null + ); + } + } - - //TODO enhancement. Split this in smaller pieces (one for each base field, and one for each "*Effect". later, later.... - public class ActorConditionFieldUpdater implements FieldUpdateListener { - @Override - public void valueChanged(JComponent source, Object value) { - ActorCondition aCond = (ActorCondition)target; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - aCond.id = (String) value; - ActorConditionEditor.this.name = aCond.getDesc(); - aCond.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ActorConditionEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - aCond.display_name = (String) value; - ActorConditionEditor.this.name = aCond.getDesc(); - aCond.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ActorConditionEditor.this); - }else if (source == descriptionField) { - aCond.description = (String) value; - aCond.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ActorConditionEditor.this); - } else if (source == acIcon) { - aCond.icon_id = (String) value; - aCond.childrenChanged(new ArrayList()); - ActorConditionEditor.this.icon = new ImageIcon(aCond.getProject().getIcon((String) value)); - ATContentStudio.frame.editorChanged(ActorConditionEditor.this); - acIcon.setIcon(new ImageIcon(aCond.getProject().getImage((String) value))); - acIcon.revalidate(); - acIcon.repaint(); - } else if (source == positiveBox) { - aCond.positive = (Integer) value; - } else if (source == stackingBox) { - aCond.stacking = (Integer) value; - } else if (source == categoryBox) { - aCond.category = (ActorCondition.ACCategory) value; - } else if (source == roundVisualField) { - if (value == null) { - if (aCond.round_effect != null) { - aCond.round_effect.visual_effect = null; - if (isEmpty(aCond.round_effect)) { - aCond.round_effect = null; - } - } - } else { - if (aCond.round_effect == null) { - aCond.round_effect = new ActorCondition.RoundEffect(); - } - aCond.round_effect.visual_effect = (ActorCondition.VisualEffectID) value; - } - } else if (source == roundHpMinField) { - if (value == null) { - if (aCond.round_effect != null) { - aCond.round_effect.hp_boost_min = null; - if (isEmpty(aCond.round_effect)) { - aCond.round_effect = null; - } - } - } else { - if (aCond.round_effect == null) { - aCond.round_effect = new ActorCondition.RoundEffect(); - } - aCond.round_effect.hp_boost_min = (Integer) value; - } - } else if (source == roundHpMaxField) { - if (value == null) { - if (aCond.round_effect != null) { - aCond.round_effect.hp_boost_max = null; - if (isEmpty(aCond.round_effect)) { - aCond.round_effect = null; - } - } - } else { - if (aCond.round_effect == null) { - aCond.round_effect = new ActorCondition.RoundEffect(); - } - aCond.round_effect.hp_boost_max = (Integer) value; - } - } else if (source == roundApMinField) { - if (value == null) { - if (aCond.round_effect != null) { - aCond.round_effect.ap_boost_min = null; - if (isEmpty(aCond.round_effect)) { - aCond.round_effect = null; - } - } - } else { - if (aCond.round_effect == null) { - aCond.round_effect = new ActorCondition.RoundEffect(); - } - aCond.round_effect.ap_boost_min = (Integer) value; - } - } else if (source == roundApMaxField) { - if (value == null) { - if (aCond.round_effect != null) { - aCond.round_effect.ap_boost_max = null; - if (isEmpty(aCond.round_effect)) { - aCond.round_effect = null; - } - } - } else { - if (aCond.round_effect == null) { - aCond.round_effect = new ActorCondition.RoundEffect(); - } - aCond.round_effect.ap_boost_max = (Integer) value; - } - } else if (source == fullRoundVisualField) { - if (value == null) { - if (aCond.full_round_effect != null) { - aCond.full_round_effect.visual_effect = null; - if (isEmpty(aCond.full_round_effect)) { - aCond.full_round_effect = null; - } - } - } else { - if (aCond.full_round_effect == null) { - aCond.full_round_effect = new ActorCondition.RoundEffect(); - } - aCond.full_round_effect.visual_effect = (ActorCondition.VisualEffectID) value; - } - } else if (source == fullRoundHpMinField) { - if (value == null) { - if (aCond.full_round_effect != null) { - aCond.full_round_effect.hp_boost_min = null; - if (isEmpty(aCond.full_round_effect)) { - aCond.full_round_effect = null; - } - } - } else { - if (aCond.full_round_effect == null) { - aCond.full_round_effect = new ActorCondition.RoundEffect(); - } - aCond.full_round_effect.hp_boost_min = (Integer) value; - } - } else if (source == fullRoundHpMaxField) { - if (value == null) { - if (aCond.full_round_effect != null) { - aCond.full_round_effect.hp_boost_max = null; - if (isEmpty(aCond.full_round_effect)) { - aCond.full_round_effect = null; - } - } - } else { - if (aCond.full_round_effect == null) { - aCond.full_round_effect = new ActorCondition.RoundEffect(); - } - aCond.full_round_effect.hp_boost_max = (Integer) value; - } - } else if (source == fullRoundApMinField) { - if (value == null) { - if (aCond.full_round_effect != null) { - aCond.full_round_effect.ap_boost_min = null; - if (isEmpty(aCond.full_round_effect)) { - aCond.full_round_effect = null; - } - } - } else { - if (aCond.full_round_effect == null) { - aCond.full_round_effect = new ActorCondition.RoundEffect(); - } - aCond.full_round_effect.ap_boost_min = (Integer) value; - } - } else if (source == fullRoundApMaxField) { - if (value == null) { - if (aCond.full_round_effect != null) { - aCond.full_round_effect.ap_boost_max = null; - if (isEmpty(aCond.full_round_effect)) { - aCond.full_round_effect = null; - } - } - } else { - if (aCond.full_round_effect == null) { - aCond.full_round_effect = new ActorCondition.RoundEffect(); - } - aCond.full_round_effect.ap_boost_max = (Integer) value; - } - } else if (source == abilityHpField) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.max_hp_boost = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.max_hp_boost = (Integer) value; - } - } else if (source == abilityApField) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.max_ap_boost = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.max_ap_boost = (Integer) value; - } - } else if (source == abilityMoveCost) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_move_cost = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_move_cost = (Integer) value; - } - } else if (source == abilityUseCost) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_use_cost = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_use_cost = (Integer) value; - } - } else if (source == abilityReequipCost) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_reequip_cost = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_reequip_cost = (Integer) value; - } - } else if (source == abilityAttackCost) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_attack_cost = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_attack_cost = (Integer) value; - } - } else if (source == abilityAttackChance) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_attack_chance = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_attack_chance = (Integer) value; - } - } else if (source == abilityDamageMinField) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_damage_min = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_damage_min = (Integer) value; - } - } else if (source == abilityDamageMaxField) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_damage_max = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_damage_max = (Integer) value; - } - } else if (source == abilityCriticalSkill) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_critical_skill = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_critical_skill = (Integer) value; - } - } else if (source == abilityBlockChance) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_block_chance = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_block_chance = (Integer) value; - } - } else if (source == abilityDamageResistance) { - if (value == null) { - if (aCond.constant_ability_effect != null) { - aCond.constant_ability_effect.increase_damage_resistance = null; - if (isEmpty(aCond.constant_ability_effect)) { - aCond.constant_ability_effect = null; - } - } - } else { - if (aCond.constant_ability_effect == null) { - aCond.constant_ability_effect = new ActorCondition.AbilityEffect(); - } - aCond.constant_ability_effect.increase_damage_resistance = (Integer) value; - } - } - - if (aCond.state != GameDataElement.State.modified) { - aCond.state = GameDataElement.State.modified; - ActorConditionEditor.this.name = aCond.getDesc(); - aCond.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ActorConditionEditor.this); - } - updateJsonViewText(aCond.toJsonString()); - } - private boolean isEmpty(ActorCondition.RoundEffect round_effect) { - return round_effect == null || ( - round_effect.visual_effect == null && - round_effect.hp_boost_min == null && - round_effect.hp_boost_max == null && - round_effect.ap_boost_min == null && - round_effect.ap_boost_max == null - ); - } - - private boolean isEmpty(ActorCondition.AbilityEffect ability_effect) { - return ability_effect == null || ( - ability_effect.max_hp_boost == null && - ability_effect.max_ap_boost == null && - ability_effect.increase_move_cost == null && - ability_effect.increase_use_cost == null && - ability_effect.increase_reequip_cost == null && - ability_effect.increase_attack_cost == null && - ability_effect.increase_attack_chance == null && - ability_effect.increase_damage_min == null && - ability_effect.increase_damage_max == null && - ability_effect.increase_critical_skill == null && - ability_effect.increase_block_chance == null && - ability_effect.increase_damage_resistance == null - ); - } - } - - - - - - - - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index 11513cd..b7dc0b8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -1,7 +1,18 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.awt.BorderLayout; -import java.awt.Component; +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; +import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; +import com.gpl.rpg.atcontentstudio.utils.UiUtils; +import com.jidesoft.swing.JideBoxLayout; + +import javax.swing.*; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; @@ -9,1071 +20,1039 @@ import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.List; -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JSpinner; -import javax.swing.JTextArea; -import javax.swing.JTextField; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; -import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; -import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; -import com.gpl.rpg.atcontentstudio.ui.BooleanBasedCheckBox; -import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; -import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; -import com.gpl.rpg.atcontentstudio.utils.UiUtils; -import com.jidesoft.swing.JideBoxLayout; - public class DialogueEditor extends JSONElementEditor { - private static final long serialVersionUID = 4140553240585599873L; + private static final long serialVersionUID = 4140553240585599873L; - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - private static final String graph_view_id = "Dialogue Tree"; - - private Dialogue.Reward selectedReward; - private Dialogue.Reply selectedReply; - private Requirement selectedRequirement; - - - private static final String[] replyTypes = new String[]{ - "Phrase leads to another without replies.", - "NPC replies too.", - "Reply ends dialogue.", - "Engage fight with NPC.", - "Remove NPC from map.", - "Start trading with NPC." - }; - private static final int GO_NEXT_INDEX = 0; - private static final int STD_REPLY_INDEX = 1; - private static final int END_INDEX = 2; - private static final int FIGHT_INDEX = 3; - private static final int REMOVE_INDEX = 4; - private static final int SHOP_INDEX = 5; - - private JTextField idField; - private JTextArea messageField; - private MyComboBox switchToNpcBox; - - private RewardsListModel rewardsListModel; - @SuppressWarnings("rawtypes") - private JList rewardsList; - @SuppressWarnings("rawtypes") - private JComboBox rewardTypeCombo; - private JPanel rewardsParamsPane; - private MyComboBox rewardMap; - private JTextField rewardObjId; - @SuppressWarnings("rawtypes") - private JComboBox rewardObjIdCombo; - private MyComboBox rewardObj; - private JComponent rewardValue; - private JRadioButton rewardConditionTimed; - private JRadioButton rewardConditionForever; - private JRadioButton rewardConditionClear; - - private RepliesListModel repliesListModel; - @SuppressWarnings("rawtypes") - private JList repliesList; - private JPanel repliesParamsPane; - @SuppressWarnings("rawtypes") - private JComboBox replyTypeCombo; - private MyComboBox replyNextPhrase; - private String replyTextCache = null; - private JTextField replyText; - - private ReplyRequirementsListModel requirementsListModel; - @SuppressWarnings("rawtypes") - private JList requirementsList; - @SuppressWarnings("rawtypes") - private JComboBox requirementTypeCombo; - private JPanel requirementParamsPane; - private MyComboBox requirementObj; - @SuppressWarnings("rawtypes") - private JComboBox requirementSkill; - private JComponent requirementObjId; - private JComponent requirementValue; - private BooleanBasedCheckBox requirementNegated; - - private DialogueGraphView dialogueGraphView; - - - public DialogueEditor(Dialogue dialogue) { - super(dialogue, dialogue.getDesc(), dialogue.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - addEditorTab(graph_view_id, createDialogueGraphView(dialogue)); - } - - public JPanel createDialogueGraphView(final Dialogue dialogue) { - final JPanel pane = new JPanel(); - pane.setLayout(new BorderLayout()); - - dialogueGraphView = new DialogueGraphView(dialogue, null); - pane.add(dialogueGraphView, BorderLayout.CENTER); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - JButton reloadButton = new JButton("Refresh graph"); - buttonPane.add(reloadButton, JideBoxLayout.FIX); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, BorderLayout.NORTH); - - - reloadButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - pane.remove(dialogueGraphView); - dialogueGraphView = new DialogueGraphView(dialogue, null); - pane.add(dialogueGraphView, BorderLayout.CENTER); - pane.revalidate(); - pane.repaint(); - } - }); - - return pane; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void insertFormViewDataField(final JPanel pane) { - - final Dialogue dialogue = (Dialogue) target; - final FieldUpdateListener listener = new DialogueFieldUpdater(); - - createButtonPane(pane, dialogue.getProject(), dialogue, Dialogue.class, dialogue.getImage(), null, listener); - - idField = addTextField(pane, "Internal ID: ", dialogue.id, dialogue.writable, listener); - messageField = addTranslatableTextArea(pane, "Message: ", dialogue.message, dialogue.writable, listener); - switchToNpcBox = addNPCBox(pane, dialogue.getProject(), "Switch active NPC to: ", dialogue.switch_to_npc, dialogue.writable, listener); + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; + private static final String graph_view_id = "Dialogue Tree"; - RewardsCellRenderer cellRendererRewards = new RewardsCellRenderer(); - String titleRewards = "Reaching this phrase gives the following rewards: "; - rewardsListModel = new RewardsListModel(dialogue); + private Dialogue.Reward selectedReward; + private Dialogue.Reply selectedReply; + private Requirement selectedRequirement; - CollapsiblePanel rewards = UiUtils.getCollapsibleItemList( - listener, - rewardsListModel, - () -> selectedReward = null, - ( selectedItem) -> this.selectedReward = selectedItem, - () -> this.selectedReward, - (reward)->{}, - (editorPane) -> updateRewardsEditorPane(editorPane, this.selectedReward, listener), - dialogue.writable, - Dialogue.Reward::new, - cellRendererRewards, - titleRewards, - (x)->null, - false - ).collapsiblePanel; - if (dialogue.rewards == null || dialogue.rewards.isEmpty()) { - rewards.collapse(); - } - pane.add(rewards, JideBoxLayout.FIX); - RepliesCellRenderer cellRendererReplies = new RepliesCellRenderer(); - String titleReplies = "Replies / Next Phrase: "; - repliesListModel = new RepliesListModel(dialogue); - CollapsiblePanel replies = UiUtils.getCollapsibleItemList( - listener, - repliesListModel, - () -> selectedReply = null, - ( selectedItem) -> this.selectedReply = selectedItem, - () -> this.selectedReply, - (selectedReply)-> { - if (selectedReply != null && !Dialogue.Reply.GO_NEXT_TEXT.equals(selectedReply.text)) { - replyTextCache = selectedReply.text; - } else { - replyTextCache = null; - } - }, - (editorPane) -> updateRepliesEditorPane(editorPane, this.selectedReply, listener), - dialogue.writable, - Dialogue.Reply::new, - cellRendererReplies, - titleReplies, - (x)->null, - true - ).collapsiblePanel; - if (dialogue.replies == null || dialogue.replies.isEmpty()) { - replies.collapse(); - } + private static final String[] replyTypes = new String[]{ + "Phrase leads to another without replies.", + "NPC replies too.", + "Reply ends dialogue.", + "Engage fight with NPC.", + "Remove NPC from map.", + "Start trading with NPC." + }; + private static final int GO_NEXT_INDEX = 0; + private static final int STD_REPLY_INDEX = 1; + private static final int END_INDEX = 2; + private static final int FIGHT_INDEX = 3; + private static final int REMOVE_INDEX = 4; + private static final int SHOP_INDEX = 5; - pane.add(replies, JideBoxLayout.FIX); - - - } - - public void updateRewardsEditorPane(final JPanel pane, final Dialogue.Reward reward, final FieldUpdateListener listener) { - pane.removeAll(); - if (rewardMap != null) { - removeElementListener(rewardMap); - } - if (rewardObj != null) { - removeElementListener(rewardObj); - } - - if (reward != null) { - rewardTypeCombo = addEnumValueBox(pane, "Reward type: ", Dialogue.Reward.RewardType.values(), reward.type, ((Dialogue)target).writable, listener); - rewardsParamsPane = new JPanel(); - rewardsParamsPane.setLayout(new JideBoxLayout(rewardsParamsPane, JideBoxLayout.PAGE_AXIS)); - updateRewardsParamsEditorPane(rewardsParamsPane, reward, listener); - pane.add(rewardsParamsPane, JideBoxLayout.FIX); - } - pane.revalidate(); - pane.repaint(); - } - - public void updateRewardsParamsEditorPane(final JPanel pane, final Dialogue.Reward reward, final FieldUpdateListener listener) { - boolean writable = ((Dialogue)target).writable; - pane.removeAll(); - if (rewardMap != null) { - removeElementListener(rewardMap); - } - if (rewardObj != null) { - removeElementListener(rewardObj); - } - boolean immunity = false; - if (reward.type != null) { - switch (reward.type) { - case activateMapObjectGroup: - case deactivateMapObjectGroup: - rewardMap = addMapBox(pane, ((Dialogue)target).getProject(), "Map Name: ", reward.map, writable, listener); - rewardObjId = addTextField(pane, "Group ID: ", reward.reward_obj_id, writable, listener); - rewardObjIdCombo = null; - rewardObj = null; - rewardValue = null; - break; - case changeMapFilter: - rewardMap = addMapBox(pane, ((Dialogue)target).getProject(), "Map Name: ", reward.map, writable, listener); - rewardObjId = null; - rewardObjIdCombo = addEnumValueBox(pane, "Color Filter", TMXMap.ColorFilter.values(), reward.reward_obj_id != null ? TMXMap.ColorFilter.valueOf(reward.reward_obj_id) : TMXMap.ColorFilter.none, writable, listener); - rewardObj = null; - rewardValue = null; - break; - case mapchange: - rewardMap = addMapBox(pane, ((Dialogue)target).getProject(), "Map Name: ", reward.map, writable, listener); - rewardObjId = addTextField(pane, "Place: ", reward.reward_obj_id, writable, listener); - rewardObjIdCombo = null; - rewardObj = null; - rewardValue = null; - break; - case deactivateSpawnArea: - case removeSpawnArea: - case spawnAll: - rewardMap = addMapBox(pane, ((Dialogue)target).getProject(), "Map Name: ", reward.map, writable, listener); - rewardObjId = addTextField(pane, "Area ID: ", reward.reward_obj_id, writable, listener); - rewardObjIdCombo = null; - rewardObj = null; - rewardValue = null; - break; - case actorConditionImmunity: - immunity = true; - case actorCondition: - - rewardMap = null; - rewardObjId = null; - rewardObjIdCombo = null; - rewardObj = addActorConditionBox(pane, ((Dialogue)target).getProject(), "Actor Condition: ", (ActorCondition) reward.reward_obj, writable, listener); - rewardConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(rewardConditionTimed, JideBoxLayout.FIX); - rewardValue = addIntegerField(pane, "Duration: ", reward.reward_value, 1, false, writable, listener); - rewardConditionForever = new JRadioButton("Forever"); - pane.add(rewardConditionForever, JideBoxLayout.FIX); - if (!immunity) { - rewardConditionClear = new JRadioButton("Clear actor condition"); - pane.add(rewardConditionClear, JideBoxLayout.FIX); - } - - ButtonGroup radioGroup = new ButtonGroup(); - radioGroup.add(rewardConditionTimed); - radioGroup.add(rewardConditionForever); - if (!immunity) radioGroup.add(rewardConditionClear); - - if (immunity) { - rewardConditionTimed.setSelected(reward.reward_value == null || (reward.reward_value != ActorCondition.DURATION_FOREVER && reward.reward_value != ActorCondition.MAGNITUDE_CLEAR)); - rewardConditionForever.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.DURATION_FOREVER); - rewardConditionClear.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.MAGNITUDE_CLEAR); - } else { - rewardConditionTimed.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.DURATION_FOREVER); - rewardConditionForever.setSelected(reward.reward_value == null || reward.reward_value == ActorCondition.DURATION_FOREVER); - } - rewardValue.setEnabled(rewardConditionTimed.isSelected()); - - rewardConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(rewardConditionTimed, new Boolean(rewardConditionTimed.isSelected())); - } - }); - rewardConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(rewardConditionForever, new Boolean(rewardConditionForever.isSelected())); - } - }); - if (!immunity) { - rewardConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(rewardConditionClear, new Boolean(rewardConditionClear.isSelected())); - } - }); - } - break; - case alignmentChange: - case alignmentSet: - rewardMap = null; - rewardObjId = addTextField(pane, "Faction: ", reward.reward_obj_id, writable, listener); - rewardObjIdCombo = null; - rewardObj = null; - rewardValue = addIntegerField(pane, "Value: ", reward.reward_value, true, writable, listener); - break; - case createTimer: - rewardMap = null; - rewardObjId = addTextField(pane, "Timer ID: ", reward.reward_obj_id, writable, listener); - rewardObjIdCombo = null; - rewardObj = null; - rewardValue = null; - break; - case dropList: - rewardMap = null; - rewardObjId = null; - rewardObjIdCombo = null; - rewardObj = addDroplistBox(pane, ((Dialogue)target).getProject(), "Droplist: ", (Droplist) reward.reward_obj, writable, listener); - rewardValue = null; - break; - case giveItem: - rewardMap = null; - rewardObjId = null; - rewardObj = addItemBox(pane, ((Dialogue)target).getProject(), "Item: ", (Item) reward.reward_obj, writable, listener); - rewardValue = addIntegerField(pane, "Quantity: ", reward.reward_value, true, writable, listener); - break; - case removeQuestProgress: - case questProgress: - rewardMap = null; - rewardObjId = null; - rewardObjIdCombo = null; - rewardObj = addQuestBox(pane, ((Dialogue)target).getProject(), "Quest: ", (Quest) reward.reward_obj, writable, listener); - rewardValue = addQuestStageBox(pane, ((Dialogue)target).getProject(), "Quest stage: ", reward.reward_value, writable, listener, (Quest) reward.reward_obj, rewardObj); - break; - case skillIncrease: - Requirement.SkillID skillId = null; - try { - skillId = reward.reward_obj_id == null ? null : Requirement.SkillID.valueOf(reward.reward_obj_id); - } catch(IllegalArgumentException e) {} - rewardMap = null; - rewardObjId = null;// addTextField(pane, "Skill ID: ", reward.reward_obj_id, writable, listener); - rewardObjIdCombo = addEnumValueBox(pane, "Skill ID: ", Requirement.SkillID.values(), skillId, writable, listener); - rewardObj = null; - rewardValue = null; - break; + private JTextField idField; + private JTextArea messageField; + private MyComboBox switchToNpcBox; - } - } - pane.revalidate(); - pane.repaint(); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void updateRepliesEditorPane(final JPanel pane, final Dialogue.Reply reply, final FieldUpdateListener listener) { - pane.removeAll(); - if (replyNextPhrase != null) { - removeElementListener(replyNextPhrase); - } - if (requirementObj != null) { - removeElementListener(requirementObj); - } - if (reply == null) return; - - JPanel comboPane = new JPanel(); - comboPane.setLayout(new BorderLayout()); - JLabel comboLabel = new JLabel("Reply type: "); - comboPane.add(comboLabel, BorderLayout.WEST); - - replyTypeCombo = new JComboBox(replyTypes); - replyTypeCombo.setEnabled(((Dialogue)target).writable); - repliesParamsPane = new JPanel(); - repliesParamsPane.setLayout(new JideBoxLayout(repliesParamsPane, JideBoxLayout.PAGE_AXIS)); - if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text)) { - replyTypeCombo.setSelectedItem(replyTypes[GO_NEXT_INDEX]); - } else if (Dialogue.Reply.EXIT_PHRASE_ID.equals(reply.next_phrase_id)) { - replyTypeCombo.setSelectedItem(replyTypes[END_INDEX]); - } else if (Dialogue.Reply.FIGHT_PHRASE_ID.equals(reply.next_phrase_id)) { - replyTypeCombo.setSelectedItem(replyTypes[FIGHT_INDEX]); - } else if (Dialogue.Reply.REMOVE_PHRASE_ID.equals(reply.next_phrase_id)) { - replyTypeCombo.setSelectedItem(replyTypes[REMOVE_INDEX]); - } else if (Dialogue.Reply.SHOP_PHRASE_ID.equals(reply.next_phrase_id)) { - replyTypeCombo.setSelectedItem(replyTypes[SHOP_INDEX]); - } else { - replyTypeCombo.setSelectedItem(replyTypes[STD_REPLY_INDEX]); - } - replyTypeCombo.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - if (replyTypes[GO_NEXT_INDEX].equals(e.getItem())) { - if (!Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text) && reply.text != null) { - replyTextCache = reply.text; - } - reply.text = Dialogue.Reply.GO_NEXT_TEXT; - if (Dialogue.Reply.KEY_PHRASE_ID.contains(selectedReply.next_phrase_id)) { - reply.next_phrase_id = null; - reply.next_phrase = null; - } - } else { - if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text) || reply.text == null) { - reply.text = replyTextCache; - } - if (!replyTypes[STD_REPLY_INDEX].equals(e.getItem())) { - if (replyTypes[END_INDEX].equals(e.getItem())) { - reply.next_phrase_id = Dialogue.Reply.EXIT_PHRASE_ID; - reply.next_phrase = null; - } else if (replyTypes[FIGHT_INDEX].equals(e.getItem())) { - reply.next_phrase_id = Dialogue.Reply.FIGHT_PHRASE_ID; - reply.next_phrase = null; - } else if (replyTypes[REMOVE_INDEX].equals(e.getItem())) { - reply.next_phrase_id = Dialogue.Reply.REMOVE_PHRASE_ID; - reply.next_phrase = null; - } else if (replyTypes[SHOP_INDEX].equals(e.getItem())) { - reply.next_phrase_id = Dialogue.Reply.SHOP_PHRASE_ID; - reply.next_phrase = null; - } - } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(selectedReply.next_phrase_id)) { - reply.next_phrase_id = null; - reply.next_phrase = null; - } - } - listener.valueChanged(replyTypeCombo, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - comboPane.add(replyTypeCombo, BorderLayout.CENTER); - pane.add(comboPane, JideBoxLayout.FIX); - updateRepliesParamsEditorPane(repliesParamsPane, reply, listener); - pane.add(repliesParamsPane, JideBoxLayout.FIX); + private RewardsListModel rewardsListModel; + @SuppressWarnings("rawtypes") + private JList rewardsList; + @SuppressWarnings("rawtypes") + private JComboBox rewardTypeCombo; + private JPanel rewardsParamsPane; + private MyComboBox rewardMap; + private JTextField rewardObjId; + @SuppressWarnings("rawtypes") + private JComboBox rewardObjIdCombo; + private MyComboBox rewardObj; + private JComponent rewardValue; + private JRadioButton rewardConditionTimed; + private JRadioButton rewardConditionForever; + private JRadioButton rewardConditionClear; - String titleRequirements = "Requirements the player must fulfill to select this reply: "; - requirementsListModel = new ReplyRequirementsListModel(reply); - ReplyRequirementsCellRenderer cellRendererRequirements = new ReplyRequirementsCellRenderer(); - UiUtils.CollapsibleItemListCreation itemsPane = UiUtils.getCollapsibleItemList( - listener, - requirementsListModel, - () -> selectedRequirement = null, - (selectedItem) -> this.selectedRequirement = selectedItem, - () -> this.selectedRequirement, - (selectedItem)->{}, - (droppedItemsEditorPane) -> updateRequirementsEditorPane(droppedItemsEditorPane, this.selectedRequirement, listener), - target.writable, - Requirement::new, - cellRendererRequirements, - titleRequirements, - (x)-> x.required_obj, - false - ); - CollapsiblePanel requirementsPane = itemsPane.collapsiblePanel; - requirementsList = itemsPane.list; + private RepliesListModel repliesListModel; + @SuppressWarnings("rawtypes") + private JList repliesList; + private JPanel repliesParamsPane; + @SuppressWarnings("rawtypes") + private JComboBox replyTypeCombo; + private MyComboBox replyNextPhrase; + private String replyTextCache = null; + private JTextField replyText; - if (reply.requirements == null || reply.requirements.isEmpty()) { - requirementsPane.collapse(); - } + private ReplyRequirementsListModel requirementsListModel; + @SuppressWarnings("rawtypes") + private JList requirementsList; + @SuppressWarnings("rawtypes") + private JComboBox requirementTypeCombo; + private JPanel requirementParamsPane; + private MyComboBox requirementObj; + @SuppressWarnings("rawtypes") + private JComboBox requirementSkill; + private JComponent requirementObjId; + private JComponent requirementValue; + private BooleanBasedCheckBox requirementNegated; - pane.add(requirementsPane, JideBoxLayout.FIX); + private DialogueGraphView dialogueGraphView; - pane.revalidate(); - pane.repaint(); - } - - public void updateRepliesParamsEditorPane(final JPanel pane, final Dialogue.Reply reply, final FieldUpdateListener listener) { - boolean writable = ((Dialogue)target).writable; - pane.removeAll(); - if (replyNextPhrase != null) { - removeElementListener(replyNextPhrase); - } - if (requirementObj != null) { - removeElementListener(requirementObj); - } - - if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text)) { - replyText = null; - replyNextPhrase = addDialogueBox(pane, ((Dialogue)target).getProject(), "Next phrase: ", reply.next_phrase, writable, listener); - } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(reply.next_phrase_id)) { - replyText = addTranslatableTextField(pane, "Reply text: ", reply.text, writable, listener); - replyNextPhrase = null; - } else { - replyText = addTranslatableTextField(pane, "Reply text: ", reply.text, writable, listener); - replyNextPhrase = addDialogueBox(pane, ((Dialogue)target).getProject(), "Next phrase: ", reply.next_phrase, writable, listener); - } - + public DialogueEditor(Dialogue dialogue) { + super(dialogue, dialogue.getDesc(), dialogue.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + addEditorTab(graph_view_id, createDialogueGraphView(dialogue)); + } - pane.revalidate(); - pane.repaint(); - } + public JPanel createDialogueGraphView(final Dialogue dialogue) { + final JPanel pane = new JPanel(); + pane.setLayout(new BorderLayout()); - public void updateRequirementsEditorPane(final JPanel pane, final Requirement requirement, final FieldUpdateListener listener) { - boolean writable = ((Dialogue)target).writable; - pane.removeAll(); + dialogueGraphView = new DialogueGraphView(dialogue, null); + pane.add(dialogueGraphView, BorderLayout.CENTER); - if (requirementObj != null) { - removeElementListener(requirementObj); - } - - requirementTypeCombo = addEnumValueBox(pane, "Requirement type: ", Requirement.RequirementType.values(), requirement == null ? null : requirement.type, writable, listener); - requirementParamsPane = new JPanel(); - requirementParamsPane.setLayout(new JideBoxLayout(requirementParamsPane, JideBoxLayout.PAGE_AXIS)); - updateRequirementParamsEditorPane(requirementParamsPane, requirement, listener); - pane.add(requirementParamsPane, JideBoxLayout.FIX); - pane.revalidate(); - pane.repaint(); - } - - public void updateRequirementParamsEditorPane(final JPanel pane, final Requirement requirement, final FieldUpdateListener listener) { - boolean writable = ((Dialogue)target).writable; - Project project = ((Dialogue)target).getProject(); - pane.removeAll(); - if (requirementObj != null) { - removeElementListener(requirementObj); - } - - if (requirement != null && requirement.type != null) { - switch (requirement.type) { - case consumedBonemeals: - case spentGold: - requirementObj = null; - requirementObjId = null; - requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); - break; - case random: - requirementObj = null; - requirementObjId = addChanceField(pane, "Chance: ", requirement.required_obj_id, "50/100", writable, listener); - requirementValue = null; - break; - case hasActorCondition: - requirementObj = addActorConditionBox(pane, project, "Actor Condition: ", (ActorCondition) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = null; - break; - case inventoryKeep: - case inventoryRemove: - case usedItem: - case wear: - case wearRemove: - requirementObj = addItemBox(pane, project, "Item: ", (Item) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); - break; - case killedMonster: - requirementObj = addNPCBox(pane, project, "Monster: ", (NPC) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); - break; - case questLatestProgress: - case questProgress: - requirementObj = addQuestBox(pane, project, "Quest: ", (Quest) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = addQuestStageBox(pane, project, "Quest stage: ", requirement.required_value, writable, listener, (Quest) requirement.required_obj, requirementObj); - break; - case skillLevel: - Requirement.SkillID skillId = null; - try { - skillId = requirement.required_obj_id == null ? null : Requirement.SkillID.valueOf(requirement.required_obj_id); - } catch(IllegalArgumentException e) {} - requirementObj = null; - requirementSkill = addEnumValueBox(pane, "Skill ID:", Requirement.SkillID.values(), skillId, writable, listener); - requirementObjId = null;//addTextField(pane, "Skill ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Level: ", requirement.required_value, false, writable, listener); - break; - case timerElapsed: - requirementObj = null; - requirementObjId = addTextField(pane, "Timer ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Timer value: ", requirement.required_value, false, writable, listener); - break; - case factionScore: - requirementObj = null; - requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Minimum score: ", requirement.required_value, true, writable, listener); - break; - case factionScoreEquals: - requirementObj = null; - requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Exact value: ", requirement.required_value, true, writable, listener); - break; - case date: - requirementObj = null; - requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Minimum date value: ", requirement.required_value, true, writable, listener); - break; - case dateEquals: - requirementObj = null; - requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Exact date value: ", requirement.required_value, true, writable, listener); - break; - case time: - requirementObj = null; - requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Minimum time value: ", requirement.required_value, true, writable, listener); - break; - case timeEquals: - requirementObj = null; - requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Exact time value: ", requirement.required_value, true, writable, listener); - break; - } - requirementNegated = addBooleanBasedCheckBox(pane, "Negate this requirement.", requirement.negated, writable, listener); - } - pane.revalidate(); - pane.repaint(); - } - - - public static class RewardsListModel extends OrderedListenerListModel { - @Override - protected List getItems() { - return source.rewards; - } + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); + JButton reloadButton = new JButton("Refresh graph"); + buttonPane.add(reloadButton, JideBoxLayout.FIX); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, BorderLayout.NORTH); - @Override - protected void setItems(List items) { - source.rewards = items; - } - public RewardsListModel(Dialogue dialogue) { - super(dialogue); - } - } - - public static class RewardsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + reloadButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + pane.remove(dialogueGraphView); + dialogueGraphView = new DialogueGraphView(dialogue, null); + pane.add(dialogueGraphView, BorderLayout.CENTER); + pane.revalidate(); + pane.repaint(); + } + }); - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Dialogue.Reward reward = (Dialogue.Reward)value; - - decorateRewardJLabel(label, reward); - } - return c; - } - } - - public static void decorateRewardJLabel(JLabel label, Dialogue.Reward reward) { - if (reward.type != null) { - String rewardObjDesc = null; - if( reward.reward_obj != null) { - rewardObjDesc = reward.reward_obj.getDesc(); - } else if (reward.reward_obj_id != null) { - rewardObjDesc = reward.reward_obj_id; - } - switch (reward.type) { - case activateMapObjectGroup: - label.setText("Activate map object group "+rewardObjDesc+" on map "+reward.map_name); - label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); - break; - case actorCondition: - boolean rewardClear = reward.reward_value != null && reward.reward_value.intValue() == ActorCondition.MAGNITUDE_CLEAR; - if (rewardClear) { - label.setText("Clear actor condition "+rewardObjDesc); - } else { - boolean rewardForever = reward.reward_value != null && reward.reward_value.intValue() == ActorCondition.DURATION_FOREVER; - label.setText("Give actor condition "+rewardObjDesc+(rewardForever ? " forever" : " for "+reward.reward_value+" turns")); - } - if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); - break; - case actorConditionImmunity: - boolean rewardForever = reward.reward_value == null || reward.reward_value.intValue() == ActorCondition.DURATION_FOREVER; - label.setText("Give immunity to actor condition "+rewardObjDesc+(rewardForever ? " forever" : " for "+reward.reward_value+" turns")); - if (reward.reward_obj != null) label.setIcon(new OverlayIcon(reward.reward_obj.getIcon(), DefaultIcons.getImmunityIcon())); - break; - case alignmentChange: - label.setText("Change alignment for faction "+rewardObjDesc+" : "+reward.reward_value); - label.setIcon(new ImageIcon(DefaultIcons.getAlignmentIcon())); - break; - case alignmentSet: - label.setText("Set alignment for faction "+rewardObjDesc+" : "+reward.reward_value); - label.setIcon(new ImageIcon(DefaultIcons.getAlignmentIcon())); - break; - case createTimer: - label.setText("Create timer "+rewardObjDesc); - label.setIcon(new ImageIcon(DefaultIcons.getTimerIcon())); - break; - case deactivateMapObjectGroup: - label.setText("Deactivate map object group "+rewardObjDesc+" on map "+reward.map_name); - label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); - break; - case deactivateSpawnArea: - label.setText("Deactivate spawnarea area "+rewardObjDesc+" on map "+reward.map_name); - label.setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); - break; - case dropList: - label.setText("Give contents of droplist "+rewardObjDesc); - if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); - break; - case giveItem: - label.setText("Give "+reward.reward_value+" "+rewardObjDesc); - if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); - break; - case questProgress: - label.setText("Give quest progress "+rewardObjDesc+":"+reward.reward_value); - if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); - break; - case removeQuestProgress: - label.setText("Removes quest progress "+rewardObjDesc+":"+reward.reward_value); - if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); - break; - case removeSpawnArea: - label.setText("Remove all monsters in spawnarea area "+rewardObjDesc+" on map "+reward.map_name); - label.setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); - break; - case skillIncrease: - label.setText("Increase skill "+rewardObjDesc+" level"); - label.setIcon(new ImageIcon(DefaultIcons.getSkillIcon())); - break; - case spawnAll: - label.setText("Respawn all monsters in spawnarea area "+rewardObjDesc+" on map "+reward.map_name); - label.setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); - break; - case changeMapFilter: - label.setText("Change map filter to "+rewardObjDesc+" on map "+reward.map_name); - label.setIcon(new ImageIcon(DefaultIcons.getReplaceIcon())); - break; - case mapchange: - label.setText("Teleport to "+rewardObjDesc+" on map "+reward.map_name); - label.setIcon(new ImageIcon(DefaultIcons.getMapchangeIcon())); - break; - } - } else { - label.setText("New, undefined reward"); - } - } - - - public static class RepliesListModel extends OrderedListenerListModel { - @Override - protected List getItems() { - return source.replies; - } + return pane; + } - @Override - protected void setItems(List items) { - source.replies = items; - } + @SuppressWarnings({"unchecked", "rawtypes"}) + public void insertFormViewDataField(final JPanel pane) { - public RepliesListModel(Dialogue dialogue) { - super(dialogue); - } - } + final Dialogue dialogue = (Dialogue) target; + final FieldUpdateListener listener = new DialogueFieldUpdater(); - public static class RepliesCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + createButtonPane(pane, dialogue.getProject(), dialogue, Dialogue.class, dialogue.getImage(), null, listener); - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Dialogue.Reply reply = (Dialogue.Reply)value; - StringBuffer buf = new StringBuffer(); - if (reply.requirements != null) { - buf.append("[Reqs]"); - } - if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.EXIT_PHRASE_ID)) { - buf.append("[Ends dialogue] "); - buf.append((reply.text != null ? reply.text : "")); - label.setIcon(new ImageIcon(DefaultIcons.getNullifyIcon())); - } else if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.FIGHT_PHRASE_ID)) { - buf.append("[Starts fight] "); - buf.append((reply.text != null ? reply.text : "")); - label.setIcon(new ImageIcon(DefaultIcons.getCombatIcon())); - } else if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.REMOVE_PHRASE_ID)) { - buf.append("[NPC vanishes] "); - buf.append((reply.text != null ? reply.text : "")); - label.setIcon(new ImageIcon(DefaultIcons.getNPCCloseIcon())); - } else if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.SHOP_PHRASE_ID)) { - buf.append("[Start trading] "); - buf.append((reply.text != null ? reply.text : "")); - label.setIcon(new ImageIcon(DefaultIcons.getGoldIcon())); - } else if (reply.text != null && reply.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) { - buf.append("[NPC keeps talking] "); - buf.append(reply.next_phrase_id); - label.setIcon(new ImageIcon(DefaultIcons.getArrowRightIcon())); - } else if (reply.next_phrase_id != null) { - buf.append("[Dialogue goes on] "); - buf.append((reply.text != null ? reply.text : "")); - buf.append(" -> "); - buf.append(reply.next_phrase_id); - label.setIcon(new ImageIcon(DefaultIcons.getDialogueIcon())); - } else if (reply.next_phrase == null && reply.next_phrase_id == null && reply.requirements == null && reply.text == null) { - buf.append("New, undefined reply"); - } else { - buf.append("[Incomplete reply]"); - } - label.setText(buf.toString()); - } - return c; - } - } + idField = addTextField(pane, "Internal ID: ", dialogue.id, dialogue.writable, listener); + messageField = addTranslatableTextArea(pane, "Message: ", dialogue.message, dialogue.writable, listener); + switchToNpcBox = addNPCBox(pane, dialogue.getProject(), "Switch active NPC to: ", dialogue.switch_to_npc, dialogue.writable, listener); - public static class ReplyRequirementsListModel extends OrderedListenerListModel { - @Override - protected List getItems() { - return source.requirements; - } + RewardsCellRenderer cellRendererRewards = new RewardsCellRenderer(); + String titleRewards = "Reaching this phrase gives the following rewards: "; + rewardsListModel = new RewardsListModel(dialogue); - @Override - protected void setItems(List items) { - source.requirements = items; - } + CollapsiblePanel rewards = UiUtils.getCollapsibleItemList( + listener, + rewardsListModel, + () -> selectedReward = null, + (selectedItem) -> this.selectedReward = selectedItem, + () -> this.selectedReward, + (reward) -> { + }, + (editorPane) -> updateRewardsEditorPane(editorPane, this.selectedReward, listener), + dialogue.writable, + Dialogue.Reward::new, + cellRendererRewards, + titleRewards, + (x) -> null, + false + ).collapsiblePanel; + if (dialogue.rewards == null || dialogue.rewards.isEmpty()) { + rewards.collapse(); + } + pane.add(rewards, JideBoxLayout.FIX); - public ReplyRequirementsListModel(Dialogue.Reply reply) { - super(reply); - } - } - - public static class ReplyRequirementsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + RepliesCellRenderer cellRendererReplies = new RepliesCellRenderer(); + String titleReplies = "Replies / Next Phrase: "; + repliesListModel = new RepliesListModel(dialogue); + CollapsiblePanel replies = UiUtils.getCollapsibleItemList( + listener, + repliesListModel, + () -> selectedReply = null, + (selectedItem) -> this.selectedReply = selectedItem, + () -> this.selectedReply, + (selectedReply) -> { + if (selectedReply != null && !Dialogue.Reply.GO_NEXT_TEXT.equals(selectedReply.text)) { + replyTextCache = selectedReply.text; + } else { + replyTextCache = null; + } + }, + (editorPane) -> updateRepliesEditorPane(editorPane, this.selectedReply, listener), + dialogue.writable, + Dialogue.Reply::new, + cellRendererReplies, + titleReplies, + (x) -> null, + true + ).collapsiblePanel; + if (dialogue.replies == null || dialogue.replies.isEmpty()) { + replies.collapse(); + } + + pane.add(replies, JideBoxLayout.FIX); + + + } + + public void updateRewardsEditorPane(final JPanel pane, final Dialogue.Reward reward, final FieldUpdateListener listener) { + pane.removeAll(); + if (rewardMap != null) { + removeElementListener(rewardMap); + } + if (rewardObj != null) { + removeElementListener(rewardObj); + } + + if (reward != null) { + rewardTypeCombo = addEnumValueBox(pane, "Reward type: ", Dialogue.Reward.RewardType.values(), reward.type, ((Dialogue) target).writable, listener); + rewardsParamsPane = new JPanel(); + rewardsParamsPane.setLayout(new JideBoxLayout(rewardsParamsPane, JideBoxLayout.PAGE_AXIS)); + updateRewardsParamsEditorPane(rewardsParamsPane, reward, listener); + pane.add(rewardsParamsPane, JideBoxLayout.FIX); + } + pane.revalidate(); + pane.repaint(); + } + + public void updateRewardsParamsEditorPane(final JPanel pane, final Dialogue.Reward reward, final FieldUpdateListener listener) { + boolean writable = ((Dialogue) target).writable; + pane.removeAll(); + if (rewardMap != null) { + removeElementListener(rewardMap); + } + if (rewardObj != null) { + removeElementListener(rewardObj); + } + boolean immunity = false; + if (reward.type != null) { + switch (reward.type) { + case activateMapObjectGroup: + case deactivateMapObjectGroup: + rewardMap = addMapBox(pane, ((Dialogue) target).getProject(), "Map Name: ", reward.map, writable, listener); + rewardObjId = addTextField(pane, "Group ID: ", reward.reward_obj_id, writable, listener); + rewardObjIdCombo = null; + rewardObj = null; + rewardValue = null; + break; + case changeMapFilter: + rewardMap = addMapBox(pane, ((Dialogue) target).getProject(), "Map Name: ", reward.map, writable, listener); + rewardObjId = null; + rewardObjIdCombo = addEnumValueBox(pane, "Color Filter", TMXMap.ColorFilter.values(), reward.reward_obj_id != null ? TMXMap.ColorFilter.valueOf(reward.reward_obj_id) : TMXMap.ColorFilter.none, writable, listener); + rewardObj = null; + rewardValue = null; + break; + case mapchange: + rewardMap = addMapBox(pane, ((Dialogue) target).getProject(), "Map Name: ", reward.map, writable, listener); + rewardObjId = addTextField(pane, "Place: ", reward.reward_obj_id, writable, listener); + rewardObjIdCombo = null; + rewardObj = null; + rewardValue = null; + break; + case deactivateSpawnArea: + case removeSpawnArea: + case spawnAll: + rewardMap = addMapBox(pane, ((Dialogue) target).getProject(), "Map Name: ", reward.map, writable, listener); + rewardObjId = addTextField(pane, "Area ID: ", reward.reward_obj_id, writable, listener); + rewardObjIdCombo = null; + rewardObj = null; + rewardValue = null; + break; + case actorConditionImmunity: + immunity = true; + case actorCondition: + + rewardMap = null; + rewardObjId = null; + rewardObjIdCombo = null; + rewardObj = addActorConditionBox(pane, ((Dialogue) target).getProject(), "Actor Condition: ", (ActorCondition) reward.reward_obj, writable, listener); + rewardConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(rewardConditionTimed, JideBoxLayout.FIX); + rewardValue = addIntegerField(pane, "Duration: ", reward.reward_value, 1, false, writable, listener); + rewardConditionForever = new JRadioButton("Forever"); + pane.add(rewardConditionForever, JideBoxLayout.FIX); + if (!immunity) { + rewardConditionClear = new JRadioButton("Clear actor condition"); + pane.add(rewardConditionClear, JideBoxLayout.FIX); + } + + ButtonGroup radioGroup = new ButtonGroup(); + radioGroup.add(rewardConditionTimed); + radioGroup.add(rewardConditionForever); + if (!immunity) radioGroup.add(rewardConditionClear); + + if (immunity) { + rewardConditionTimed.setSelected(reward.reward_value == null || (reward.reward_value != ActorCondition.DURATION_FOREVER && reward.reward_value != ActorCondition.MAGNITUDE_CLEAR)); + rewardConditionForever.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.DURATION_FOREVER); + rewardConditionClear.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.MAGNITUDE_CLEAR); + } else { + rewardConditionTimed.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.DURATION_FOREVER); + rewardConditionForever.setSelected(reward.reward_value == null || reward.reward_value == ActorCondition.DURATION_FOREVER); + } + rewardValue.setEnabled(rewardConditionTimed.isSelected()); + + rewardConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(rewardConditionTimed, new Boolean(rewardConditionTimed.isSelected())); + } + }); + rewardConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(rewardConditionForever, new Boolean(rewardConditionForever.isSelected())); + } + }); + if (!immunity) { + rewardConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(rewardConditionClear, new Boolean(rewardConditionClear.isSelected())); + } + }); + } + break; + case alignmentChange: + case alignmentSet: + rewardMap = null; + rewardObjId = addTextField(pane, "Faction: ", reward.reward_obj_id, writable, listener); + rewardObjIdCombo = null; + rewardObj = null; + rewardValue = addIntegerField(pane, "Value: ", reward.reward_value, true, writable, listener); + break; + case createTimer: + rewardMap = null; + rewardObjId = addTextField(pane, "Timer ID: ", reward.reward_obj_id, writable, listener); + rewardObjIdCombo = null; + rewardObj = null; + rewardValue = null; + break; + case dropList: + rewardMap = null; + rewardObjId = null; + rewardObjIdCombo = null; + rewardObj = addDroplistBox(pane, ((Dialogue) target).getProject(), "Droplist: ", (Droplist) reward.reward_obj, writable, listener); + rewardValue = null; + break; + case giveItem: + rewardMap = null; + rewardObjId = null; + rewardObj = addItemBox(pane, ((Dialogue) target).getProject(), "Item: ", (Item) reward.reward_obj, writable, listener); + rewardValue = addIntegerField(pane, "Quantity: ", reward.reward_value, true, writable, listener); + break; + case removeQuestProgress: + case questProgress: + rewardMap = null; + rewardObjId = null; + rewardObjIdCombo = null; + rewardObj = addQuestBox(pane, ((Dialogue) target).getProject(), "Quest: ", (Quest) reward.reward_obj, writable, listener); + rewardValue = addQuestStageBox(pane, ((Dialogue) target).getProject(), "Quest stage: ", reward.reward_value, writable, listener, (Quest) reward.reward_obj, rewardObj); + break; + case skillIncrease: + Requirement.SkillID skillId = null; + try { + skillId = reward.reward_obj_id == null ? null : Requirement.SkillID.valueOf(reward.reward_obj_id); + } catch (IllegalArgumentException e) { + } + rewardMap = null; + rewardObjId = null;// addTextField(pane, "Skill ID: ", reward.reward_obj_id, writable, listener); + rewardObjIdCombo = addEnumValueBox(pane, "Skill ID: ", Requirement.SkillID.values(), skillId, writable, listener); + rewardObj = null; + rewardValue = null; + break; + + } + } + pane.revalidate(); + pane.repaint(); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public void updateRepliesEditorPane(final JPanel pane, final Dialogue.Reply reply, final FieldUpdateListener listener) { + pane.removeAll(); + if (replyNextPhrase != null) { + removeElementListener(replyNextPhrase); + } + if (requirementObj != null) { + removeElementListener(requirementObj); + } + if (reply == null) return; + + JPanel comboPane = new JPanel(); + comboPane.setLayout(new BorderLayout()); + JLabel comboLabel = new JLabel("Reply type: "); + comboPane.add(comboLabel, BorderLayout.WEST); + + replyTypeCombo = new JComboBox(replyTypes); + replyTypeCombo.setEnabled(((Dialogue) target).writable); + repliesParamsPane = new JPanel(); + repliesParamsPane.setLayout(new JideBoxLayout(repliesParamsPane, JideBoxLayout.PAGE_AXIS)); + if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text)) { + replyTypeCombo.setSelectedItem(replyTypes[GO_NEXT_INDEX]); + } else if (Dialogue.Reply.EXIT_PHRASE_ID.equals(reply.next_phrase_id)) { + replyTypeCombo.setSelectedItem(replyTypes[END_INDEX]); + } else if (Dialogue.Reply.FIGHT_PHRASE_ID.equals(reply.next_phrase_id)) { + replyTypeCombo.setSelectedItem(replyTypes[FIGHT_INDEX]); + } else if (Dialogue.Reply.REMOVE_PHRASE_ID.equals(reply.next_phrase_id)) { + replyTypeCombo.setSelectedItem(replyTypes[REMOVE_INDEX]); + } else if (Dialogue.Reply.SHOP_PHRASE_ID.equals(reply.next_phrase_id)) { + replyTypeCombo.setSelectedItem(replyTypes[SHOP_INDEX]); + } else { + replyTypeCombo.setSelectedItem(replyTypes[STD_REPLY_INDEX]); + } + replyTypeCombo.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + if (replyTypes[GO_NEXT_INDEX].equals(e.getItem())) { + if (!Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text) && reply.text != null) { + replyTextCache = reply.text; + } + reply.text = Dialogue.Reply.GO_NEXT_TEXT; + if (Dialogue.Reply.KEY_PHRASE_ID.contains(selectedReply.next_phrase_id)) { + reply.next_phrase_id = null; + reply.next_phrase = null; + } + } else { + if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text) || reply.text == null) { + reply.text = replyTextCache; + } + if (!replyTypes[STD_REPLY_INDEX].equals(e.getItem())) { + if (replyTypes[END_INDEX].equals(e.getItem())) { + reply.next_phrase_id = Dialogue.Reply.EXIT_PHRASE_ID; + reply.next_phrase = null; + } else if (replyTypes[FIGHT_INDEX].equals(e.getItem())) { + reply.next_phrase_id = Dialogue.Reply.FIGHT_PHRASE_ID; + reply.next_phrase = null; + } else if (replyTypes[REMOVE_INDEX].equals(e.getItem())) { + reply.next_phrase_id = Dialogue.Reply.REMOVE_PHRASE_ID; + reply.next_phrase = null; + } else if (replyTypes[SHOP_INDEX].equals(e.getItem())) { + reply.next_phrase_id = Dialogue.Reply.SHOP_PHRASE_ID; + reply.next_phrase = null; + } + } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(selectedReply.next_phrase_id)) { + reply.next_phrase_id = null; + reply.next_phrase = null; + } + } + listener.valueChanged(replyTypeCombo, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + comboPane.add(replyTypeCombo, BorderLayout.CENTER); + pane.add(comboPane, JideBoxLayout.FIX); + updateRepliesParamsEditorPane(repliesParamsPane, reply, listener); + pane.add(repliesParamsPane, JideBoxLayout.FIX); + + String titleRequirements = "Requirements the player must fulfill to select this reply: "; + requirementsListModel = new ReplyRequirementsListModel(reply); + ReplyRequirementsCellRenderer cellRendererRequirements = new ReplyRequirementsCellRenderer(); + UiUtils.CollapsibleItemListCreation itemsPane = UiUtils.getCollapsibleItemList( + listener, + requirementsListModel, + () -> selectedRequirement = null, + (selectedItem) -> this.selectedRequirement = selectedItem, + () -> this.selectedRequirement, + (selectedItem) -> { + }, + (droppedItemsEditorPane) -> updateRequirementsEditorPane(droppedItemsEditorPane, this.selectedRequirement, listener), + target.writable, + Requirement::new, + cellRendererRequirements, + titleRequirements, + (x) -> x.required_obj, + false + ); + CollapsiblePanel requirementsPane = itemsPane.collapsiblePanel; + requirementsList = itemsPane.list; + + if (reply.requirements == null || reply.requirements.isEmpty()) { + requirementsPane.collapse(); + } + + pane.add(requirementsPane, JideBoxLayout.FIX); + + pane.revalidate(); + pane.repaint(); + } + + public void updateRepliesParamsEditorPane(final JPanel pane, final Dialogue.Reply reply, final FieldUpdateListener listener) { + boolean writable = ((Dialogue) target).writable; + pane.removeAll(); + + if (replyNextPhrase != null) { + removeElementListener(replyNextPhrase); + } + if (requirementObj != null) { + removeElementListener(requirementObj); + } + + if (Dialogue.Reply.GO_NEXT_TEXT.equals(reply.text)) { + replyText = null; + replyNextPhrase = addDialogueBox(pane, ((Dialogue) target).getProject(), "Next phrase: ", reply.next_phrase, writable, listener); + } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(reply.next_phrase_id)) { + replyText = addTranslatableTextField(pane, "Reply text: ", reply.text, writable, listener); + replyNextPhrase = null; + } else { + replyText = addTranslatableTextField(pane, "Reply text: ", reply.text, writable, listener); + replyNextPhrase = addDialogueBox(pane, ((Dialogue) target).getProject(), "Next phrase: ", reply.next_phrase, writable, listener); + } + + + pane.revalidate(); + pane.repaint(); + } + + public void updateRequirementsEditorPane(final JPanel pane, final Requirement requirement, final FieldUpdateListener listener) { + boolean writable = ((Dialogue) target).writable; + pane.removeAll(); + + if (requirementObj != null) { + removeElementListener(requirementObj); + } + + requirementTypeCombo = addEnumValueBox(pane, "Requirement type: ", Requirement.RequirementType.values(), requirement == null ? null : requirement.type, writable, listener); + requirementParamsPane = new JPanel(); + requirementParamsPane.setLayout(new JideBoxLayout(requirementParamsPane, JideBoxLayout.PAGE_AXIS)); + updateRequirementParamsEditorPane(requirementParamsPane, requirement, listener); + pane.add(requirementParamsPane, JideBoxLayout.FIX); + pane.revalidate(); + pane.repaint(); + } + + public void updateRequirementParamsEditorPane(final JPanel pane, final Requirement requirement, final FieldUpdateListener listener) { + boolean writable = ((Dialogue) target).writable; + Project project = ((Dialogue) target).getProject(); + pane.removeAll(); + if (requirementObj != null) { + removeElementListener(requirementObj); + } + + if (requirement != null && requirement.type != null) { + switch (requirement.type) { + case consumedBonemeals: + case spentGold: + requirementObj = null; + requirementObjId = null; + requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); + break; + case random: + requirementObj = null; + requirementObjId = addChanceField(pane, "Chance: ", requirement.required_obj_id, "50/100", writable, listener); + requirementValue = null; + break; + case hasActorCondition: + requirementObj = addActorConditionBox(pane, project, "Actor Condition: ", (ActorCondition) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = null; + break; + case inventoryKeep: + case inventoryRemove: + case usedItem: + case wear: + case wearRemove: + requirementObj = addItemBox(pane, project, "Item: ", (Item) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); + break; + case killedMonster: + requirementObj = addNPCBox(pane, project, "Monster: ", (NPC) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); + break; + case questLatestProgress: + case questProgress: + requirementObj = addQuestBox(pane, project, "Quest: ", (Quest) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = addQuestStageBox(pane, project, "Quest stage: ", requirement.required_value, writable, listener, (Quest) requirement.required_obj, requirementObj); + break; + case skillLevel: + Requirement.SkillID skillId = null; + try { + skillId = requirement.required_obj_id == null ? null : Requirement.SkillID.valueOf(requirement.required_obj_id); + } catch (IllegalArgumentException e) { + } + requirementObj = null; + requirementSkill = addEnumValueBox(pane, "Skill ID:", Requirement.SkillID.values(), skillId, writable, listener); + requirementObjId = null;//addTextField(pane, "Skill ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Level: ", requirement.required_value, false, writable, listener); + break; + case timerElapsed: + requirementObj = null; + requirementObjId = addTextField(pane, "Timer ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Timer value: ", requirement.required_value, false, writable, listener); + break; + case factionScore: + requirementObj = null; + requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Minimum score: ", requirement.required_value, true, writable, listener); + break; + case factionScoreEquals: + requirementObj = null; + requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Exact value: ", requirement.required_value, true, writable, listener); + break; + case date: + requirementObj = null; + requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Minimum date value: ", requirement.required_value, true, writable, listener); + break; + case dateEquals: + requirementObj = null; + requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Exact date value: ", requirement.required_value, true, writable, listener); + break; + case time: + requirementObj = null; + requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Minimum time value: ", requirement.required_value, true, writable, listener); + break; + case timeEquals: + requirementObj = null; + requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Exact time value: ", requirement.required_value, true, writable, listener); + break; + } + requirementNegated = addBooleanBasedCheckBox(pane, "Negate this requirement.", requirement.negated, writable, listener); + } + pane.revalidate(); + pane.repaint(); + } + + + public static class RewardsListModel extends OrderedListenerListModel { + @Override + protected List getItems() { + return source.rewards; + } + + @Override + protected void setItems(List items) { + source.rewards = items; + } + + public RewardsListModel(Dialogue dialogue) { + super(dialogue); + } + } + + public static class RewardsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Dialogue.Reward reward = (Dialogue.Reward) value; + + decorateRewardJLabel(label, reward); + } + return c; + } + } + + public static void decorateRewardJLabel(JLabel label, Dialogue.Reward reward) { + if (reward.type != null) { + String rewardObjDesc = null; + if (reward.reward_obj != null) { + rewardObjDesc = reward.reward_obj.getDesc(); + } else if (reward.reward_obj_id != null) { + rewardObjDesc = reward.reward_obj_id; + } + switch (reward.type) { + case activateMapObjectGroup: + label.setText("Activate map object group " + rewardObjDesc + " on map " + reward.map_name); + label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); + break; + case actorCondition: + boolean rewardClear = reward.reward_value != null && reward.reward_value.intValue() == ActorCondition.MAGNITUDE_CLEAR; + if (rewardClear) { + label.setText("Clear actor condition " + rewardObjDesc); + } else { + boolean rewardForever = reward.reward_value != null && reward.reward_value.intValue() == ActorCondition.DURATION_FOREVER; + label.setText("Give actor condition " + rewardObjDesc + (rewardForever ? " forever" : " for " + reward.reward_value + " turns")); + } + if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); + break; + case actorConditionImmunity: + boolean rewardForever = reward.reward_value == null || reward.reward_value.intValue() == ActorCondition.DURATION_FOREVER; + label.setText("Give immunity to actor condition " + rewardObjDesc + (rewardForever ? " forever" : " for " + reward.reward_value + " turns")); + if (reward.reward_obj != null) + label.setIcon(new OverlayIcon(reward.reward_obj.getIcon(), DefaultIcons.getImmunityIcon())); + break; + case alignmentChange: + label.setText("Change alignment for faction " + rewardObjDesc + " : " + reward.reward_value); + label.setIcon(new ImageIcon(DefaultIcons.getAlignmentIcon())); + break; + case alignmentSet: + label.setText("Set alignment for faction " + rewardObjDesc + " : " + reward.reward_value); + label.setIcon(new ImageIcon(DefaultIcons.getAlignmentIcon())); + break; + case createTimer: + label.setText("Create timer " + rewardObjDesc); + label.setIcon(new ImageIcon(DefaultIcons.getTimerIcon())); + break; + case deactivateMapObjectGroup: + label.setText("Deactivate map object group " + rewardObjDesc + " on map " + reward.map_name); + label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); + break; + case deactivateSpawnArea: + label.setText("Deactivate spawnarea area " + rewardObjDesc + " on map " + reward.map_name); + label.setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); + break; + case dropList: + label.setText("Give contents of droplist " + rewardObjDesc); + if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); + break; + case giveItem: + label.setText("Give " + reward.reward_value + " " + rewardObjDesc); + if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); + break; + case questProgress: + label.setText("Give quest progress " + rewardObjDesc + ":" + reward.reward_value); + if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); + break; + case removeQuestProgress: + label.setText("Removes quest progress " + rewardObjDesc + ":" + reward.reward_value); + if (reward.reward_obj != null) label.setIcon(new ImageIcon(reward.reward_obj.getIcon())); + break; + case removeSpawnArea: + label.setText("Remove all monsters in spawnarea area " + rewardObjDesc + " on map " + reward.map_name); + label.setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); + break; + case skillIncrease: + label.setText("Increase skill " + rewardObjDesc + " level"); + label.setIcon(new ImageIcon(DefaultIcons.getSkillIcon())); + break; + case spawnAll: + label.setText("Respawn all monsters in spawnarea area " + rewardObjDesc + " on map " + reward.map_name); + label.setIcon(new ImageIcon(DefaultIcons.getNPCIcon())); + break; + case changeMapFilter: + label.setText("Change map filter to " + rewardObjDesc + " on map " + reward.map_name); + label.setIcon(new ImageIcon(DefaultIcons.getReplaceIcon())); + break; + case mapchange: + label.setText("Teleport to " + rewardObjDesc + " on map " + reward.map_name); + label.setIcon(new ImageIcon(DefaultIcons.getMapchangeIcon())); + break; + } + } else { + label.setText("New, undefined reward"); + } + } + + + public static class RepliesListModel extends OrderedListenerListModel { + @Override + protected List getItems() { + return source.replies; + } + + @Override + protected void setItems(List items) { + source.replies = items; + } + + public RepliesListModel(Dialogue dialogue) { + super(dialogue); + } + } + + public static class RepliesCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Dialogue.Reply reply = (Dialogue.Reply) value; + StringBuffer buf = new StringBuffer(); + if (reply.requirements != null) { + buf.append("[Reqs]"); + } + if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.EXIT_PHRASE_ID)) { + buf.append("[Ends dialogue] "); + buf.append((reply.text != null ? reply.text : "")); + label.setIcon(new ImageIcon(DefaultIcons.getNullifyIcon())); + } else if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.FIGHT_PHRASE_ID)) { + buf.append("[Starts fight] "); + buf.append((reply.text != null ? reply.text : "")); + label.setIcon(new ImageIcon(DefaultIcons.getCombatIcon())); + } else if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.REMOVE_PHRASE_ID)) { + buf.append("[NPC vanishes] "); + buf.append((reply.text != null ? reply.text : "")); + label.setIcon(new ImageIcon(DefaultIcons.getNPCCloseIcon())); + } else if (reply.next_phrase_id != null && reply.next_phrase_id.equals(Dialogue.Reply.SHOP_PHRASE_ID)) { + buf.append("[Start trading] "); + buf.append((reply.text != null ? reply.text : "")); + label.setIcon(new ImageIcon(DefaultIcons.getGoldIcon())); + } else if (reply.text != null && reply.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) { + buf.append("[NPC keeps talking] "); + buf.append(reply.next_phrase_id); + label.setIcon(new ImageIcon(DefaultIcons.getArrowRightIcon())); + } else if (reply.next_phrase_id != null) { + buf.append("[Dialogue goes on] "); + buf.append((reply.text != null ? reply.text : "")); + buf.append(" -> "); + buf.append(reply.next_phrase_id); + label.setIcon(new ImageIcon(DefaultIcons.getDialogueIcon())); + } else if (reply.next_phrase == null && reply.next_phrase_id == null && reply.requirements == null && reply.text == null) { + buf.append("New, undefined reply"); + } else { + buf.append("[Incomplete reply]"); + } + label.setText(buf.toString()); + } + return c; + } + } + + public static class ReplyRequirementsListModel extends OrderedListenerListModel { + @Override + protected List getItems() { + return source.requirements; + } + + @Override + protected void setItems(List items) { + source.requirements = items; + } + + public ReplyRequirementsListModel(Dialogue.Reply reply) { + super(reply); + } + } + + public static class ReplyRequirementsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + decorateRequirementJLabel((JLabel) c, (Requirement) value); + } + return c; + } + } + + public static void decorateRequirementJLabel(JLabel label, Requirement req) { + label.setText(req.getDesc()); + if (req.required_obj != null) { + if (req.required_obj.getIcon() != null) { + label.setIcon(new ImageIcon(req.required_obj.getIcon())); + } + } else if (req.type == Requirement.RequirementType.skillLevel) { + label.setIcon(new ImageIcon(DefaultIcons.getSkillIcon())); + } else if (req.type == Requirement.RequirementType.spentGold) { + label.setIcon(new ImageIcon(DefaultIcons.getGoldIcon())); + } else if (req.type == Requirement.RequirementType.consumedBonemeals) { + label.setIcon(new ImageIcon(DefaultIcons.getBonemealIcon())); + } else if (req.type == Requirement.RequirementType.timerElapsed) { + label.setIcon(new ImageIcon(DefaultIcons.getTimerIcon())); + } else if (req.type == Requirement.RequirementType.factionScore || req.type == Requirement.RequirementType.factionScoreEquals) { + label.setIcon(new ImageIcon(DefaultIcons.getAlignmentIcon())); + } else if (req.type == Requirement.RequirementType.date || req.type == Requirement.RequirementType.dateEquals || + req.type == Requirement.RequirementType.time || req.type == Requirement.RequirementType.timeEquals) { + label.setIcon(new ImageIcon(DefaultIcons.getDateIcon())); + } + if (req.type == null) { + label.setText("New, undefined requirement."); + } + } + + public class DialogueFieldUpdater implements FieldUpdateListener { + @Override + public void valueChanged(JComponent source, Object value) { + Dialogue dialogue = (Dialogue) target; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + dialogue.id = (String) value; + DialogueEditor.this.name = dialogue.getDesc(); + dialogue.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(DialogueEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == messageField) { + dialogue.message = (String) value; + } else if (source == switchToNpcBox) { + if (dialogue.switch_to_npc != null) { + dialogue.switch_to_npc.removeBacklink(dialogue); + } + dialogue.switch_to_npc = (NPC) value; + if (dialogue.switch_to_npc != null) { + dialogue.switch_to_npc_id = dialogue.switch_to_npc.id; + dialogue.switch_to_npc.addBacklink(dialogue); + } else { + dialogue.switch_to_npc_id = null; + } + } else if (source == rewardTypeCombo) { + if (selectedReward.type != value) { + selectedReward.type = (Dialogue.Reward.RewardType) value; + if (selectedReward.map != null) { + selectedReward.map.removeBacklink(dialogue); + } + selectedReward.map = null; + selectedReward.map_name = null; + selectedReward.reward_obj = null; + selectedReward.reward_obj_id = null; + selectedReward.reward_value = null; + rewardsListModel.itemChanged(selectedReward); + updateRewardsParamsEditorPane(rewardsParamsPane, selectedReward, this); + } + } else if (source == rewardMap) { + if (selectedReward.map != null) { + selectedReward.map.removeBacklink(dialogue); + } + selectedReward.map = (TMXMap) value; + if (selectedReward.map != null) { + selectedReward.map_name = selectedReward.map.id; + selectedReward.map.addBacklink(dialogue); + } else { + selectedReward.map_name = null; + } + rewardsListModel.itemChanged(selectedReward); + } else if (source == rewardObjId) { + selectedReward.reward_obj_id = rewardObjId.getText(); + rewardsListModel.itemChanged(selectedReward); + } else if (source == rewardObjIdCombo) { + selectedReward.reward_obj_id = rewardObjIdCombo.getSelectedItem().toString(); + rewardsListModel.itemChanged(selectedReward); + } else if (source == rewardObj) { + if (selectedReward.reward_obj != null) { + selectedReward.reward_obj.removeBacklink(dialogue); + } + selectedReward.reward_obj = (GameDataElement) value; + if (selectedReward.reward_obj != null) { + selectedReward.reward_obj_id = selectedReward.reward_obj.id; + selectedReward.reward_obj.addBacklink(dialogue); + } else { + selectedReward.reward_obj_id = null; + } + rewardsListModel.itemChanged(selectedReward); + } else if (source == rewardValue) { + //Backlink removal to quest stages when selecting another quest are handled in the addQuestStageBox() method. Too complex too handle here + Quest quest = null; + QuestStage stage; + if (rewardValue instanceof JComboBox) { + quest = ((Quest) selectedReward.reward_obj); + if (quest != null && selectedReward.reward_value != null) { + stage = quest.getStage(selectedReward.reward_value); + if (stage != null) stage.removeBacklink(dialogue); + } + } + selectedReward.reward_value = (Integer) value; + if (quest != null) { + stage = quest.getStage(selectedReward.reward_value); + if (stage != null) stage.addBacklink(dialogue); + } + rewardsListModel.itemChanged(selectedReward); + } else if (source == rewardConditionClear) { + selectedReward.reward_value = ActorCondition.MAGNITUDE_CLEAR; + rewardValue.setEnabled(false); + rewardsListModel.itemChanged(selectedReward); + } else if (source == rewardConditionForever) { + selectedReward.reward_value = ActorCondition.DURATION_FOREVER; + rewardValue.setEnabled(false); + rewardsListModel.itemChanged(selectedReward); + } else if (source == rewardConditionTimed) { + selectedReward.reward_value = (Integer) ((JSpinner) rewardValue).getValue(); + rewardValue.setEnabled(true); + rewardsListModel.itemChanged(selectedReward); + } else if (source == replyTypeCombo) { + updateRepliesParamsEditorPane(repliesParamsPane, selectedReply, this); + repliesListModel.itemChanged(selectedReply); + } else if (source == replyText) { + selectedReply.text = (String) value; + repliesListModel.itemChanged(selectedReply); + } else if (source == replyNextPhrase) { + if (selectedReply.next_phrase != null) { + selectedReply.next_phrase.removeBacklink(dialogue); + } + selectedReply.next_phrase = (Dialogue) value; + if (selectedReply.next_phrase != null) { + selectedReply.next_phrase_id = selectedReply.next_phrase.id; + selectedReply.next_phrase.addBacklink(dialogue); + } else { + selectedReply.next_phrase_id = null; + } + repliesListModel.itemChanged(selectedReply); + } else if (source == requirementTypeCombo) { + selectedRequirement.changeType((Requirement.RequirementType) requirementTypeCombo.getSelectedItem()); + updateRequirementParamsEditorPane(requirementParamsPane, selectedRequirement, this); + requirementsListModel.itemChanged(selectedRequirement); + } else if (source == requirementObj) { + if (selectedRequirement.required_obj != null) { + selectedRequirement.required_obj.removeBacklink(dialogue); + } + selectedRequirement.required_obj = (GameDataElement) value; + if (selectedRequirement.required_obj != null) { + selectedRequirement.required_obj_id = selectedRequirement.required_obj.id; + selectedRequirement.required_obj.addBacklink(dialogue); + } else { + selectedRequirement.required_obj_id = null; + } + requirementsListModel.itemChanged(selectedRequirement); + } else if (source == requirementSkill) { + if (selectedRequirement.required_obj != null) { + selectedRequirement.required_obj.removeBacklink(dialogue); + selectedRequirement.required_obj = null; + } + if (selectedRequirement.type == Requirement.RequirementType.skillLevel) { + selectedRequirement.required_obj_id = value == null ? null : value.toString(); + } + requirementsListModel.itemChanged(selectedRequirement); + } else if (source == requirementObjId) { + selectedRequirement.required_obj_id = (String) value; + selectedRequirement.required_obj = null; + requirementsListModel.itemChanged(selectedRequirement); + } else if (source == requirementValue) { + //Backlink removal to quest stages when selecting another quest are handled in the addQuestStageBox() method. Too complex too handle here + Quest quest = null; + QuestStage stage; + if (requirementValue instanceof JComboBox) { + quest = ((Quest) selectedRequirement.required_obj); + if (quest != null && selectedRequirement.required_value != null) { + stage = quest.getStage(selectedRequirement.required_value); + if (stage != null) stage.removeBacklink(dialogue); + } + } + selectedRequirement.required_value = (Integer) value; + if (quest != null) { + stage = quest.getStage(selectedRequirement.required_value); + if (stage != null) stage.addBacklink(dialogue); + } + requirementsListModel.itemChanged(selectedRequirement); + } else if (source == requirementNegated) { + selectedRequirement.negated = (Boolean) value; + } + + if (dialogue.state != GameDataElement.State.modified) { + dialogue.state = GameDataElement.State.modified; + DialogueEditor.this.name = dialogue.getDesc(); + dialogue.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(DialogueEditor.this); + } + updateJsonViewText(dialogue.toJsonString()); + } + } - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - decorateRequirementJLabel((JLabel)c, (Requirement)value); - } - return c; - } - } - - public static void decorateRequirementJLabel(JLabel label, Requirement req) { - label.setText(req.getDesc()); - if (req.required_obj != null) { - if (req.required_obj.getIcon() != null) { - label.setIcon(new ImageIcon(req.required_obj.getIcon())); - } - } else if (req.type == Requirement.RequirementType.skillLevel) { - label.setIcon(new ImageIcon(DefaultIcons.getSkillIcon())); - } else if (req.type == Requirement.RequirementType.spentGold) { - label.setIcon(new ImageIcon(DefaultIcons.getGoldIcon())); - } else if (req.type == Requirement.RequirementType.consumedBonemeals) { - label.setIcon(new ImageIcon(DefaultIcons.getBonemealIcon())); - } else if (req.type == Requirement.RequirementType.timerElapsed) { - label.setIcon(new ImageIcon(DefaultIcons.getTimerIcon())); - } else if (req.type == Requirement.RequirementType.factionScore || req.type == Requirement.RequirementType.factionScoreEquals) { - label.setIcon(new ImageIcon(DefaultIcons.getAlignmentIcon())); - } else if (req.type == Requirement.RequirementType.date || req.type == Requirement.RequirementType.dateEquals || - req.type == Requirement.RequirementType.time || req.type == Requirement.RequirementType.timeEquals) { - label.setIcon(new ImageIcon(DefaultIcons.getDateIcon())); - } - if (req.type == null) { - label.setText("New, undefined requirement."); - } - } - - public class DialogueFieldUpdater implements FieldUpdateListener { - @Override - public void valueChanged(JComponent source, Object value) { - Dialogue dialogue = (Dialogue) target; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - dialogue.id = (String) value; - DialogueEditor.this.name = dialogue.getDesc(); - dialogue.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(DialogueEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == messageField) { - dialogue.message = (String) value; - } else if (source == switchToNpcBox) { - if (dialogue.switch_to_npc != null) { - dialogue.switch_to_npc.removeBacklink(dialogue); - } - dialogue.switch_to_npc = (NPC) value; - if (dialogue.switch_to_npc != null) { - dialogue.switch_to_npc_id = dialogue.switch_to_npc.id; - dialogue.switch_to_npc.addBacklink(dialogue); - } else { - dialogue.switch_to_npc_id = null; - } - } else if (source == rewardTypeCombo) { - if (selectedReward.type != value) { - selectedReward.type = (Dialogue.Reward.RewardType) value; - if (selectedReward.map != null) { - selectedReward.map.removeBacklink(dialogue); - } - selectedReward.map = null; - selectedReward.map_name = null; - selectedReward.reward_obj = null; - selectedReward.reward_obj_id = null; - selectedReward.reward_value = null; - rewardsListModel.itemChanged(selectedReward); - updateRewardsParamsEditorPane(rewardsParamsPane, selectedReward, this); - } - } else if (source == rewardMap) { - if (selectedReward.map != null) { - selectedReward.map.removeBacklink(dialogue); - } - selectedReward.map = (TMXMap) value; - if (selectedReward.map != null) { - selectedReward.map_name = selectedReward.map.id; - selectedReward.map.addBacklink(dialogue); - } else { - selectedReward.map_name = null; - } - rewardsListModel.itemChanged(selectedReward); - } else if (source == rewardObjId) { - selectedReward.reward_obj_id = rewardObjId.getText(); - rewardsListModel.itemChanged(selectedReward); - } else if (source == rewardObjIdCombo) { - selectedReward.reward_obj_id = rewardObjIdCombo.getSelectedItem().toString(); - rewardsListModel.itemChanged(selectedReward); - } else if (source == rewardObj) { - if (selectedReward.reward_obj != null) { - selectedReward.reward_obj.removeBacklink(dialogue); - } - selectedReward.reward_obj = (GameDataElement) value; - if (selectedReward.reward_obj != null) { - selectedReward.reward_obj_id = selectedReward.reward_obj.id; - selectedReward.reward_obj.addBacklink(dialogue); - } else { - selectedReward.reward_obj_id = null; - } - rewardsListModel.itemChanged(selectedReward); - } else if (source == rewardValue) { - //Backlink removal to quest stages when selecting another quest are handled in the addQuestStageBox() method. Too complex too handle here - Quest quest = null; - QuestStage stage; - if (rewardValue instanceof JComboBox) { - quest = ((Quest)selectedReward.reward_obj); - if (quest != null && selectedReward.reward_value != null) { - stage = quest.getStage(selectedReward.reward_value); - if (stage != null) stage.removeBacklink(dialogue); - } - } - selectedReward.reward_value = (Integer) value; - if (quest != null) { - stage = quest.getStage(selectedReward.reward_value); - if (stage != null) stage.addBacklink(dialogue); - } - rewardsListModel.itemChanged(selectedReward); - } else if (source == rewardConditionClear) { - selectedReward.reward_value = ActorCondition.MAGNITUDE_CLEAR; - rewardValue.setEnabled(false); - rewardsListModel.itemChanged(selectedReward); - } else if (source == rewardConditionForever) { - selectedReward.reward_value = ActorCondition.DURATION_FOREVER; - rewardValue.setEnabled(false); - rewardsListModel.itemChanged(selectedReward); - } else if (source == rewardConditionTimed) { - selectedReward.reward_value = (Integer) ((JSpinner)rewardValue).getValue(); - rewardValue.setEnabled(true); - rewardsListModel.itemChanged(selectedReward); - } else if (source == replyTypeCombo) { - updateRepliesParamsEditorPane(repliesParamsPane, selectedReply, this); - repliesListModel.itemChanged(selectedReply); - } else if (source == replyText) { - selectedReply.text = (String) value; - repliesListModel.itemChanged(selectedReply); - } else if (source == replyNextPhrase) { - if (selectedReply.next_phrase != null) { - selectedReply.next_phrase.removeBacklink(dialogue); - } - selectedReply.next_phrase = (Dialogue) value; - if (selectedReply.next_phrase != null) { - selectedReply.next_phrase_id = selectedReply.next_phrase.id; - selectedReply.next_phrase.addBacklink(dialogue); - } else { - selectedReply.next_phrase_id = null; - } - repliesListModel.itemChanged(selectedReply); - } else if (source == requirementTypeCombo) { - selectedRequirement.changeType((Requirement.RequirementType)requirementTypeCombo.getSelectedItem()); - updateRequirementParamsEditorPane(requirementParamsPane, selectedRequirement, this); - requirementsListModel.itemChanged(selectedRequirement); - } else if (source == requirementObj) { - if (selectedRequirement.required_obj != null) { - selectedRequirement.required_obj.removeBacklink(dialogue); - } - selectedRequirement.required_obj = (GameDataElement) value; - if (selectedRequirement.required_obj != null) { - selectedRequirement.required_obj_id = selectedRequirement.required_obj.id; - selectedRequirement.required_obj.addBacklink(dialogue); - } else { - selectedRequirement.required_obj_id = null; - } - requirementsListModel.itemChanged(selectedRequirement); - } else if (source == requirementSkill) { - if (selectedRequirement.required_obj != null) { - selectedRequirement.required_obj.removeBacklink(dialogue); - selectedRequirement.required_obj = null; - } - if (selectedRequirement.type == Requirement.RequirementType.skillLevel) { - selectedRequirement.required_obj_id = value == null ? null : value.toString(); - } - requirementsListModel.itemChanged(selectedRequirement); - } else if (source == requirementObjId) { - selectedRequirement.required_obj_id = (String) value; - selectedRequirement.required_obj = null; - requirementsListModel.itemChanged(selectedRequirement); - } else if (source == requirementValue) { - //Backlink removal to quest stages when selecting another quest are handled in the addQuestStageBox() method. Too complex too handle here - Quest quest = null; - QuestStage stage; - if (requirementValue instanceof JComboBox) { - quest = ((Quest)selectedRequirement.required_obj); - if (quest != null && selectedRequirement.required_value != null) { - stage = quest.getStage(selectedRequirement.required_value); - if (stage != null) stage.removeBacklink(dialogue); - } - } - selectedRequirement.required_value = (Integer) value; - if (quest != null) { - stage = quest.getStage(selectedRequirement.required_value); - if (stage != null) stage.addBacklink(dialogue); - } - requirementsListModel.itemChanged(selectedRequirement); - } else if (source == requirementNegated) { - selectedRequirement.negated = (Boolean) value; - } - - if (dialogue.state != GameDataElement.State.modified) { - dialogue.state = GameDataElement.State.modified; - DialogueEditor.this.name = dialogue.getDesc(); - dialogue.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(DialogueEditor.this); - } - updateJsonViewText(dialogue.toJsonString()); - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java index e85d12c..44e50a5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java @@ -1,18 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.awt.Component; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JSpinner; -import javax.swing.JTextField; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; @@ -26,181 +13,187 @@ import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; +import java.util.List; + public class DroplistEditor extends JSONElementEditor { - private static final long serialVersionUID = 1139455254096811058L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - - private Droplist.DroppedItem selectedItem; - - private JTextField idField; - private MyComboBox itemCombo; - private DroppedItemsListModel droppedItemsListModel; - private JSpinner qtyMinField; - private JSpinner qtyMaxField; - private JComponent chanceField; - - public DroplistEditor(Droplist droplist) { - super(droplist, droplist.getDesc(), droplist.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void insertFormViewDataField(JPanel pane) { - - final Droplist droplist = (Droplist)target; - final FieldUpdateListener listener = new DroplistFieldUpdater(); - - createButtonPane(pane, droplist.getProject(), droplist, Droplist.class, Droplist.getImage(), null, listener); - - idField = addTextField(pane, "Droplist ID: ", droplist.id, droplist.writable, listener); + private static final long serialVersionUID = 1139455254096811058L; + + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; + + private Droplist.DroppedItem selectedItem; + + private JTextField idField; + private MyComboBox itemCombo; + private DroppedItemsListModel droppedItemsListModel; + private JSpinner qtyMinField; + private JSpinner qtyMaxField; + private JComponent chanceField; + + public DroplistEditor(Droplist droplist) { + super(droplist, droplist.getDesc(), droplist.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void insertFormViewDataField(JPanel pane) { + + final Droplist droplist = (Droplist) target; + final FieldUpdateListener listener = new DroplistFieldUpdater(); + + createButtonPane(pane, droplist.getProject(), droplist, Droplist.class, Droplist.getImage(), null, listener); + + idField = addTextField(pane, "Droplist ID: ", droplist.id, droplist.writable, listener); - droppedItemsListModel = new DroplistEditor.DroppedItemsListModel(droplist); - CollapsiblePanel itemsPane = UiUtils.getCollapsibleItemList( - listener, - droppedItemsListModel, - () -> selectedItem = null, - (selectedItem) -> this.selectedItem = selectedItem, - () -> this.selectedItem, - (selectedItem)->{}, - (droppedItemsEditorPane) -> updateDroppedItemsEditorPane(droppedItemsEditorPane, this.selectedItem, listener), - droplist.writable, - DroppedItem::new, - new DroppedItemsCellRenderer(), - "Items in this droplist: ", - (x)-> x.item, - false - ).collapsiblePanel; - if (droplist.dropped_items == null || droplist.dropped_items.isEmpty()) { - itemsPane.collapse(); - } + droppedItemsListModel = new DroplistEditor.DroppedItemsListModel(droplist); + CollapsiblePanel itemsPane = UiUtils.getCollapsibleItemList( + listener, + droppedItemsListModel, + () -> selectedItem = null, + (selectedItem) -> this.selectedItem = selectedItem, + () -> this.selectedItem, + (selectedItem) -> { + }, + (droppedItemsEditorPane) -> updateDroppedItemsEditorPane(droppedItemsEditorPane, this.selectedItem, listener), + droplist.writable, + DroppedItem::new, + new DroppedItemsCellRenderer(), + "Items in this droplist: ", + (x) -> x.item, + false + ).collapsiblePanel; + if (droplist.dropped_items == null || droplist.dropped_items.isEmpty()) { + itemsPane.collapse(); + } - pane.add(itemsPane, JideBoxLayout.FIX); - - } + pane.add(itemsPane, JideBoxLayout.FIX); - public void updateDroppedItemsEditorPane(JPanel pane, DroppedItem di, FieldUpdateListener listener) { - boolean writable = ((Droplist)target).writable; - Project proj = ((Droplist)target).getProject(); - pane.removeAll(); - if (itemCombo != null) { - removeElementListener(itemCombo); - } - if (di != null) { - itemCombo = addItemBox(pane, proj, "Item: ", di.item, writable, listener); - qtyMinField = addIntegerField(pane, "Quantity min: ", di.quantity_min, false, writable, listener); - qtyMaxField = addIntegerField(pane, "Quantity max: ", di.quantity_max, false, writable, listener); - chanceField = addChanceField(pane, "Chance: ", di.chance, "100", writable, listener);//addDoubleField(pane, "Chance: ", di.chance, writable, listener); - } - pane.revalidate(); - pane.repaint(); - } - - public class DroppedItemsListModel extends OrderedListenerListModel { - public DroppedItemsListModel(Droplist droplist) { - super(droplist); - } + } - @Override - protected List getItems() { - return source.dropped_items; - } + public void updateDroppedItemsEditorPane(JPanel pane, DroppedItem di, FieldUpdateListener listener) { + boolean writable = ((Droplist) target).writable; + Project proj = ((Droplist) target).getProject(); + pane.removeAll(); + if (itemCombo != null) { + removeElementListener(itemCombo); + } + if (di != null) { + itemCombo = addItemBox(pane, proj, "Item: ", di.item, writable, listener); + qtyMinField = addIntegerField(pane, "Quantity min: ", di.quantity_min, false, writable, listener); + qtyMaxField = addIntegerField(pane, "Quantity max: ", di.quantity_max, false, writable, listener); + chanceField = addChanceField(pane, "Chance: ", di.chance, "100", writable, listener);//addDoubleField(pane, "Chance: ", di.chance, writable, listener); + } + pane.revalidate(); + pane.repaint(); + } - @Override - protected void setItems(List items) { - source.dropped_items = items; - } - } - - public static class DroppedItemsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + public class DroppedItemsListModel extends OrderedListenerListModel { + public DroppedItemsListModel(Droplist droplist) { + super(droplist); + } - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Droplist.DroppedItem di = (Droplist.DroppedItem)value; - if (di.item != null) { - label.setIcon(new ImageIcon(di.item.getIcon())); - label.setText(di.chance+(di.chance != null && di.chance.contains("/") ? "" : "%")+" to get "+di.quantity_min+"-"+di.quantity_max+" "+di.item.getDesc()); - } else if (!isNull(di)) { - label.setText(di.chance+(di.chance != null && di.chance.contains("/") ? "" : "%")+" to get "+di.quantity_min+"-"+di.quantity_max+" "+di.item_id); - } else { - label.setText("New, undefined, dropped item."); - } - } - return c; - } - - public boolean isNull(Droplist.DroppedItem item) { - return ((item == null) || ( - item.item == null && - item.item_id == null && - item.quantity_min == null && - item.quantity_max == null && - item.chance == null - )); - } - } - - - public class DroplistFieldUpdater implements FieldUpdateListener { - @Override - public void valueChanged(JComponent source, Object value) { - Droplist droplist = ((Droplist)target); - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - droplist.id = (String) value; - DroplistEditor.this.name = droplist.getDesc(); - droplist.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(DroplistEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == itemCombo) { - if (selectedItem.item != null) { - selectedItem.item.removeBacklink(droplist); - } - selectedItem.item = (Item) value; - if (selectedItem.item != null) { - selectedItem.item_id = selectedItem.item.id; - selectedItem.item.addBacklink(droplist); - } else { - selectedItem.item_id = null; - } - droppedItemsListModel.itemChanged(selectedItem); - } else if (source == qtyMinField) { - selectedItem.quantity_min = (Integer) value; - droppedItemsListModel.itemChanged(selectedItem); - } else if (source == qtyMaxField) { - selectedItem.quantity_max = (Integer) value; - droppedItemsListModel.itemChanged(selectedItem); - } else if (source == chanceField) { - selectedItem.chance = (String) value; - droppedItemsListModel.itemChanged(selectedItem); - } + @Override + protected List getItems() { + return source.dropped_items; + } - if (droplist.state != GameDataElement.State.modified) { - droplist.state = GameDataElement.State.modified; - DroplistEditor.this.name = droplist.getDesc(); - droplist.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(DroplistEditor.this); - } - updateJsonViewText(droplist.toJsonString()); - } - } + @Override + protected void setItems(List items) { + source.dropped_items = items; + } + } + + public static class DroppedItemsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Droplist.DroppedItem di = (Droplist.DroppedItem) value; + if (di.item != null) { + label.setIcon(new ImageIcon(di.item.getIcon())); + label.setText(di.chance + (di.chance != null && di.chance.contains("/") ? "" : "%") + " to get " + di.quantity_min + "-" + di.quantity_max + " " + di.item.getDesc()); + } else if (!isNull(di)) { + label.setText(di.chance + (di.chance != null && di.chance.contains("/") ? "" : "%") + " to get " + di.quantity_min + "-" + di.quantity_max + " " + di.item_id); + } else { + label.setText("New, undefined, dropped item."); + } + } + return c; + } + + public boolean isNull(Droplist.DroppedItem item) { + return ((item == null) || ( + item.item == null && + item.item_id == null && + item.quantity_min == null && + item.quantity_max == null && + item.chance == null + )); + } + } + + + public class DroplistFieldUpdater implements FieldUpdateListener { + @Override + public void valueChanged(JComponent source, Object value) { + Droplist droplist = ((Droplist) target); + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + droplist.id = (String) value; + DroplistEditor.this.name = droplist.getDesc(); + droplist.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(DroplistEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == itemCombo) { + if (selectedItem.item != null) { + selectedItem.item.removeBacklink(droplist); + } + selectedItem.item = (Item) value; + if (selectedItem.item != null) { + selectedItem.item_id = selectedItem.item.id; + selectedItem.item.addBacklink(droplist); + } else { + selectedItem.item_id = null; + } + droppedItemsListModel.itemChanged(selectedItem); + } else if (source == qtyMinField) { + selectedItem.quantity_min = (Integer) value; + droppedItemsListModel.itemChanged(selectedItem); + } else if (source == qtyMaxField) { + selectedItem.quantity_max = (Integer) value; + droppedItemsListModel.itemChanged(selectedItem); + } else if (source == chanceField) { + selectedItem.chance = (String) value; + droppedItemsListModel.itemChanged(selectedItem); + } + + if (droplist.state != GameDataElement.State.modified) { + droplist.state = GameDataElement.State.modified; + DroplistEditor.this.name = droplist.getDesc(); + droplist.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(DroplistEditor.this); + } + updateJsonViewText(droplist.toJsonString()); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemCategoryEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemCategoryEditor.java index 0c2501e..67264bd 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemCategoryEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemCategoryEditor.java @@ -1,144 +1,135 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.awt.Component; -import java.util.ArrayList; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTextField; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import javax.swing.*; +import java.awt.*; +import java.util.ArrayList; + public class ItemCategoryEditor extends JSONElementEditor { - private static final long serialVersionUID = -2893876158803488355L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - - public ItemCategoryEditor(ItemCategory ic) { - super(ic, ic.getDesc(), ic.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - } - - private JButton icIcon; - private JTextField idField; - private JTextField nameField; - @SuppressWarnings("rawtypes") - private JComboBox slotBox; - @SuppressWarnings("rawtypes") - private JComboBox typeBox; - @SuppressWarnings("rawtypes") - private JComboBox sizeBox; - - @SuppressWarnings("unchecked") - @Override - public void insertFormViewDataField(JPanel pane) { - final ItemCategory ic = ((ItemCategory)target); - final FieldUpdateListener listener = new ItemCategoryFieldUpdater(); - - icIcon = createButtonPane(pane, ic.getProject(), ic, ItemCategory.class, ic.getImage(), null, listener); - - - idField = addTextField(pane, "Internal ID: ", ic.id, ic.writable, listener); - nameField = addTranslatableTextField(pane, "Display name: ", ic.name, ic.writable, listener); - typeBox = addEnumValueBox(pane, "Action type: ", ItemCategory.ActionType.values(), ic.action_type, ic.writable, listener); - slotBox = addEnumValueBox(pane, "Inventory slot: ", ItemCategory.InventorySlot.values(), ic.slot, ic.writable, listener); - sizeBox = addEnumValueBox(pane, "Item size: ", ItemCategory.Size.values(), ic.size, ic.writable, listener); - if (ic.action_type != ItemCategory.ActionType.equip) { - slotBox.setEnabled(false); - } - slotBox.setRenderer(new SlotCellRenderer()); - } - - public class SlotCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -8359181274986492979L; + private static final long serialVersionUID = -2893876158803488355L; - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - ((JLabel)c).setIcon(new ImageIcon(ItemCategory.getIcon((ItemCategory.InventorySlot) value))); - if (value == null) { - if (typeBox.getSelectedItem() == ItemCategory.ActionType.equip) { - ((JLabel)c).setText("Undefined. Select the slot to use when equipped."); - } else { - ((JLabel)c).setText("Non equippable. Select \"equip\" action type."); - } - } - } - return c; - } - } - - public class ItemCategoryFieldUpdater implements FieldUpdateListener { - @Override - public void valueChanged(JComponent source, Object value) { - ItemCategory ic = (ItemCategory)target; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - ic.id = (String) value; - ItemCategoryEditor.this.name = ic.getDesc(); - ic.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - ic.name = (String) value; - ItemCategoryEditor.this.name = ic.getDesc(); - ic.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); - } else if (source == slotBox) { - ic.slot = (ItemCategory.InventorySlot) value; - icIcon.setIcon(new ImageIcon(ic.getImage())); - ItemCategoryEditor.this.icon = new ImageIcon(ic.getIcon()); - ic.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); - } else if (source == typeBox) { - ic.action_type = (ItemCategory.ActionType) value; - if (ic.action_type != ItemCategory.ActionType.equip && ic.slot != null) { - ic.slot = null; - slotBox.setSelectedItem(null); - slotBox.setEnabled(false); - icIcon.setIcon(new ImageIcon(ic.getImage())); - ItemCategoryEditor.this.icon = new ImageIcon(ic.getIcon()); - ic.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); - } else if (ic.action_type == ItemCategory.ActionType.equip) { - slotBox.setEnabled(true); - } - } else if (source == sizeBox) { - ic.size = (ItemCategory.Size) value; - } - - if (ic.state != GameDataElement.State.modified) { - ic.state = GameDataElement.State.modified; - ItemCategoryEditor.this.name = ic.getDesc(); - ic.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); - } - updateJsonViewText(ic.toJsonString()); - } - } + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; + + public ItemCategoryEditor(ItemCategory ic) { + super(ic, ic.getDesc(), ic.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + } + + private JButton icIcon; + private JTextField idField; + private JTextField nameField; + @SuppressWarnings("rawtypes") + private JComboBox slotBox; + @SuppressWarnings("rawtypes") + private JComboBox typeBox; + @SuppressWarnings("rawtypes") + private JComboBox sizeBox; + + @SuppressWarnings("unchecked") + @Override + public void insertFormViewDataField(JPanel pane) { + final ItemCategory ic = ((ItemCategory) target); + final FieldUpdateListener listener = new ItemCategoryFieldUpdater(); + + icIcon = createButtonPane(pane, ic.getProject(), ic, ItemCategory.class, ic.getImage(), null, listener); + + + idField = addTextField(pane, "Internal ID: ", ic.id, ic.writable, listener); + nameField = addTranslatableTextField(pane, "Display name: ", ic.name, ic.writable, listener); + typeBox = addEnumValueBox(pane, "Action type: ", ItemCategory.ActionType.values(), ic.action_type, ic.writable, listener); + slotBox = addEnumValueBox(pane, "Inventory slot: ", ItemCategory.InventorySlot.values(), ic.slot, ic.writable, listener); + sizeBox = addEnumValueBox(pane, "Item size: ", ItemCategory.Size.values(), ic.size, ic.writable, listener); + if (ic.action_type != ItemCategory.ActionType.equip) { + slotBox.setEnabled(false); + } + slotBox.setRenderer(new SlotCellRenderer()); + } + + public class SlotCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = -8359181274986492979L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + ((JLabel) c).setIcon(new ImageIcon(ItemCategory.getIcon((ItemCategory.InventorySlot) value))); + if (value == null) { + if (typeBox.getSelectedItem() == ItemCategory.ActionType.equip) { + ((JLabel) c).setText("Undefined. Select the slot to use when equipped."); + } else { + ((JLabel) c).setText("Non equippable. Select \"equip\" action type."); + } + } + } + return c; + } + } + + public class ItemCategoryFieldUpdater implements FieldUpdateListener { + @Override + public void valueChanged(JComponent source, Object value) { + ItemCategory ic = (ItemCategory) target; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + ic.id = (String) value; + ItemCategoryEditor.this.name = ic.getDesc(); + ic.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + ic.name = (String) value; + ItemCategoryEditor.this.name = ic.getDesc(); + ic.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); + } else if (source == slotBox) { + ic.slot = (ItemCategory.InventorySlot) value; + icIcon.setIcon(new ImageIcon(ic.getImage())); + ItemCategoryEditor.this.icon = new ImageIcon(ic.getIcon()); + ic.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); + } else if (source == typeBox) { + ic.action_type = (ItemCategory.ActionType) value; + if (ic.action_type != ItemCategory.ActionType.equip && ic.slot != null) { + ic.slot = null; + slotBox.setSelectedItem(null); + slotBox.setEnabled(false); + icIcon.setIcon(new ImageIcon(ic.getImage())); + ItemCategoryEditor.this.icon = new ImageIcon(ic.getIcon()); + ic.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); + } else if (ic.action_type == ItemCategory.ActionType.equip) { + slotBox.setEnabled(true); + } + } else if (source == sizeBox) { + ic.size = (ItemCategory.Size) value; + } + + if (ic.state != GameDataElement.State.modified) { + ic.state = GameDataElement.State.modified; + ItemCategoryEditor.this.name = ic.getDesc(); + ic.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemCategoryEditor.this); + } + updateJsonViewText(ic.toJsonString()); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 66dbc11..50d7bd6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -1,1954 +1,1944 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; +import com.gpl.rpg.atcontentstudio.model.gamedata.Common; +import com.gpl.rpg.atcontentstudio.model.gamedata.Item; +import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.*; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.List; + public class ItemEditor extends JSONElementEditor { - private static final long serialVersionUID = 7538154592029351986L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - - private static final String killLabel = "Effect on every kill: "; - private static final String useLabel = "Effect on use: "; - - - private Common.ConditionEffect selectedEquipEffectCondition; - private Common.TimedConditionEffect selectedHitEffectSourceCondition; - private Common.TimedConditionEffect selectedHitEffectTargetCondition; - private Common.TimedConditionEffect selectedKillEffectCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; - - - private JButton itemIcon; - private JTextField idField; - private JTextField nameField; - private JTextField descriptionField; - @SuppressWarnings("rawtypes") - private JComboBox typeBox; - private IntegerBasedCheckBox manualPriceBox; - private JSpinner baseCostField; - private MyComboBox categoryBox; - private Integer baseManualPrice = null; - - private CollapsiblePanel equipEffectPane; - private Item.EquipEffect equipEffect; - private JSpinner equipDmgMin; - private JSpinner equipDmgMax; - private JSpinner equipBoostHP; - private JSpinner equipBoostAP; - private JSpinner equipBoostAC; - private JSpinner equipBoostBC; - private JSpinner equipBoostCS; - private JSpinner equipSetCM; - private JSpinner equipSetDM; - private JSpinner equipBoostDR; - private JSpinner equipIncMoveCost; - private JSpinner equipIncUseCost; - private JSpinner equipIncReequipCost; - private JSpinner equipIncAttackCost; - private ConditionsListModel equipConditionsModel; - @SuppressWarnings("rawtypes") - private JList equipConditionsList; - private MyComboBox equipConditionBox; - private JRadioButton equipConditionWithMagnitude; - private JRadioButton equipConditionImmunity; - private JSpinner equipConditionMagnitude; + private static final long serialVersionUID = 7538154592029351986L; - private CollapsiblePanel hitEffectPane; - private Common.HitEffect hitEffect; - private JSpinner hitHPMin; - private JSpinner hitHPMax; - private JSpinner hitAPMin; - private JSpinner hitAPMax; - private SourceTimedConditionsListModel hitSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; - private MyComboBox hitSourceConditionBox; - private JSpinner hitSourceConditionChance; - private JRadioButton hitSourceConditionClear; - private JRadioButton hitSourceConditionApply; - private JRadioButton hitSourceConditionImmunity; - private JSpinner hitSourceConditionMagnitude; - private JRadioButton hitSourceConditionTimed; - private JRadioButton hitSourceConditionForever; - private JSpinner hitSourceConditionDuration; - private TargetTimedConditionsListModel hitTargetConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitTargetConditionsList; - private MyComboBox hitTargetConditionBox; - private JSpinner hitTargetConditionChance; - private JRadioButton hitTargetConditionClear; - private JRadioButton hitTargetConditionApply; - private JRadioButton hitTargetConditionImmunity; - private JSpinner hitTargetConditionMagnitude; - private JRadioButton hitTargetConditionTimed; - private JRadioButton hitTargetConditionForever; - private JSpinner hitTargetConditionDuration; - - private CollapsiblePanel killEffectPane; - private Common.DeathEffect killEffect; - private JSpinner killHPMin; - private JSpinner killHPMax; - private JSpinner killAPMin; - private JSpinner killAPMax; - private SourceTimedConditionsListModel killSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList killSourceConditionsList; - private MyComboBox killSourceConditionBox; - private JSpinner killSourceConditionChance; - private JRadioButton killSourceConditionClear; - private JRadioButton killSourceConditionApply; - private JRadioButton killSourceConditionImmunity; - private JSpinner killSourceConditionMagnitude; - private JRadioButton killSourceConditionTimed; - private JRadioButton killSourceConditionForever; - private JSpinner killSourceConditionDuration; - - private CollapsiblePanel hitReceivedEffectPane; - private Common.HitReceivedEffect hitReceivedEffect; - private JSpinner hitReceivedHPMin; - private JSpinner hitReceivedHPMax; - private JSpinner hitReceivedAPMin; - private JSpinner hitReceivedAPMax; - private JSpinner hitReceivedHPMinTarget; - private JSpinner hitReceivedHPMaxTarget; - private JSpinner hitReceivedAPMinTarget; - private JSpinner hitReceivedAPMaxTarget; - private SourceTimedConditionsListModel hitReceivedSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedSourceConditionsList; - private MyComboBox hitReceivedSourceConditionBox; - private JSpinner hitReceivedSourceConditionChance; - private JRadioButton hitReceivedSourceConditionClear; - private JRadioButton hitReceivedSourceConditionApply; - private JRadioButton hitReceivedSourceConditionImmunity; - private JSpinner hitReceivedSourceConditionMagnitude; - private JRadioButton hitReceivedSourceConditionTimed; - private JRadioButton hitReceivedSourceConditionForever; - private JSpinner hitReceivedSourceConditionDuration; - private TargetTimedConditionsListModel hitReceivedTargetConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedTargetConditionsList; - private MyComboBox hitReceivedTargetConditionBox; - private JSpinner hitReceivedTargetConditionChance; - private JRadioButton hitReceivedTargetConditionClear; - private JRadioButton hitReceivedTargetConditionApply; - private JRadioButton hitReceivedTargetConditionImmunity; - private JSpinner hitReceivedTargetConditionMagnitude; - private JRadioButton hitReceivedTargetConditionTimed; - private JRadioButton hitReceivedTargetConditionForever; - private JSpinner hitReceivedTargetConditionDuration; - - public ItemEditor(Item item) { - super(item, item.getDesc(), item.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void insertFormViewDataField(JPanel pane) { + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; - final Item item = (Item) target; - - final FieldUpdateListener listener = new ItemFieldUpdater(); - - itemIcon = createButtonPane(pane, item.getProject(), item, Item.class, item.getImage(), Spritesheet.Category.item, listener); - - idField = addTextField(pane, "Internal ID: ", item.id, item.writable, listener); - nameField = addTranslatableTextField(pane, "Display name: ", item.name, item.writable, listener); - descriptionField = addTranslatableTextField(pane, "Description: ", item.description, item.writable, listener); - typeBox = addEnumValueBox(pane, "Type: ", Item.DisplayType.values(), item.display_type, item.writable, listener); - manualPriceBox = addIntegerBasedCheckBox(pane, "Has manual price", item.has_manual_price, item.writable, listener); - baseManualPrice = item.base_market_cost; - baseCostField = addIntegerField(pane, "Base market cost: ", (item.has_manual_price != null && item.has_manual_price == 1) ? item.base_market_cost : item.computePrice(), false, item.writable, listener); - if (!manualPriceBox.isSelected()) { - baseCostField.setEnabled(false); - } - categoryBox = addItemCategoryBox(pane, item.getProject(), "Category: ", item.category, item.writable, listener); - - equipEffectPane = new CollapsiblePanel("Effect when equipped: "); - equipEffectPane.setLayout(new JideBoxLayout(equipEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.equip_effect == null) { - equipEffect = new Item.EquipEffect(); - } else { - equipEffect = item.equip_effect; - } - equipDmgMin = addIntegerField(equipEffectPane, "Attack Damage min: ", equipEffect.damage_boost_min, true, item.writable, listener); - equipDmgMax = addIntegerField(equipEffectPane, "Attack Damage max: ", equipEffect.damage_boost_max, true, item.writable, listener); - equipSetDM = addIntegerField(equipEffectPane, "Damage modifier %: ", equipEffect.damage_modifier, 100, false, item.writable, listener); - equipBoostHP = addIntegerField(equipEffectPane, "Boost max HP: ", equipEffect.max_hp_boost, true, item.writable, listener); - equipBoostAP = addIntegerField(equipEffectPane, "Boost max AP: ", equipEffect.max_ap_boost, true, item.writable, listener); - equipBoostAC = addIntegerField(equipEffectPane, "Boost attack chance: ", equipEffect.increase_attack_chance, true, item.writable, listener); - equipBoostBC = addIntegerField(equipEffectPane, "Boost block chance: ", equipEffect.increase_block_chance, true, item.writable, listener); - equipBoostCS = addIntegerField(equipEffectPane, "Boost critical skill: ", equipEffect.increase_critical_skill, true, item.writable, listener); - equipSetCM = addDoubleField(equipEffectPane, "Critical multiplier: ", equipEffect.critical_multiplier, item.writable, listener); - equipBoostDR = addIntegerField(equipEffectPane, "Boost damage resistance: ", equipEffect.increase_damage_resistance, true, item.writable, listener); - equipIncMoveCost = addIntegerField(equipEffectPane, "Increase move cost: ", equipEffect.increase_move_cost, true, item.writable, listener); - equipIncUseCost = addIntegerField(equipEffectPane, "Increase item use cost: ", equipEffect.increase_use_item_cost, true, item.writable, listener); - equipIncReequipCost = addIntegerField(equipEffectPane, "Increase reequip cost: ", equipEffect.increase_reequip_cost, true, item.writable, listener); - equipIncAttackCost = addIntegerField(equipEffectPane, "Increase attack cost: ", equipEffect.increase_attack_cost, true, item.writable, listener); - CollapsiblePanel equipConditionsPane = new CollapsiblePanel("Actor Conditions applied when equipped: "); - equipConditionsPane.setLayout(new JideBoxLayout(equipConditionsPane, JideBoxLayout.PAGE_AXIS)); - equipConditionsModel = new ConditionsListModel(equipEffect); - equipConditionsList = new JList(equipConditionsModel); - equipConditionsList.setCellRenderer(new ConditionsCellRenderer()); - equipConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - equipConditionsPane.add(new JScrollPane(equipConditionsList), JideBoxLayout.FIX); - final JPanel equipConditionsEditorPane = new JPanel(); - final JButton createEquipCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteEquipCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - equipConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedEquipEffectCondition = (Common.ConditionEffect) equipConditionsList.getSelectedValue(); - if (selectedEquipEffectCondition == null) { - deleteEquipCondition.setEnabled(false); - } else { - deleteEquipCondition.setEnabled(true); - } - updateEquipConditionEditorPane(equipConditionsEditorPane, selectedEquipEffectCondition, listener); - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createEquipCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.ConditionEffect condition = new Common.ConditionEffect(); - equipConditionsModel.addItem(condition); - equipConditionsList.setSelectedValue(condition, true); - listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteEquipCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedEquipEffectCondition != null) { - equipConditionsModel.removeItem(selectedEquipEffectCondition); - selectedEquipEffectCondition = null; - equipConditionsList.clearSelection(); - listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createEquipCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteEquipCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - equipConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - equipConditionsEditorPane.setLayout(new JideBoxLayout(equipConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - equipConditionsPane.add(equipConditionsEditorPane, JideBoxLayout.FIX); - if (item.equip_effect == null || item.equip_effect.conditions == null || item.equip_effect.conditions.isEmpty()) { - equipConditionsPane.collapse(); - } - equipEffectPane.add(equipConditionsPane, JideBoxLayout.FIX); - pane.add(equipEffectPane, JideBoxLayout.FIX); - if (item.equip_effect == null) { - equipEffectPane.collapse(); - } - - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = item.hit_effect; - } - hitHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, item.writable, listener); - hitHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, item.writable, listener); - hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); - hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); - final CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); - hitSourceConditionsList = new JList(hitSourceConditionsModel); - hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); - final JPanel sourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); - updateHitSourceTimedConditionEditorPane(sourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); - if (selectedHitEffectSourceCondition == null) { - deleteHitSourceCondition.setEnabled(false); - } else { - deleteHitSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitSourceConditionsModel.addItem(condition); - hitSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectSourceCondition != null) { - hitSourceConditionsModel.removeItem(selectedHitEffectSourceCondition); - selectedHitEffectSourceCondition = null; - hitSourceConditionsList.clearSelection(); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - sourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(sourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsPane.add(sourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_effect == null || item.hit_effect.conditions_source == null || item.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); - } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); - hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); - hitTargetConditionsList = new JList(hitTargetConditionsModel); - hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); - final JPanel targetTimedConditionsEditorPane = new JPanel(); - final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); - updateHitTargetTimedConditionEditorPane(targetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); - if (selectedHitEffectTargetCondition == null) { - deleteHitTargetCondition.setEnabled(false); - } else { - deleteHitTargetCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitTargetConditionsModel.addItem(condition); - hitTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectTargetCondition != null) { - hitTargetConditionsModel.removeItem(selectedHitEffectTargetCondition); - selectedHitEffectTargetCondition = null; - hitTargetConditionsList.clearSelection(); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - targetTimedConditionsEditorPane.setLayout(new JideBoxLayout(targetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsPane.add(targetTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_effect == null || item.hit_effect.conditions_target == null || item.hit_effect.conditions_target.isEmpty()) { - hitTargetConditionsPane.collapse(); - } - hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); - if (item.hit_effect == null) { - hitEffectPane.collapse(); - } - pane.add(hitEffectPane, JideBoxLayout.FIX); - - - - killEffectPane = new CollapsiblePanel(killLabel); - killEffectPane.setLayout(new JideBoxLayout(killEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.kill_effect == null) { - killEffect = new Common.DeathEffect(); - } else { - killEffect = item.kill_effect; - } - killHPMin = addIntegerField(killEffectPane, "HP bonus min: ", killEffect.hp_boost_min, true, item.writable, listener); - killHPMax = addIntegerField(killEffectPane, "HP bonus max: ", killEffect.hp_boost_max, true, item.writable, listener); - killAPMin = addIntegerField(killEffectPane, "AP bonus min: ", killEffect.ap_boost_min, true, item.writable, listener); - killAPMax = addIntegerField(killEffectPane, "AP bonus max: ", killEffect.ap_boost_max, true, item.writable, listener); - final CollapsiblePanel killSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - killSourceConditionsPane.setLayout(new JideBoxLayout(killSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); - killSourceConditionsList = new JList(killSourceConditionsModel); - killSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - killSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - killSourceConditionsPane.add(new JScrollPane(killSourceConditionsList), JideBoxLayout.FIX); - final JPanel killSourceTimedConditionsEditorPane = new JPanel(); - final JButton createKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - killSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedKillEffectCondition = (Common.TimedConditionEffect) killSourceConditionsList.getSelectedValue(); - updateKillSourceTimedConditionEditorPane(killSourceTimedConditionsEditorPane, selectedKillEffectCondition, listener); - if (selectedKillEffectCondition == null) { - deleteKillSourceCondition.setEnabled(false); - } else { - deleteKillSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createKillSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - killSourceConditionsModel.addItem(condition); - killSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteKillSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedKillEffectCondition != null) { - killSourceConditionsModel.removeItem(selectedKillEffectCondition); - selectedKillEffectCondition = null; - killSourceConditionsList.clearSelection(); - listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createKillSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteKillSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - killSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - killSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(killSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - killSourceConditionsPane.add(killSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.kill_effect == null || item.kill_effect.conditions_source == null || item.kill_effect.conditions_source.isEmpty()) { - killSourceConditionsPane.collapse(); - } - killEffectPane.add(killSourceConditionsPane, JideBoxLayout.FIX); - if (item.kill_effect == null) { - killEffectPane.collapse(); - } - pane.add(killEffectPane, JideBoxLayout.FIX); - - - hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); - hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); - if (item.hit_received_effect == null) { - hitReceivedEffect = new Common.HitReceivedEffect(); - } else { - hitReceivedEffect = item.hit_received_effect; - } - hitReceivedHPMin = addIntegerField(hitReceivedEffectPane, "Player HP bonus min: ", hitReceivedEffect.hp_boost_min, true, item.writable, listener); - hitReceivedHPMax = addIntegerField(hitReceivedEffectPane, "Player HP bonus max: ", hitReceivedEffect.hp_boost_max, true, item.writable, listener); - hitReceivedAPMin = addIntegerField(hitReceivedEffectPane, "Player AP bonus min: ", hitReceivedEffect.ap_boost_min, true, item.writable, listener); - hitReceivedAPMax = addIntegerField(hitReceivedEffectPane, "Player AP bonus max: ", hitReceivedEffect.ap_boost_max, true, item.writable, listener); - hitReceivedHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, item.writable, listener); - hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, item.writable, listener); - hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, item.writable, listener); - hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, item.writable, listener); - final CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the player: "); - hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(hitReceivedEffect); - hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsModel); - hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); - updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); - if (selectedHitReceivedEffectSourceCondition == null) { - deleteHitReceivedSourceCondition.setEnabled(false); - } else { - deleteHitReceivedSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedSourceConditionsModel.addItem(condition); - hitReceivedSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectSourceCondition != null) { - hitReceivedSourceConditionsModel.removeItem(selectedHitReceivedEffectSourceCondition); - selectedHitReceivedEffectSourceCondition = null; - hitReceivedSourceConditionsList.clearSelection(); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_received_effect == null || item.hit_received_effect.conditions_source == null || item.hit_received_effect.conditions_source.isEmpty()) { - hitReceivedSourceConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); - hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); - hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsModel); - hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); - updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); - if (selectedHitReceivedEffectTargetCondition == null) { - deleteHitReceivedTargetCondition.setEnabled(false); - } else { - deleteHitReceivedTargetCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedTargetConditionsModel.addItem(condition); - hitReceivedTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectTargetCondition != null) { - hitReceivedTargetConditionsModel.removeItem(selectedHitReceivedEffectTargetCondition); - selectedHitReceivedEffectTargetCondition = null; - hitReceivedTargetConditionsList.clearSelection(); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - if (item.hit_received_effect == null || item.hit_received_effect.conditions_target == null || item.hit_received_effect.conditions_target.isEmpty()) { - hitReceivedTargetConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); - if (item.hit_received_effect == null) { - hitReceivedEffectPane.collapse(); - } - pane.add(hitReceivedEffectPane, JideBoxLayout.FIX); - - - if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { - equipEffectPane.setVisible(false); - hitEffectPane.setVisible(false); - killEffectPane.setVisible(false); - } else if (item.category.action_type == ItemCategory.ActionType.use) { - equipEffectPane.setVisible(false); - hitEffectPane.setVisible(false); - killEffectPane.setVisible(true); - killEffectPane.setTitle(useLabel); - killEffectPane.revalidate(); - killEffectPane.repaint(); - } else if (item.category.action_type == ItemCategory.ActionType.equip) { - equipEffectPane.setVisible(true); - hitEffectPane.setVisible(true); - killEffectPane.setVisible(true); - killEffectPane.setTitle(killLabel); - killEffectPane.revalidate(); - killEffectPane.repaint(); - } - - } - - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitSourceConditionBox != null) { - removeElementListener(hitSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); - - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); - - updateHitSourceTimedConditionWidgets(condition); - - hitSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); - } - }); - hitSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); - } - }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); - } - }); - - hitSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); - } - }); - hitSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + private static final String killLabel = "Effect on every kill: "; + private static final String useLabel = "Effect on use: "; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); - - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); - } - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitTargetConditionBox != null) { - removeElementListener(hitTargetConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); + private Common.ConditionEffect selectedEquipEffectCondition; + private Common.TimedConditionEffect selectedHitEffectSourceCondition; + private Common.TimedConditionEffect selectedHitEffectTargetCondition; + private Common.TimedConditionEffect selectedKillEffectCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; - hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitTargetConditionClear, JideBoxLayout.FIX); - hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitTargetConditionApply); - radioEffectGroup.add(hitTargetConditionClear); - radioEffectGroup.add(hitTargetConditionImmunity); - - hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitTargetConditionTimed); - radioDurationGroup.add(hitTargetConditionForever); - - updateHitTargetTimedConditionWidgets(condition); - - hitTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); - } - }); - hitTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); - } - }); - hitTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); - } - }); - - hitTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); - } - }); - hitTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } + private JButton itemIcon; + private JTextField idField; + private JTextField nameField; + private JTextField descriptionField; + @SuppressWarnings("rawtypes") + private JComboBox typeBox; + private IntegerBasedCheckBox manualPriceBox; + private JSpinner baseCostField; + private MyComboBox categoryBox; + private Integer baseManualPrice = null; - public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + private CollapsiblePanel equipEffectPane; + private Item.EquipEffect equipEffect; + private JSpinner equipDmgMin; + private JSpinner equipDmgMax; + private JSpinner equipBoostHP; + private JSpinner equipBoostAP; + private JSpinner equipBoostAC; + private JSpinner equipBoostBC; + private JSpinner equipBoostCS; + private JSpinner equipSetCM; + private JSpinner equipSetDM; + private JSpinner equipBoostDR; + private JSpinner equipIncMoveCost; + private JSpinner equipIncUseCost; + private JSpinner equipIncReequipCost; + private JSpinner equipIncAttackCost; + private ConditionsListModel equipConditionsModel; + @SuppressWarnings("rawtypes") + private JList equipConditionsList; + private MyComboBox equipConditionBox; + private JRadioButton equipConditionWithMagnitude; + private JRadioButton equipConditionImmunity; + private JSpinner equipConditionMagnitude; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitTargetConditionClear.setSelected(clear); - hitTargetConditionApply.setSelected(!clear && !immunity); - hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitTargetConditionImmunity.setSelected(immunity); - - hitTargetConditionTimed.setSelected(!forever); - hitTargetConditionTimed.setEnabled(!clear); - hitTargetConditionDuration.setEnabled(!clear && !forever); - hitTargetConditionForever.setSelected(forever); - hitTargetConditionForever.setEnabled(!clear); - } - - public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (killSourceConditionBox != null) { - removeElementListener(killSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); + private CollapsiblePanel hitEffectPane; + private Common.HitEffect hitEffect; + private JSpinner hitHPMin; + private JSpinner hitHPMax; + private JSpinner hitAPMin; + private JSpinner hitAPMax; + private SourceTimedConditionsListModel hitSourceConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitSourceConditionsList; + private MyComboBox hitSourceConditionBox; + private JSpinner hitSourceConditionChance; + private JRadioButton hitSourceConditionClear; + private JRadioButton hitSourceConditionApply; + private JRadioButton hitSourceConditionImmunity; + private JSpinner hitSourceConditionMagnitude; + private JRadioButton hitSourceConditionTimed; + private JRadioButton hitSourceConditionForever; + private JSpinner hitSourceConditionDuration; + private TargetTimedConditionsListModel hitTargetConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitTargetConditionsList; + private MyComboBox hitTargetConditionBox; + private JSpinner hitTargetConditionChance; + private JRadioButton hitTargetConditionClear; + private JRadioButton hitTargetConditionApply; + private JRadioButton hitTargetConditionImmunity; + private JSpinner hitTargetConditionMagnitude; + private JRadioButton hitTargetConditionTimed; + private JRadioButton hitTargetConditionForever; + private JSpinner hitTargetConditionDuration; - killSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - killSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + private CollapsiblePanel killEffectPane; + private Common.DeathEffect killEffect; + private JSpinner killHPMin; + private JSpinner killHPMax; + private JSpinner killAPMin; + private JSpinner killAPMax; + private SourceTimedConditionsListModel killSourceConditionsModel; + @SuppressWarnings("rawtypes") + private JList killSourceConditionsList; + private MyComboBox killSourceConditionBox; + private JSpinner killSourceConditionChance; + private JRadioButton killSourceConditionClear; + private JRadioButton killSourceConditionApply; + private JRadioButton killSourceConditionImmunity; + private JSpinner killSourceConditionMagnitude; + private JRadioButton killSourceConditionTimed; + private JRadioButton killSourceConditionForever; + private JSpinner killSourceConditionDuration; - killSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(killSourceConditionClear, JideBoxLayout.FIX); - killSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(killSourceConditionApply, JideBoxLayout.FIX); - killSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - killSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(killSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(killSourceConditionApply); - radioEffectGroup.add(killSourceConditionClear); - radioEffectGroup.add(killSourceConditionImmunity); - - killSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(killSourceConditionTimed, JideBoxLayout.FIX); - killSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - killSourceConditionForever = new JRadioButton("Forever"); - pane.add(killSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(killSourceConditionTimed); - radioDurationGroup.add(killSourceConditionForever); - - updateKillSourceTimedConditionWidgets(condition); - - killSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionClear, new Boolean(killSourceConditionClear.isSelected())); - } - }); - killSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionApply, new Boolean(killSourceConditionApply.isSelected())); - } - }); - killSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionImmunity, new Boolean(killSourceConditionImmunity.isSelected())); - } - }); - - killSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionTimed, new Boolean(killSourceConditionTimed.isSelected())); - } - }); - killSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionForever, new Boolean(killSourceConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } + private CollapsiblePanel hitReceivedEffectPane; + private Common.HitReceivedEffect hitReceivedEffect; + private JSpinner hitReceivedHPMin; + private JSpinner hitReceivedHPMax; + private JSpinner hitReceivedAPMin; + private JSpinner hitReceivedAPMax; + private JSpinner hitReceivedHPMinTarget; + private JSpinner hitReceivedHPMaxTarget; + private JSpinner hitReceivedAPMinTarget; + private JSpinner hitReceivedAPMaxTarget; + private SourceTimedConditionsListModel hitReceivedSourceConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedSourceConditionsList; + private MyComboBox hitReceivedSourceConditionBox; + private JSpinner hitReceivedSourceConditionChance; + private JRadioButton hitReceivedSourceConditionClear; + private JRadioButton hitReceivedSourceConditionApply; + private JRadioButton hitReceivedSourceConditionImmunity; + private JSpinner hitReceivedSourceConditionMagnitude; + private JRadioButton hitReceivedSourceConditionTimed; + private JRadioButton hitReceivedSourceConditionForever; + private JSpinner hitReceivedSourceConditionDuration; + private TargetTimedConditionsListModel hitReceivedTargetConditionsModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedTargetConditionsList; + private MyComboBox hitReceivedTargetConditionBox; + private JSpinner hitReceivedTargetConditionChance; + private JRadioButton hitReceivedTargetConditionClear; + private JRadioButton hitReceivedTargetConditionApply; + private JRadioButton hitReceivedTargetConditionImmunity; + private JSpinner hitReceivedTargetConditionMagnitude; + private JRadioButton hitReceivedTargetConditionTimed; + private JRadioButton hitReceivedTargetConditionForever; + private JSpinner hitReceivedTargetConditionDuration; - public void updateKillSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + public ItemEditor(Item item) { + super(item, item.getDesc(), item.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + } - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - killSourceConditionClear.setSelected(clear); - killSourceConditionApply.setSelected(!clear && !immunity); - killSourceConditionMagnitude.setEnabled(!clear && !immunity); - killSourceConditionImmunity.setSelected(immunity); - - killSourceConditionTimed.setSelected(!forever); - killSourceConditionTimed.setEnabled(!clear); - killSourceConditionDuration.setEnabled(!clear && !forever); - killSourceConditionForever.setSelected(forever); - killSourceConditionForever.setEnabled(!clear); - } - - public void updateEquipConditionEditorPane(JPanel pane, Common.ConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (equipConditionBox != null) { - removeElementListener(equipConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - equipConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - equipConditionWithMagnitude = new JRadioButton("Apply condition with magnitude."); - pane.add(equipConditionWithMagnitude, JideBoxLayout.FIX); - equipConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude, 1, false, writable, listener); - equipConditionImmunity = new JRadioButton("Give immunity to condition."); - pane.add(equipConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(equipConditionWithMagnitude); - radioEffectGroup.add(equipConditionImmunity); - - boolean immunity = condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR; - equipConditionImmunity.setSelected(immunity); - equipConditionWithMagnitude.setSelected(!immunity); - equipConditionMagnitude.setEnabled(!immunity); - - equipConditionWithMagnitude.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(equipConditionWithMagnitude, new Boolean(equipConditionWithMagnitude.isSelected())); - } - }); - equipConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(equipConditionImmunity, new Boolean(equipConditionImmunity.isSelected())); - } - }); - + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void insertFormViewDataField(JPanel pane) { - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedSourceConditionBox != null) { - removeElementListener(hitReceivedSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); - - hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); - hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); - hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedSourceConditionApply); - radioEffectGroup.add(hitReceivedSourceConditionClear); - radioEffectGroup.add(hitReceivedSourceConditionImmunity); - - hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); - hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedSourceConditionTimed); - radioDurationGroup.add(hitReceivedSourceConditionForever); - - updateHitReceivedSourceTimedConditionWidgets(condition); - - hitReceivedSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); - } - }); - hitReceivedSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); - } - }); - hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); - } - }); - - hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); - } - }); - hitReceivedSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + final Item item = (Item) target; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedSourceConditionClear.setSelected(clear); - hitReceivedSourceConditionApply.setSelected(!clear && !immunity); - hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedSourceConditionImmunity.setSelected(immunity); - - hitReceivedSourceConditionTimed.setSelected(!forever); - hitReceivedSourceConditionTimed.setEnabled(!clear); - hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); - hitReceivedSourceConditionForever.setSelected(forever); - hitReceivedSourceConditionForever.setEnabled(!clear); - } + final FieldUpdateListener listener = new ItemFieldUpdater(); - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedTargetConditionBox != null) { - removeElementListener(hitReceivedTargetConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item)target).writable; - Project proj = ((Item)target).getProject(); + itemIcon = createButtonPane(pane, item.getProject(), item, Item.class, item.getImage(), Spritesheet.Category.item, listener); - hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + idField = addTextField(pane, "Internal ID: ", item.id, item.writable, listener); + nameField = addTranslatableTextField(pane, "Display name: ", item.name, item.writable, listener); + descriptionField = addTranslatableTextField(pane, "Description: ", item.description, item.writable, listener); + typeBox = addEnumValueBox(pane, "Type: ", Item.DisplayType.values(), item.display_type, item.writable, listener); + manualPriceBox = addIntegerBasedCheckBox(pane, "Has manual price", item.has_manual_price, item.writable, listener); + baseManualPrice = item.base_market_cost; + baseCostField = addIntegerField(pane, "Base market cost: ", (item.has_manual_price != null && item.has_manual_price == 1) ? item.base_market_cost : item.computePrice(), false, item.writable, listener); + if (!manualPriceBox.isSelected()) { + baseCostField.setEnabled(false); + } + categoryBox = addItemCategoryBox(pane, item.getProject(), "Category: ", item.category, item.writable, listener); - hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); - hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); - hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedTargetConditionApply); - radioEffectGroup.add(hitReceivedTargetConditionClear); - radioEffectGroup.add(hitReceivedTargetConditionImmunity); - - hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); - hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedTargetConditionTimed); - radioDurationGroup.add(hitReceivedTargetConditionForever); - - updateHitReceivedTargetTimedConditionWidgets(condition); - - hitReceivedTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); - } - }); - hitReceivedTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); - } - }); - hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); - } - }); - - hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); - } - }); - hitReceivedTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); - } - }); - - pane.revalidate(); - pane.repaint(); - } + equipEffectPane = new CollapsiblePanel("Effect when equipped: "); + equipEffectPane.setLayout(new JideBoxLayout(equipEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.equip_effect == null) { + equipEffect = new Item.EquipEffect(); + } else { + equipEffect = item.equip_effect; + } + equipDmgMin = addIntegerField(equipEffectPane, "Attack Damage min: ", equipEffect.damage_boost_min, true, item.writable, listener); + equipDmgMax = addIntegerField(equipEffectPane, "Attack Damage max: ", equipEffect.damage_boost_max, true, item.writable, listener); + equipSetDM = addIntegerField(equipEffectPane, "Damage modifier %: ", equipEffect.damage_modifier, 100, false, item.writable, listener); + equipBoostHP = addIntegerField(equipEffectPane, "Boost max HP: ", equipEffect.max_hp_boost, true, item.writable, listener); + equipBoostAP = addIntegerField(equipEffectPane, "Boost max AP: ", equipEffect.max_ap_boost, true, item.writable, listener); + equipBoostAC = addIntegerField(equipEffectPane, "Boost attack chance: ", equipEffect.increase_attack_chance, true, item.writable, listener); + equipBoostBC = addIntegerField(equipEffectPane, "Boost block chance: ", equipEffect.increase_block_chance, true, item.writable, listener); + equipBoostCS = addIntegerField(equipEffectPane, "Boost critical skill: ", equipEffect.increase_critical_skill, true, item.writable, listener); + equipSetCM = addDoubleField(equipEffectPane, "Critical multiplier: ", equipEffect.critical_multiplier, item.writable, listener); + equipBoostDR = addIntegerField(equipEffectPane, "Boost damage resistance: ", equipEffect.increase_damage_resistance, true, item.writable, listener); + equipIncMoveCost = addIntegerField(equipEffectPane, "Increase move cost: ", equipEffect.increase_move_cost, true, item.writable, listener); + equipIncUseCost = addIntegerField(equipEffectPane, "Increase item use cost: ", equipEffect.increase_use_item_cost, true, item.writable, listener); + equipIncReequipCost = addIntegerField(equipEffectPane, "Increase reequip cost: ", equipEffect.increase_reequip_cost, true, item.writable, listener); + equipIncAttackCost = addIntegerField(equipEffectPane, "Increase attack cost: ", equipEffect.increase_attack_cost, true, item.writable, listener); + CollapsiblePanel equipConditionsPane = new CollapsiblePanel("Actor Conditions applied when equipped: "); + equipConditionsPane.setLayout(new JideBoxLayout(equipConditionsPane, JideBoxLayout.PAGE_AXIS)); + equipConditionsModel = new ConditionsListModel(equipEffect); + equipConditionsList = new JList(equipConditionsModel); + equipConditionsList.setCellRenderer(new ConditionsCellRenderer()); + equipConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + equipConditionsPane.add(new JScrollPane(equipConditionsList), JideBoxLayout.FIX); + final JPanel equipConditionsEditorPane = new JPanel(); + final JButton createEquipCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteEquipCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + equipConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedEquipEffectCondition = (Common.ConditionEffect) equipConditionsList.getSelectedValue(); + if (selectedEquipEffectCondition == null) { + deleteEquipCondition.setEnabled(false); + } else { + deleteEquipCondition.setEnabled(true); + } + updateEquipConditionEditorPane(equipConditionsEditorPane, selectedEquipEffectCondition, listener); + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createEquipCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.ConditionEffect condition = new Common.ConditionEffect(); + equipConditionsModel.addItem(condition); + equipConditionsList.setSelectedValue(condition, true); + listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteEquipCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedEquipEffectCondition != null) { + equipConditionsModel.removeItem(selectedEquipEffectCondition); + selectedEquipEffectCondition = null; + equipConditionsList.clearSelection(); + listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + listButtonsPane.add(createEquipCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteEquipCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + equipConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + equipConditionsEditorPane.setLayout(new JideBoxLayout(equipConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + equipConditionsPane.add(equipConditionsEditorPane, JideBoxLayout.FIX); + if (item.equip_effect == null || item.equip_effect.conditions == null || item.equip_effect.conditions.isEmpty()) { + equipConditionsPane.collapse(); + } + equipEffectPane.add(equipConditionsPane, JideBoxLayout.FIX); + pane.add(equipEffectPane, JideBoxLayout.FIX); + if (item.equip_effect == null) { + equipEffectPane.collapse(); + } - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedTargetConditionClear.setSelected(clear); - hitReceivedTargetConditionApply.setSelected(!clear && !immunity); - hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedTargetConditionImmunity.setSelected(immunity); - - hitReceivedTargetConditionTimed.setSelected(!forever); - hitReceivedTargetConditionTimed.setEnabled(!clear); - hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); - hitReceivedTargetConditionForever.setSelected(forever); - hitReceivedTargetConditionForever.setEnabled(!clear); - } + hitEffectPane = new CollapsiblePanel("Effect on every hit: "); + hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.hit_effect == null) { + hitEffect = new Common.HitEffect(); + } else { + hitEffect = item.hit_effect; + } + hitHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, item.writable, listener); + hitHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, item.writable, listener); + hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); + hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); + final CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); + hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); + hitSourceConditionsList = new JList(hitSourceConditionsModel); + hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); + final JPanel sourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); + updateHitSourceTimedConditionEditorPane(sourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); + if (selectedHitEffectSourceCondition == null) { + deleteHitSourceCondition.setEnabled(false); + } else { + deleteHitSourceCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitSourceConditionsModel.addItem(condition); + hitSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectSourceCondition != null) { + hitSourceConditionsModel.removeItem(selectedHitEffectSourceCondition); + selectedHitEffectSourceCondition = null; + hitSourceConditionsList.clearSelection(); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); - - public static class SourceTimedConditionsListModel extends OrderedListenerListModel { - public SourceTimedConditionsListModel(Common.DeathEffect effect) { - super(effect);; - } - @Override - protected List getItems() { - return source.conditions_source; - } + listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + sourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(sourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsPane.add(sourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_effect == null || item.hit_effect.conditions_source == null || item.hit_effect.conditions_source.isEmpty()) { + hitSourceConditionsPane.collapse(); + } + hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); + hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); + hitTargetConditionsList = new JList(hitTargetConditionsModel); + hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); + final JPanel targetTimedConditionsEditorPane = new JPanel(); + final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); + updateHitTargetTimedConditionEditorPane(targetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); + if (selectedHitEffectTargetCondition == null) { + deleteHitTargetCondition.setEnabled(false); + } else { + deleteHitTargetCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitTargetConditionsModel.addItem(condition); + hitTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectTargetCondition != null) { + hitTargetConditionsModel.removeItem(selectedHitEffectTargetCondition); + selectedHitEffectTargetCondition = null; + hitTargetConditionsList.clearSelection(); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); - @Override - protected void setItems(List items) { - source.conditions_source = items; - } - } - - public static class TargetTimedConditionsListModel extends OrderedListenerListModel { - public TargetTimedConditionsListModel(Common.HitEffect effect) { - super(effect); - } + listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + targetTimedConditionsEditorPane.setLayout(new JideBoxLayout(targetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsPane.add(targetTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_effect == null || item.hit_effect.conditions_target == null || item.hit_effect.conditions_target.isEmpty()) { + hitTargetConditionsPane.collapse(); + } + hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); + if (item.hit_effect == null) { + hitEffectPane.collapse(); + } + pane.add(hitEffectPane, JideBoxLayout.FIX); - @Override - protected List getItems() { - return source.conditions_target; - } - @Override - protected void setItems(List items) { - source.conditions_target = items; - } - } - - public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + killEffectPane = new CollapsiblePanel(killLabel); + killEffectPane.setLayout(new JideBoxLayout(killEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.kill_effect == null) { + killEffect = new Common.DeathEffect(); + } else { + killEffect = item.kill_effect; + } + killHPMin = addIntegerField(killEffectPane, "HP bonus min: ", killEffect.hp_boost_min, true, item.writable, listener); + killHPMax = addIntegerField(killEffectPane, "HP bonus max: ", killEffect.hp_boost_max, true, item.writable, listener); + killAPMin = addIntegerField(killEffectPane, "AP bonus min: ", killEffect.ap_boost_min, true, item.writable, listener); + killAPMax = addIntegerField(killEffectPane, "AP bonus max: ", killEffect.ap_boost_max, true, item.writable, listener); + final CollapsiblePanel killSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); + killSourceConditionsPane.setLayout(new JideBoxLayout(killSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); + killSourceConditionsList = new JList(killSourceConditionsModel); + killSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + killSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + killSourceConditionsPane.add(new JScrollPane(killSourceConditionsList), JideBoxLayout.FIX); + final JPanel killSourceTimedConditionsEditorPane = new JPanel(); + final JButton createKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + killSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedKillEffectCondition = (Common.TimedConditionEffect) killSourceConditionsList.getSelectedValue(); + updateKillSourceTimedConditionEditorPane(killSourceTimedConditionsEditorPane, selectedKillEffectCondition, listener); + if (selectedKillEffectCondition == null) { + deleteKillSourceCondition.setEnabled(false); + } else { + deleteKillSourceCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createKillSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + killSourceConditionsModel.addItem(condition); + killSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteKillSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedKillEffectCondition != null) { + killSourceConditionsModel.removeItem(selectedKillEffectCondition); + selectedKillEffectCondition = null; + killSourceConditionsList.clearSelection(); + listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; - - if (effect.condition != null) { - - boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); - boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); - boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; - - if (clear) { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to clear actor condition "+effect.condition.getDesc()); - } else if (immunity) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText(effect.chance+"% chances to give immunity to "+effect.condition.getDesc()+(forever ? " forever" : " for "+effect.duration+" rounds")); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude+(forever ? " forever" : " for "+effect.duration+" rounds")); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - - public static class ConditionsListModel extends OrderedListenerListModel { - public ConditionsListModel(Item.EquipEffect equipEffect) { - super(equipEffect); - } + listButtonsPane.add(createKillSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteKillSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + killSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + killSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(killSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + killSourceConditionsPane.add(killSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.kill_effect == null || item.kill_effect.conditions_source == null || item.kill_effect.conditions_source.isEmpty()) { + killSourceConditionsPane.collapse(); + } + killEffectPane.add(killSourceConditionsPane, JideBoxLayout.FIX); + if (item.kill_effect == null) { + killEffectPane.collapse(); + } + pane.add(killEffectPane, JideBoxLayout.FIX); - @Override - protected List getItems() { - return source.conditions; - } - @Override - protected void setItems(List conditions) { - source.conditions = conditions; - } - } - - public static class ConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); + hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); + if (item.hit_received_effect == null) { + hitReceivedEffect = new Common.HitReceivedEffect(); + } else { + hitReceivedEffect = item.hit_received_effect; + } + hitReceivedHPMin = addIntegerField(hitReceivedEffectPane, "Player HP bonus min: ", hitReceivedEffect.hp_boost_min, true, item.writable, listener); + hitReceivedHPMax = addIntegerField(hitReceivedEffectPane, "Player HP bonus max: ", hitReceivedEffect.hp_boost_max, true, item.writable, listener); + hitReceivedAPMin = addIntegerField(hitReceivedEffectPane, "Player AP bonus min: ", hitReceivedEffect.ap_boost_min, true, item.writable, listener); + hitReceivedAPMax = addIntegerField(hitReceivedEffectPane, "Player AP bonus max: ", hitReceivedEffect.ap_boost_max, true, item.writable, listener); + hitReceivedHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, item.writable, listener); + hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, item.writable, listener); + hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, item.writable, listener); + hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, item.writable, listener); + final CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the player: "); + hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(hitReceivedEffect); + hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsModel); + hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); + updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); + if (selectedHitReceivedEffectSourceCondition == null) { + deleteHitReceivedSourceCondition.setEnabled(false); + } else { + deleteHitReceivedSourceCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedSourceConditionsModel.addItem(condition); + hitReceivedSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectSourceCondition != null) { + hitReceivedSourceConditionsModel.removeItem(selectedHitReceivedEffectSourceCondition); + selectedHitReceivedEffectSourceCondition = null; + hitReceivedSourceConditionsList.clearSelection(); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Common.ConditionEffect effect = (Common.ConditionEffect) value; - - if (effect.condition != null) { - if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText("Immune to actor condition "+effect.condition.getDesc()); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText("Give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - - public static boolean isNull(Item.EquipEffect effect) { - if (effect.conditions != null) return false; - if (effect.critical_multiplier != null) return false; - if (effect.damage_modifier != null) return false; - if (effect.damage_boost_max != null) return false; - if (effect.damage_boost_min != null) return false; - if (effect.increase_attack_chance != null) return false; - if (effect.increase_attack_cost != null) return false; - if (effect.increase_block_chance != null) return false; - if (effect.increase_critical_skill != null) return false; - if (effect.increase_damage_resistance != null) return false; - if (effect.increase_move_cost != null) return false; - if (effect.increase_reequip_cost != null) return false; - if (effect.increase_use_item_cost != null) return false; - if (effect.max_ap_boost != null) return false; - if (effect.max_hp_boost != null) return false; - return true; - } - - - public static boolean isNull(Common.HitEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - + listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_received_effect == null || item.hit_received_effect.conditions_source == null || item.hit_received_effect.conditions_source.isEmpty()) { + hitReceivedSourceConditionsPane.collapse(); + } + hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); + hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); + hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsModel); + hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); + updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); + if (selectedHitReceivedEffectTargetCondition == null) { + deleteHitReceivedTargetCondition.setEnabled(false); + } else { + deleteHitReceivedTargetCondition.setEnabled(true); + } + } + }); + if (item.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedTargetConditionsModel.addItem(condition); + hitReceivedTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectTargetCondition != null) { + hitReceivedTargetConditionsModel.removeItem(selectedHitReceivedEffectTargetCondition); + selectedHitReceivedEffectTargetCondition = null; + hitReceivedTargetConditionsList.clearSelection(); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); - public static boolean isNull(Common.DeathEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - return true; - } - - public static boolean isNull(Common.HitReceivedEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.ap_boost_min_target != null) return false; - if (effect.ap_boost_max_target != null) return false; - if (effect.hp_boost_min_target != null) return false; - if (effect.hp_boost_max_target != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - - public class ItemFieldUpdater implements FieldUpdateListener { + listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); + if (item.hit_received_effect == null || item.hit_received_effect.conditions_target == null || item.hit_received_effect.conditions_target.isEmpty()) { + hitReceivedTargetConditionsPane.collapse(); + } + hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); + if (item.hit_received_effect == null) { + hitReceivedEffectPane.collapse(); + } + pane.add(hitReceivedEffectPane, JideBoxLayout.FIX); - @Override - public void valueChanged(JComponent source, Object value) { - Item item = (Item)target; - boolean updatePrice, updateEquip, updateHit, updateKill, updateHitReceived; - updatePrice = updateEquip = updateHit = updateKill = updateHitReceived = false; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - item.id = (String) value; - ItemEditor.this.name = item.getDesc(); - item.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - item.name = (String) value; - ItemEditor.this.name = item.getDesc(); - item.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemEditor.this); - } else if (source == itemIcon) { - item.icon_id = (String) value; - item.childrenChanged(new ArrayList()); - ItemEditor.this.icon = new ImageIcon(item.getProject().getIcon((String) value)); - ATContentStudio.frame.editorChanged(ItemEditor.this); - itemIcon.setIcon(new ImageIcon(item.getProject().getImage((String) value))); - itemIcon.revalidate(); - itemIcon.repaint(); - } else if (source == descriptionField) { - item.description = descriptionField.getText(); - } else if (source == typeBox) { - item.display_type = (Item.DisplayType) value; - } else if (source == manualPriceBox) { - item.has_manual_price = (Integer) value; - if (!manualPriceBox.isSelected()) { - baseCostField.setEnabled(false); - updatePrice = true; - } else { - baseCostField.setEnabled(true); - if (baseManualPrice != null) { - baseCostField.setValue(baseManualPrice); - } - } - } else if (source == baseCostField) { - if (manualPriceBox.isSelected()) { - item.base_market_cost = (Integer) value; - baseManualPrice = item.base_market_cost; - } - } else if (source == categoryBox) { - if (item.category != null) { - item.category.removeBacklink(item); - } - item.category = (ItemCategory) value; - if (item.category != null) { - item.category_id = item.category.id; - item.category.addBacklink(item); - } else { - item.category_id = null; - } - if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { - equipEffectPane.setVisible(false); - item.equip_effect = null; - hitEffectPane.setVisible(false); - item.hit_effect = null; - killEffectPane.setVisible(false); - item.kill_effect = null; - hitReceivedEffectPane.setVisible(false); - item.hit_received_effect = null; - ItemEditor.this.revalidate(); - ItemEditor.this.repaint(); - } else if (item.category.action_type == ItemCategory.ActionType.use) { - equipEffectPane.setVisible(false); - item.equip_effect = null; - hitEffectPane.setVisible(false); - item.hit_effect = null; - killEffectPane.setVisible(true); - updateKill = true; - hitReceivedEffectPane.setVisible(false); - item.hit_received_effect = null; - killEffectPane.setTitle(useLabel); - ItemEditor.this.revalidate(); - ItemEditor.this.repaint(); - } else if (item.category.action_type == ItemCategory.ActionType.equip) { - equipEffectPane.setVisible(true); + + if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { + equipEffectPane.setVisible(false); + hitEffectPane.setVisible(false); + killEffectPane.setVisible(false); + } else if (item.category.action_type == ItemCategory.ActionType.use) { + equipEffectPane.setVisible(false); + hitEffectPane.setVisible(false); + killEffectPane.setVisible(true); + killEffectPane.setTitle(useLabel); + killEffectPane.revalidate(); + killEffectPane.repaint(); + } else if (item.category.action_type == ItemCategory.ActionType.equip) { + equipEffectPane.setVisible(true); + hitEffectPane.setVisible(true); + killEffectPane.setVisible(true); + killEffectPane.setTitle(killLabel); + killEffectPane.revalidate(); + killEffectPane.repaint(); + } + + } + + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitSourceConditionBox != null) { + removeElementListener(hitSourceConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item) target).writable; + Project proj = ((Item) target).getProject(); + + hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitSourceConditionClear, JideBoxLayout.FIX); + hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitSourceConditionApply, JideBoxLayout.FIX); + hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitSourceConditionApply); + radioEffectGroup.add(hitSourceConditionClear); + radioEffectGroup.add(hitSourceConditionImmunity); + + hitSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); + hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitSourceConditionTimed); + radioDurationGroup.add(hitSourceConditionForever); + + updateHitSourceTimedConditionWidgets(condition); + + hitSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + } + }); + hitSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + } + }); + hitSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + } + }); + + hitSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + } + }); + hitSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitSourceConditionClear.setSelected(clear); + hitSourceConditionApply.setSelected(!clear && !immunity); + hitSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitSourceConditionImmunity.setSelected(immunity); + + hitSourceConditionTimed.setSelected(!forever); + hitSourceConditionTimed.setEnabled(!clear); + hitSourceConditionDuration.setEnabled(!clear && !forever); + hitSourceConditionForever.setSelected(forever); + hitSourceConditionForever.setEnabled(!clear); + } + + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitTargetConditionBox != null) { + removeElementListener(hitTargetConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item) target).writable; + Project proj = ((Item) target).getProject(); + + hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitTargetConditionClear, JideBoxLayout.FIX); + hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitTargetConditionApply, JideBoxLayout.FIX); + hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitTargetConditionApply); + radioEffectGroup.add(hitTargetConditionClear); + radioEffectGroup.add(hitTargetConditionImmunity); + + hitTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); + hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitTargetConditionTimed); + radioDurationGroup.add(hitTargetConditionForever); + + updateHitTargetTimedConditionWidgets(condition); + + hitTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + } + }); + hitTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + } + }); + hitTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + } + }); + + hitTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + } + }); + hitTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitTargetConditionClear.setSelected(clear); + hitTargetConditionApply.setSelected(!clear && !immunity); + hitTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitTargetConditionImmunity.setSelected(immunity); + + hitTargetConditionTimed.setSelected(!forever); + hitTargetConditionTimed.setEnabled(!clear); + hitTargetConditionDuration.setEnabled(!clear && !forever); + hitTargetConditionForever.setSelected(forever); + hitTargetConditionForever.setEnabled(!clear); + } + + public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (killSourceConditionBox != null) { + removeElementListener(killSourceConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item) target).writable; + Project proj = ((Item) target).getProject(); + + killSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + killSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + killSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(killSourceConditionClear, JideBoxLayout.FIX); + killSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(killSourceConditionApply, JideBoxLayout.FIX); + killSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + killSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(killSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(killSourceConditionApply); + radioEffectGroup.add(killSourceConditionClear); + radioEffectGroup.add(killSourceConditionImmunity); + + killSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(killSourceConditionTimed, JideBoxLayout.FIX); + killSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + killSourceConditionForever = new JRadioButton("Forever"); + pane.add(killSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(killSourceConditionTimed); + radioDurationGroup.add(killSourceConditionForever); + + updateKillSourceTimedConditionWidgets(condition); + + killSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionClear, new Boolean(killSourceConditionClear.isSelected())); + } + }); + killSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionApply, new Boolean(killSourceConditionApply.isSelected())); + } + }); + killSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionImmunity, new Boolean(killSourceConditionImmunity.isSelected())); + } + }); + + killSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionTimed, new Boolean(killSourceConditionTimed.isSelected())); + } + }); + killSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(killSourceConditionForever, new Boolean(killSourceConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateKillSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + killSourceConditionClear.setSelected(clear); + killSourceConditionApply.setSelected(!clear && !immunity); + killSourceConditionMagnitude.setEnabled(!clear && !immunity); + killSourceConditionImmunity.setSelected(immunity); + + killSourceConditionTimed.setSelected(!forever); + killSourceConditionTimed.setEnabled(!clear); + killSourceConditionDuration.setEnabled(!clear && !forever); + killSourceConditionForever.setSelected(forever); + killSourceConditionForever.setEnabled(!clear); + } + + public void updateEquipConditionEditorPane(JPanel pane, Common.ConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (equipConditionBox != null) { + removeElementListener(equipConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item) target).writable; + Project proj = ((Item) target).getProject(); + + equipConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + equipConditionWithMagnitude = new JRadioButton("Apply condition with magnitude."); + pane.add(equipConditionWithMagnitude, JideBoxLayout.FIX); + equipConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude, 1, false, writable, listener); + equipConditionImmunity = new JRadioButton("Give immunity to condition."); + pane.add(equipConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(equipConditionWithMagnitude); + radioEffectGroup.add(equipConditionImmunity); + + boolean immunity = condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR; + equipConditionImmunity.setSelected(immunity); + equipConditionWithMagnitude.setSelected(!immunity); + equipConditionMagnitude.setEnabled(!immunity); + + equipConditionWithMagnitude.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(equipConditionWithMagnitude, new Boolean(equipConditionWithMagnitude.isSelected())); + } + }); + equipConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(equipConditionImmunity, new Boolean(equipConditionImmunity.isSelected())); + } + }); + + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedSourceConditionBox != null) { + removeElementListener(hitReceivedSourceConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item) target).writable; + Project proj = ((Item) target).getProject(); + + hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); + hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); + hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedSourceConditionApply); + radioEffectGroup.add(hitReceivedSourceConditionClear); + radioEffectGroup.add(hitReceivedSourceConditionImmunity); + + hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); + hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedSourceConditionTimed); + radioDurationGroup.add(hitReceivedSourceConditionForever); + + updateHitReceivedSourceTimedConditionWidgets(condition); + + hitReceivedSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); + } + }); + hitReceivedSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); + } + }); + hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); + } + }); + + hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); + } + }); + hitReceivedSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedSourceConditionClear.setSelected(clear); + hitReceivedSourceConditionApply.setSelected(!clear && !immunity); + hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedSourceConditionImmunity.setSelected(immunity); + + hitReceivedSourceConditionTimed.setSelected(!forever); + hitReceivedSourceConditionTimed.setEnabled(!clear); + hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); + hitReceivedSourceConditionForever.setSelected(forever); + hitReceivedSourceConditionForever.setEnabled(!clear); + } + + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedTargetConditionBox != null) { + removeElementListener(hitReceivedTargetConditionBox); + } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } + + boolean writable = ((Item) target).writable; + Project proj = ((Item) target).getProject(); + + hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); + hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); + hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedTargetConditionApply); + radioEffectGroup.add(hitReceivedTargetConditionClear); + radioEffectGroup.add(hitReceivedTargetConditionImmunity); + + hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); + hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedTargetConditionTimed); + radioDurationGroup.add(hitReceivedTargetConditionForever); + + updateHitReceivedTargetTimedConditionWidgets(condition); + + hitReceivedTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); + } + }); + hitReceivedTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); + } + }); + hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); + } + }); + + hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); + } + }); + hitReceivedTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); + } + }); + + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedTargetConditionClear.setSelected(clear); + hitReceivedTargetConditionApply.setSelected(!clear && !immunity); + hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedTargetConditionImmunity.setSelected(immunity); + + hitReceivedTargetConditionTimed.setSelected(!forever); + hitReceivedTargetConditionTimed.setEnabled(!clear); + hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); + hitReceivedTargetConditionForever.setSelected(forever); + hitReceivedTargetConditionForever.setEnabled(!clear); + } + + + public static class SourceTimedConditionsListModel extends OrderedListenerListModel { + public SourceTimedConditionsListModel(Common.DeathEffect effect) { + super(effect); + ; + } + + @Override + protected List getItems() { + return source.conditions_source; + } + + @Override + protected void setItems(List items) { + source.conditions_source = items; + } + } + + public static class TargetTimedConditionsListModel extends OrderedListenerListModel { + public TargetTimedConditionsListModel(Common.HitEffect effect) { + super(effect); + } + + @Override + protected List getItems() { + return source.conditions_target; + } + + @Override + protected void setItems(List items) { + source.conditions_target = items; + } + } + + public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; + + if (effect.condition != null) { + + boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); + boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); + boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; + + if (clear) { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance + "% chances to clear actor condition " + effect.condition.getDesc()); + } else if (immunity) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText(effect.chance + "% chances to give immunity to " + effect.condition.getDesc() + (forever ? " forever" : " for " + effect.duration + " rounds")); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } + + public static class ConditionsListModel extends OrderedListenerListModel { + public ConditionsListModel(Item.EquipEffect equipEffect) { + super(equipEffect); + } + + @Override + protected List getItems() { + return source.conditions; + } + + @Override + protected void setItems(List conditions) { + source.conditions = conditions; + } + } + + public static class ConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Common.ConditionEffect effect = (Common.ConditionEffect) value; + + if (effect.condition != null) { + if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText("Immune to actor condition " + effect.condition.getDesc()); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText("Give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } + + public static boolean isNull(Item.EquipEffect effect) { + if (effect.conditions != null) return false; + if (effect.critical_multiplier != null) return false; + if (effect.damage_modifier != null) return false; + if (effect.damage_boost_max != null) return false; + if (effect.damage_boost_min != null) return false; + if (effect.increase_attack_chance != null) return false; + if (effect.increase_attack_cost != null) return false; + if (effect.increase_block_chance != null) return false; + if (effect.increase_critical_skill != null) return false; + if (effect.increase_damage_resistance != null) return false; + if (effect.increase_move_cost != null) return false; + if (effect.increase_reequip_cost != null) return false; + if (effect.increase_use_item_cost != null) return false; + if (effect.max_ap_boost != null) return false; + if (effect.max_hp_boost != null) return false; + return true; + } + + + public static boolean isNull(Common.HitEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + + public static boolean isNull(Common.DeathEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + return true; + } + + public static boolean isNull(Common.HitReceivedEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.ap_boost_min_target != null) return false; + if (effect.ap_boost_max_target != null) return false; + if (effect.hp_boost_min_target != null) return false; + if (effect.hp_boost_max_target != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + + public class ItemFieldUpdater implements FieldUpdateListener { + + @Override + public void valueChanged(JComponent source, Object value) { + Item item = (Item) target; + boolean updatePrice, updateEquip, updateHit, updateKill, updateHitReceived; + updatePrice = updateEquip = updateHit = updateKill = updateHitReceived = false; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + item.id = (String) value; + ItemEditor.this.name = item.getDesc(); + item.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + item.name = (String) value; + ItemEditor.this.name = item.getDesc(); + item.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemEditor.this); + } else if (source == itemIcon) { + item.icon_id = (String) value; + item.childrenChanged(new ArrayList()); + ItemEditor.this.icon = new ImageIcon(item.getProject().getIcon((String) value)); + ATContentStudio.frame.editorChanged(ItemEditor.this); + itemIcon.setIcon(new ImageIcon(item.getProject().getImage((String) value))); + itemIcon.revalidate(); + itemIcon.repaint(); + } else if (source == descriptionField) { + item.description = descriptionField.getText(); + } else if (source == typeBox) { + item.display_type = (Item.DisplayType) value; + } else if (source == manualPriceBox) { + item.has_manual_price = (Integer) value; + if (!manualPriceBox.isSelected()) { + baseCostField.setEnabled(false); + updatePrice = true; + } else { + baseCostField.setEnabled(true); + if (baseManualPrice != null) { + baseCostField.setValue(baseManualPrice); + } + } + } else if (source == baseCostField) { + if (manualPriceBox.isSelected()) { + item.base_market_cost = (Integer) value; + baseManualPrice = item.base_market_cost; + } + } else if (source == categoryBox) { + if (item.category != null) { + item.category.removeBacklink(item); + } + item.category = (ItemCategory) value; + if (item.category != null) { + item.category_id = item.category.id; + item.category.addBacklink(item); + } else { + item.category_id = null; + } + if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { + equipEffectPane.setVisible(false); + item.equip_effect = null; + hitEffectPane.setVisible(false); + item.hit_effect = null; + killEffectPane.setVisible(false); + item.kill_effect = null; + hitReceivedEffectPane.setVisible(false); + item.hit_received_effect = null; + ItemEditor.this.revalidate(); + ItemEditor.this.repaint(); + } else if (item.category.action_type == ItemCategory.ActionType.use) { + equipEffectPane.setVisible(false); + item.equip_effect = null; + hitEffectPane.setVisible(false); + item.hit_effect = null; + killEffectPane.setVisible(true); + updateKill = true; + hitReceivedEffectPane.setVisible(false); + item.hit_received_effect = null; + killEffectPane.setTitle(useLabel); + ItemEditor.this.revalidate(); + ItemEditor.this.repaint(); + } else if (item.category.action_type == ItemCategory.ActionType.equip) { + equipEffectPane.setVisible(true); hitEffectPane.setVisible(true); killEffectPane.setVisible(true); - updateKill = true; - hitReceivedEffectPane.setVisible(true); - updateEquip = true; - killEffectPane.setTitle(killLabel); - ItemEditor.this.revalidate(); - ItemEditor.this.repaint(); - } - updatePrice = true; - } else if (source == equipDmgMin) { - equipEffect.damage_boost_min = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipDmgMax) { - equipEffect.damage_boost_max = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostHP) { - equipEffect.max_hp_boost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostAP) { - equipEffect.max_ap_boost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostAC) { - equipEffect.increase_attack_chance = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostBC) { - equipEffect.increase_block_chance = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostCS) { - equipEffect.increase_critical_skill = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipSetCM) { - equipEffect.critical_multiplier = (Double) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipSetDM) { - equipEffect.damage_modifier = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipBoostDR) { - equipEffect.increase_damage_resistance = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncMoveCost) { - equipEffect.increase_move_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncUseCost) { - equipEffect.increase_use_item_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncReequipCost) { - equipEffect.increase_reequip_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipIncAttackCost) { - equipEffect.increase_attack_cost = (Integer) value; - updatePrice = true; - updateEquip = true; - } else if (source == equipConditionsList) { - updateEquip = true; - } else if (source == equipConditionBox) { - if (selectedEquipEffectCondition.condition != null) { - selectedEquipEffectCondition.condition.removeBacklink(item); - } - selectedEquipEffectCondition.condition = (ActorCondition) value; - if (selectedEquipEffectCondition.condition != null) { - selectedEquipEffectCondition.condition_id = selectedEquipEffectCondition.condition.id; - selectedEquipEffectCondition.condition.addBacklink(item); - } else { - selectedEquipEffectCondition.condition_id = null; - } - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == equipConditionMagnitude) { - selectedEquipEffectCondition.magnitude = (Integer) value; - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == equipConditionImmunity && (Boolean) value) { - selectedEquipEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - equipConditionMagnitude.setEnabled(false); - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == equipConditionWithMagnitude && (Boolean) value) { - selectedEquipEffectCondition.magnitude = (Integer) equipConditionMagnitude.getValue(); - equipConditionMagnitude.setEnabled(true); - equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == hitHPMin) { - hitEffect.hp_boost_min = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitHPMax) { - hitEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitAPMin) { - hitEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitAPMax) { - hitEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitSourceConditionsList) { - updateHit = true; - } else if (source == hitSourceConditionBox) { - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.removeBacklink(item); - } - selectedHitEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; - selectedHitEffectSourceCondition.condition.addBacklink(item); - } else { - selectedHitEffectSourceCondition.condition_id = null; - } - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionClear && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionApply && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionImmunity && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionMagnitude) { - selectedHitEffectSourceCondition.magnitude = (Integer) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionTimed && (Boolean) value) { - selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionForever && (Boolean) value) { - selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionDuration) { - selectedHitEffectSourceCondition.duration = (Integer) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionChance) { - selectedHitEffectSourceCondition.chance = (Double) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitTargetConditionsList) { - updateHit = true; - } else if (source == hitTargetConditionBox) { - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition.removeBacklink(item); - } - selectedHitEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; - selectedHitEffectTargetCondition.condition.addBacklink(item); - } else { - selectedHitEffectTargetCondition.condition_id = null; - } - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionClear && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionApply && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionImmunity && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionMagnitude) { - selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionTimed && (Boolean) value) { - selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionForever && (Boolean) value) { - selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionDuration) { - selectedHitEffectTargetCondition.duration = (Integer) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionChance) { - selectedHitEffectTargetCondition.chance = (Double) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == killHPMin) { - killEffect.hp_boost_min = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killHPMax) { - killEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killAPMin) { - killEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killAPMax) { - killEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killSourceConditionsList) { - updateKill = true; - } else if (source == killSourceConditionBox) { - if (selectedKillEffectCondition.condition != null) { - selectedKillEffectCondition.condition.removeBacklink(item); - } - selectedKillEffectCondition.condition = (ActorCondition) value; - if (selectedKillEffectCondition.condition != null) { - selectedKillEffectCondition.condition_id = selectedKillEffectCondition.condition.id; - selectedKillEffectCondition.condition.addBacklink(item); - } else { - selectedKillEffectCondition.condition_id = null; - } - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionClear && (Boolean) value) { - selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedKillEffectCondition.duration = null; - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionApply && (Boolean) value) { - selectedKillEffectCondition.magnitude = (Integer) killSourceConditionMagnitude.getValue(); - selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionImmunity && (Boolean) value) { - selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionMagnitude) { - selectedKillEffectCondition.magnitude = (Integer) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionTimed && (Boolean) value) { - selectedKillEffectCondition.duration = (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionForever && (Boolean) value) { - selectedKillEffectCondition.duration = ActorCondition.DURATION_FOREVER; - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionDuration) { - selectedKillEffectCondition.duration = (Integer) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionChance) { - selectedKillEffectCondition.chance = (Double) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == hitReceivedHPMin) { - hitReceivedEffect.hp_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMax) { - hitReceivedEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMin) { - hitReceivedEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMax) { - hitReceivedEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMinTarget) { - hitReceivedEffect.hp_boost_min_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMaxTarget) { - hitReceivedEffect.hp_boost_max_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMinTarget) { - hitReceivedEffect.ap_boost_min_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMaxTarget) { - hitReceivedEffect.ap_boost_max_target = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionBox) { - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.removeBacklink(item); - } - selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; - selectedHitReceivedEffectSourceCondition.condition.addBacklink(item); - } else { - selectedHitReceivedEffectSourceCondition.condition_id = null; - } - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = null; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionMagnitude) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionDuration) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionChance) { - selectedHitReceivedEffectSourceCondition.chance = (Double) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionBox) { - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition.removeBacklink(item); - } - selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; - selectedHitReceivedEffectTargetCondition.condition.addBacklink(item); - } else { - selectedHitReceivedEffectTargetCondition.condition_id = null; - } - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = null; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionMagnitude) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionDuration) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionChance) { - selectedHitReceivedEffectTargetCondition.chance = (Double) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } - - if (updateEquip) { - if (isNull(equipEffect)) { - item.equip_effect = null; - } else { - item.equip_effect = equipEffect; - } - } - if (updateHit) { - if (isNull(hitEffect)) { - item.hit_effect = null; - } else { - item.hit_effect = hitEffect; - } - } - if (updateKill) { - if (isNull(killEffect)) { - item.kill_effect = null; - } else { - item.kill_effect = killEffect; - } - } - if (updateHitReceived) { - if (isNull(hitReceivedEffect)) { - item.hit_received_effect = null; - } else { - item.hit_received_effect = hitReceivedEffect; - } - } - if (updatePrice && !manualPriceBox.isSelected()) { - baseCostField.setValue(item.computePrice()); - } + updateKill = true; + hitReceivedEffectPane.setVisible(true); + updateEquip = true; + killEffectPane.setTitle(killLabel); + ItemEditor.this.revalidate(); + ItemEditor.this.repaint(); + } + updatePrice = true; + } else if (source == equipDmgMin) { + equipEffect.damage_boost_min = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipDmgMax) { + equipEffect.damage_boost_max = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostHP) { + equipEffect.max_hp_boost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostAP) { + equipEffect.max_ap_boost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostAC) { + equipEffect.increase_attack_chance = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostBC) { + equipEffect.increase_block_chance = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostCS) { + equipEffect.increase_critical_skill = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipSetCM) { + equipEffect.critical_multiplier = (Double) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipSetDM) { + equipEffect.damage_modifier = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipBoostDR) { + equipEffect.increase_damage_resistance = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncMoveCost) { + equipEffect.increase_move_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncUseCost) { + equipEffect.increase_use_item_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncReequipCost) { + equipEffect.increase_reequip_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipIncAttackCost) { + equipEffect.increase_attack_cost = (Integer) value; + updatePrice = true; + updateEquip = true; + } else if (source == equipConditionsList) { + updateEquip = true; + } else if (source == equipConditionBox) { + if (selectedEquipEffectCondition.condition != null) { + selectedEquipEffectCondition.condition.removeBacklink(item); + } + selectedEquipEffectCondition.condition = (ActorCondition) value; + if (selectedEquipEffectCondition.condition != null) { + selectedEquipEffectCondition.condition_id = selectedEquipEffectCondition.condition.id; + selectedEquipEffectCondition.condition.addBacklink(item); + } else { + selectedEquipEffectCondition.condition_id = null; + } + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == equipConditionMagnitude) { + selectedEquipEffectCondition.magnitude = (Integer) value; + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == equipConditionImmunity && (Boolean) value) { + selectedEquipEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + equipConditionMagnitude.setEnabled(false); + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == equipConditionWithMagnitude && (Boolean) value) { + selectedEquipEffectCondition.magnitude = (Integer) equipConditionMagnitude.getValue(); + equipConditionMagnitude.setEnabled(true); + equipConditionsModel.itemChanged(selectedEquipEffectCondition); + } else if (source == hitHPMin) { + hitEffect.hp_boost_min = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitHPMax) { + hitEffect.hp_boost_max = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitAPMin) { + hitEffect.ap_boost_min = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitAPMax) { + hitEffect.ap_boost_max = (Integer) value; + updatePrice = true; + updateHit = true; + } else if (source == hitSourceConditionsList) { + updateHit = true; + } else if (source == hitSourceConditionBox) { + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition.removeBacklink(item); + } + selectedHitEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; + selectedHitEffectSourceCondition.condition.addBacklink(item); + } else { + selectedHitEffectSourceCondition.condition_id = null; + } + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionClear && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = null; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionApply && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionImmunity && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionMagnitude) { + selectedHitEffectSourceCondition.magnitude = (Integer) value; + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionTimed && (Boolean) value) { + selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionForever && (Boolean) value) { + selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionDuration) { + selectedHitEffectSourceCondition.duration = (Integer) value; + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionChance) { + selectedHitEffectSourceCondition.chance = (Double) value; + hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitTargetConditionsList) { + updateHit = true; + } else if (source == hitTargetConditionBox) { + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition.removeBacklink(item); + } + selectedHitEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; + selectedHitEffectTargetCondition.condition.addBacklink(item); + } else { + selectedHitEffectTargetCondition.condition_id = null; + } + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionClear && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = null; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionApply && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionImmunity && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionMagnitude) { + selectedHitEffectTargetCondition.magnitude = (Integer) value; + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionTimed && (Boolean) value) { + selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionForever && (Boolean) value) { + selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionDuration) { + selectedHitEffectTargetCondition.duration = (Integer) value; + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionChance) { + selectedHitEffectTargetCondition.chance = (Double) value; + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == killHPMin) { + killEffect.hp_boost_min = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killHPMax) { + killEffect.hp_boost_max = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killAPMin) { + killEffect.ap_boost_min = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killAPMax) { + killEffect.ap_boost_max = (Integer) value; + updatePrice = true; + updateKill = true; + } else if (source == killSourceConditionsList) { + updateKill = true; + } else if (source == killSourceConditionBox) { + if (selectedKillEffectCondition.condition != null) { + selectedKillEffectCondition.condition.removeBacklink(item); + } + selectedKillEffectCondition.condition = (ActorCondition) value; + if (selectedKillEffectCondition.condition != null) { + selectedKillEffectCondition.condition_id = selectedKillEffectCondition.condition.id; + selectedKillEffectCondition.condition.addBacklink(item); + } else { + selectedKillEffectCondition.condition_id = null; + } + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionClear && (Boolean) value) { + selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedKillEffectCondition.duration = null; + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionApply && (Boolean) value) { + selectedKillEffectCondition.magnitude = (Integer) killSourceConditionMagnitude.getValue(); + selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); + if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { + selectedKillEffectCondition.duration = 1; + } + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionImmunity && (Boolean) value) { + selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); + if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { + selectedKillEffectCondition.duration = 1; + } + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionMagnitude) { + selectedKillEffectCondition.magnitude = (Integer) value; + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionTimed && (Boolean) value) { + selectedKillEffectCondition.duration = (Integer) killSourceConditionDuration.getValue(); + if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { + selectedKillEffectCondition.duration = 1; + } + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionForever && (Boolean) value) { + selectedKillEffectCondition.duration = ActorCondition.DURATION_FOREVER; + updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionDuration) { + selectedKillEffectCondition.duration = (Integer) value; + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == killSourceConditionChance) { + selectedKillEffectCondition.chance = (Double) value; + killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateKill = true; + } else if (source == hitReceivedHPMin) { + hitReceivedEffect.hp_boost_min = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedHPMax) { + hitReceivedEffect.hp_boost_max = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMin) { + hitReceivedEffect.ap_boost_min = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMax) { + hitReceivedEffect.ap_boost_max = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedHPMinTarget) { + hitReceivedEffect.hp_boost_min_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedHPMaxTarget) { + hitReceivedEffect.hp_boost_max_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMinTarget) { + hitReceivedEffect.ap_boost_min_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedAPMaxTarget) { + hitReceivedEffect.ap_boost_max_target = (Integer) value; + updatePrice = true; + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionBox) { + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition.removeBacklink(item); + } + selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; + selectedHitReceivedEffectSourceCondition.condition.addBacklink(item); + } else { + selectedHitReceivedEffectSourceCondition.condition_id = null; + } + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = null; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionMagnitude) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionDuration) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) value; + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionChance) { + selectedHitReceivedEffectSourceCondition.chance = (Double) value; + hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionBox) { + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition.removeBacklink(item); + } + selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; + selectedHitReceivedEffectTargetCondition.condition.addBacklink(item); + } else { + selectedHitReceivedEffectTargetCondition.condition_id = null; + } + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = null; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionMagnitude) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionDuration) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) value; + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionChance) { + selectedHitReceivedEffectTargetCondition.chance = (Double) value; + hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } - - if (item.state != GameDataElement.State.modified) { - item.state = GameDataElement.State.modified; - ItemEditor.this.name = item.getDesc(); - item.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(ItemEditor.this); - } - updateJsonViewText(item.toJsonString()); - - } - - } + if (updateEquip) { + if (isNull(equipEffect)) { + item.equip_effect = null; + } else { + item.equip_effect = equipEffect; + } + } + if (updateHit) { + if (isNull(hitEffect)) { + item.hit_effect = null; + } else { + item.hit_effect = hitEffect; + } + } + if (updateKill) { + if (isNull(killEffect)) { + item.kill_effect = null; + } else { + item.kill_effect = killEffect; + } + } + if (updateHitReceived) { + if (isNull(hitReceivedEffect)) { + item.hit_received_effect = null; + } else { + item.hit_received_effect = hitReceivedEffect; + } + } + if (updatePrice && !manualPriceBox.isSelected()) { + baseCostField.setValue(item.computePrice()); + } + + + if (item.state != GameDataElement.State.modified) { + item.state = GameDataElement.State.modified; + ItemEditor.this.name = item.getDesc(); + item.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(ItemEditor.this); + } + updateJsonViewText(item.toJsonString()); + + } + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/JSONElementEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/JSONElementEditor.java index e313805..b501dba 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/JSONElementEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/JSONElementEditor.java @@ -1,33 +1,7 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.awt.BorderLayout; -import java.awt.Image; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.ScrollPaneConstants; -import javax.swing.SwingUtilities; - -import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; -import org.fife.ui.rsyntaxtextarea.SyntaxConstants; - import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.SaveEvent; +import com.gpl.rpg.atcontentstudio.model.*; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataCategory; import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; @@ -35,347 +9,352 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.Editor; -import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; -import com.gpl.rpg.atcontentstudio.ui.IdChangeImpactWizard; -import com.gpl.rpg.atcontentstudio.ui.SaveItemsWizard; -import com.gpl.rpg.atcontentstudio.ui.ScrollablePanel; +import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.ui.ScrollablePanel.ScrollableSizeHint; import com.gpl.rpg.atcontentstudio.ui.sprites.SpriteChooser; import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideTabbedPane; +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; + +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import java.util.*; public abstract class JSONElementEditor extends Editor { - private static final long serialVersionUID = -5889046987755079563L; - - - Map editorTabs = new LinkedHashMap(); - JideTabbedPane editorTabsHolder; - RSyntaxTextArea jsonEditorPane; - - public JSONElementEditor(JSONElement target, String desc, Image icon) { - super(); - this.target = target; - this.name = desc; - this.icon = new ImageIcon(icon); - - setLayout(new BorderLayout()); - editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); - editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); - editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); - editorTabsHolder.setShowCloseButtonOnTab(false); - add(editorTabsHolder, BorderLayout.CENTER); - } - - public void addEditorTab(String id, JPanel editor) { - ScrollablePanel view = new ScrollablePanel(new BorderLayout()); - view.setScrollableWidth(ScrollableSizeHint.FIT); - view.setScrollableHeight(ScrollableSizeHint.STRETCH); - view.add(editor, BorderLayout.CENTER); - JScrollPane scroller = new JScrollPane(view, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - scroller.getVerticalScrollBar().setUnitIncrement(16); - editorTabsHolder.addTab(id, scroller); - editorTabs.put(id, editor); - } - - public void removeEditorTab(String id) { - if (id == null) return; - for (int i =0; i concreteNodeClass, Image icon, final Spritesheet.Category iconCat, final FieldUpdateListener listener) { - final JButton gdeIcon = new JButton(new ImageIcon(icon)); - JPanel savePane = new JPanel(); - savePane.add(gdeIcon, JideBoxLayout.FIX); - savePane.setLayout(new JideBoxLayout(savePane, JideBoxLayout.LINE_AXIS, 6)); - if (node.writable) { - if (iconCat != null) { - gdeIcon.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - SpriteChooser chooser = SpriteChooser.getChooser(proj, iconCat); - chooser.setSelectionListener(new SpriteChooser.SelectionListener() { - @Override - public void iconSelected(String selected) { - if (selected != null) { - listener.valueChanged(gdeIcon, selected); - } - } - }); - chooser.setVisible(true); - } - }); - } - if (node.getDataType() == GameSource.Type.altered) { - savePane.add(message = new JLabel(ALTERED_MESSAGE), JideBoxLayout.FIX); - } else if (node.getDataType() == GameSource.Type.created) { - savePane.add(message = new JLabel(CREATED_MESSAGE), JideBoxLayout.FIX); - } - JButton save = new JButton(SAVE); - save.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (node.getParent() instanceof GameDataCategory) { - if (node.state != GameDataElement.State.saved) { - final List events = node.attemptSave(); - if (events == null) { - ATContentStudio.frame.nodeChanged(node); - } else { - new Thread() { - @Override - public void run() { - new SaveItemsWizard(events, node).setVisible(true); - } - }.start(); - } - } - } - } - }); - savePane.add(save, JideBoxLayout.FIX); - JButton delete = new JButton(DELETE); - if (node.getDataType() == GameSource.Type.altered) { - delete.setText(REVERT); - } - delete.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ATContentStudio.frame.closeEditor(node); - node.childrenRemoved(new ArrayList()); - if (node.getParent() instanceof GameDataCategory) { - ((GameDataCategory)node.getParent()).remove(node); - node.save(); - GameDataElement newOne = proj.getGameDataElement(node.getClass(), node.id); - if (node instanceof Quest) { - for (QuestStage oldStage : ((Quest) node).stages) { - QuestStage newStage = newOne != null ? ((Quest) newOne).getStage(oldStage.progress) : null; - for (GameDataElement backlink : oldStage.getBacklinks()) { - backlink.elementChanged(oldStage, newStage); - } - } - } - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, newOne); - } - } - } - }); - savePane.add(delete, JideBoxLayout.FIX); - - } else { - if (proj.alteredContent.gameData.getGameDataElement(concreteNodeClass, node.id) != null) { - savePane.add(message = new JLabel(ALTERED_EXISTS_MESSAGE), JideBoxLayout.FIX); - JButton makeWritable = new JButton("Go to altered"); - makeWritable.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (node.getProject().getGameDataElement(concreteNodeClass, node.id) != node) { - ATContentStudio.frame.openEditor(node.getProject().getGameDataElement(concreteNodeClass, node.id)); - ATContentStudio.frame.closeEditor(node); - ATContentStudio.frame.selectInTree(node.getProject().getGameDataElement(concreteNodeClass, node.id)); - } - } - }); - savePane.add(makeWritable, JideBoxLayout.FIX); - - } else { - savePane.add(message = new JLabel(READ_ONLY_MESSAGE), JideBoxLayout.FIX); - JButton makeWritable = new JButton("Alter"); - makeWritable.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (node.getProject().getGameDataElement(concreteNodeClass, node.id) == node) { - node.getProject().makeWritable(node); - } - if (node.getProject().getGameDataElement(concreteNodeClass, node.id) != node) { - ATContentStudio.frame.openEditor(node.getProject().getGameDataElement(concreteNodeClass, node.id)); - ATContentStudio.frame.closeEditor(node); - ATContentStudio.frame.selectInTree(node.getProject().getGameDataElement(concreteNodeClass, node.id)); - } - updateMessage(); - } - }); - savePane.add(makeWritable, JideBoxLayout.FIX); - } - } - JButton prev = new JButton(new ImageIcon(DefaultIcons.getArrowLeftIcon())); - JButton next = new JButton(new ImageIcon(DefaultIcons.getArrowRightIcon())); - final JButton bookmark = new JButton(new ImageIcon(node.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); - savePane.add(prev, JideBoxLayout.FIX); - savePane.add(next, JideBoxLayout.FIX); - savePane.add(bookmark, JideBoxLayout.FIX); - if (node.getParent().getIndex(node) == 0) { - prev.setEnabled(false); - } - if (node.getParent().getIndex(node) == node.getParent().getChildCount() - 1) { - next.setEnabled(false); - } - prev.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ProjectTreeNode prevNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) - 1); - if (prevNode != null && prevNode instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement) prevNode); - } - } - }); - next.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ProjectTreeNode nextNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) + 1); - if (nextNode != null && nextNode instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement) nextNode); - } - } - }); - bookmark.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - if (node.bookmark == null) { - node.getProject().bookmark(node); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); - } else { - node.bookmark.delete(); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); - } - } - }); - - - //Placeholder. Fills the eventual remaining space. - savePane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(savePane, JideBoxLayout.FIX); - return gdeIcon; - } + private static final long serialVersionUID = -5889046987755079563L; - @Override - public void targetUpdated() { - this.icon = new ImageIcon(((GameDataElement)target).getIcon()); - this.name = ((GameDataElement)target).getDesc(); - updateMessage(); - } - - public void updateMessage() { - - //TODO make this a full update of the button panel. - JSONElement node = (JSONElement) target; - if (node.writable) { - if (node.getDataType() == GameSource.Type.altered) { - message.setText(ALTERED_MESSAGE); - } else if (node.getDataType() == GameSource.Type.created) { - message.setText(CREATED_MESSAGE); - } - } else if (node.getProject().alteredContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { - message.setText(ALTERED_EXISTS_MESSAGE); - } else { - message.setText(READ_ONLY_MESSAGE); - } - message.revalidate(); - message.repaint(); - } - + Map editorTabs = new LinkedHashMap(); + JideTabbedPane editorTabsHolder; + RSyntaxTextArea jsonEditorPane; - @SuppressWarnings("unchecked") - public boolean idChanging() { - JSONElement node = (JSONElement) target; - List toModify = new LinkedList(); - List toAlter = new LinkedList(); - for (GameDataElement element : node.getBacklinks()) { - GameDataElement activeElement = element; - if (element instanceof JSONElement) { - activeElement = node.getProject().getGameDataElement((Class) element.getClass(), element.id); - } else if (element instanceof TMXMap) { - activeElement = node.getProject().getMap(element.id); - } else if (element instanceof WorldmapSegment) { - activeElement = node.getProject().getWorldmapSegment(element.id); - } - if (activeElement.writable) { - //No need to alter. Check if we flag a new modification. - if (!activeElement.needsSaving()) { - toModify.add(activeElement); - } - } else { - toAlter.add(activeElement); - } - } - if (!(toModify.isEmpty() && toAlter.isEmpty())) { - IdChangeImpactWizard.Result result = IdChangeImpactWizard.showIdChangeImapctWizard(target, toModify, toAlter); - if (result == IdChangeImpactWizard.Result.ok) { - for (GameDataElement element : toModify) { - element.state = GameDataElement.State.modified; - element.childrenChanged(new ArrayList()); - } - for (GameDataElement element : toAlter) { - if (element instanceof JSONElement) { - node.getProject().makeWritable((JSONElement)element); - } else if (element instanceof TMXMap) { - node.getProject().makeWritable((TMXMap)element); - } else if (element instanceof WorldmapSegment) { - node.getProject().makeWritable((WorldmapSegment)element); - } - } - return true; - } - } else { - return true; - } - return false; - } - - //setText in cancelIdEdit generates to edit events, one replacing the contents with the empty string, and one with the target.id. We want to skip the first one. - public boolean skipNext = false; - public void cancelIdEdit(final JTextField idField) { - Runnable revertField = new Runnable(){ - @Override - public void run() { - skipNext = true; - idField.setText(target.id); - } - }; - SwingUtilities.invokeLater(revertField); - } + public JSONElementEditor(JSONElement target, String desc, Image icon) { + super(); + this.target = target; + this.name = desc; + this.icon = new ImageIcon(icon); + + setLayout(new BorderLayout()); + editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); + editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); + editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); + editorTabsHolder.setShowCloseButtonOnTab(false); + add(editorTabsHolder, BorderLayout.CENTER); + } + + public void addEditorTab(String id, JPanel editor) { + ScrollablePanel view = new ScrollablePanel(new BorderLayout()); + view.setScrollableWidth(ScrollableSizeHint.FIT); + view.setScrollableHeight(ScrollableSizeHint.STRETCH); + view.add(editor, BorderLayout.CENTER); + JScrollPane scroller = new JScrollPane(view, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + scroller.getVerticalScrollBar().setUnitIncrement(16); + editorTabsHolder.addTab(id, scroller); + editorTabs.put(id, editor); + } + + public void removeEditorTab(String id) { + if (id == null) return; + for (int i = 0; i < editorTabsHolder.getTabCount(); i++) { + if (id.equals(editorTabsHolder.getTitleAt(i))) { + editorTabsHolder.removeTabAt(i); + editorTabs.remove(id); + } + } + } + + public JPanel getJSONView() { + jsonEditorPane = new RSyntaxTextArea(); + jsonEditorPane.setText(((JSONElement) target).toJsonString()); + jsonEditorPane.setEditable(((JSONElement) target).writable); + jsonEditorPane.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JSON); + jsonEditorPane.setFont(jsonEditorPane.getFont().deriveFont(ATContentStudio.SCALING * jsonEditorPane.getFont().getSize())); + JPanel result = new JPanel(); + result.setLayout(new BorderLayout()); + result.add(jsonEditorPane, BorderLayout.CENTER); + return result; + } + + public void updateJsonViewText(String text) { + jsonEditorPane.setText(text); + } + + public JPanel getFormView() { + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + if (((JSONElement) target).jsonFile != null) { + addLabelField(pane, "JSON File: ", ((JSONElement) target).jsonFile.getAbsolutePath()); + } + + insertFormViewDataField(pane); + + addBacklinksList(pane, (JSONElement) target); + + //Placeholder. Fills the eventual remaining space. + pane.add(new JPanel(), JideBoxLayout.VARY); + + return pane; + } + + public abstract void insertFormViewDataField(JPanel pane); + + + public JButton createButtonPane(JPanel pane, final Project proj, final JSONElement node, final Class concreteNodeClass, Image icon, final Spritesheet.Category iconCat, final FieldUpdateListener listener) { + final JButton gdeIcon = new JButton(new ImageIcon(icon)); + JPanel savePane = new JPanel(); + savePane.add(gdeIcon, JideBoxLayout.FIX); + savePane.setLayout(new JideBoxLayout(savePane, JideBoxLayout.LINE_AXIS, 6)); + if (node.writable) { + if (iconCat != null) { + gdeIcon.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + SpriteChooser chooser = SpriteChooser.getChooser(proj, iconCat); + chooser.setSelectionListener(new SpriteChooser.SelectionListener() { + @Override + public void iconSelected(String selected) { + if (selected != null) { + listener.valueChanged(gdeIcon, selected); + } + } + }); + chooser.setVisible(true); + } + }); + } + if (node.getDataType() == GameSource.Type.altered) { + savePane.add(message = new JLabel(ALTERED_MESSAGE), JideBoxLayout.FIX); + } else if (node.getDataType() == GameSource.Type.created) { + savePane.add(message = new JLabel(CREATED_MESSAGE), JideBoxLayout.FIX); + } + JButton save = new JButton(SAVE); + save.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (node.getParent() instanceof GameDataCategory) { + if (node.state != GameDataElement.State.saved) { + final List events = node.attemptSave(); + if (events == null) { + ATContentStudio.frame.nodeChanged(node); + } else { + new Thread() { + @Override + public void run() { + new SaveItemsWizard(events, node).setVisible(true); + } + }.start(); + } + } + } + } + }); + savePane.add(save, JideBoxLayout.FIX); + JButton delete = new JButton(DELETE); + if (node.getDataType() == GameSource.Type.altered) { + delete.setText(REVERT); + } + delete.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ATContentStudio.frame.closeEditor(node); + node.childrenRemoved(new ArrayList()); + if (node.getParent() instanceof GameDataCategory) { + ((GameDataCategory) node.getParent()).remove(node); + node.save(); + GameDataElement newOne = proj.getGameDataElement(node.getClass(), node.id); + if (node instanceof Quest) { + for (QuestStage oldStage : ((Quest) node).stages) { + QuestStage newStage = newOne != null ? ((Quest) newOne).getStage(oldStage.progress) : null; + for (GameDataElement backlink : oldStage.getBacklinks()) { + backlink.elementChanged(oldStage, newStage); + } + } + } + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, newOne); + } + } + } + }); + savePane.add(delete, JideBoxLayout.FIX); + + } else { + if (proj.alteredContent.gameData.getGameDataElement(concreteNodeClass, node.id) != null) { + savePane.add(message = new JLabel(ALTERED_EXISTS_MESSAGE), JideBoxLayout.FIX); + JButton makeWritable = new JButton("Go to altered"); + makeWritable.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (node.getProject().getGameDataElement(concreteNodeClass, node.id) != node) { + ATContentStudio.frame.openEditor(node.getProject().getGameDataElement(concreteNodeClass, node.id)); + ATContentStudio.frame.closeEditor(node); + ATContentStudio.frame.selectInTree(node.getProject().getGameDataElement(concreteNodeClass, node.id)); + } + } + }); + savePane.add(makeWritable, JideBoxLayout.FIX); + + } else { + savePane.add(message = new JLabel(READ_ONLY_MESSAGE), JideBoxLayout.FIX); + JButton makeWritable = new JButton("Alter"); + makeWritable.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (node.getProject().getGameDataElement(concreteNodeClass, node.id) == node) { + node.getProject().makeWritable(node); + } + if (node.getProject().getGameDataElement(concreteNodeClass, node.id) != node) { + ATContentStudio.frame.openEditor(node.getProject().getGameDataElement(concreteNodeClass, node.id)); + ATContentStudio.frame.closeEditor(node); + ATContentStudio.frame.selectInTree(node.getProject().getGameDataElement(concreteNodeClass, node.id)); + } + updateMessage(); + } + }); + savePane.add(makeWritable, JideBoxLayout.FIX); + } + } + JButton prev = new JButton(new ImageIcon(DefaultIcons.getArrowLeftIcon())); + JButton next = new JButton(new ImageIcon(DefaultIcons.getArrowRightIcon())); + final JButton bookmark = new JButton(new ImageIcon(node.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); + savePane.add(prev, JideBoxLayout.FIX); + savePane.add(next, JideBoxLayout.FIX); + savePane.add(bookmark, JideBoxLayout.FIX); + if (node.getParent().getIndex(node) == 0) { + prev.setEnabled(false); + } + if (node.getParent().getIndex(node) == node.getParent().getChildCount() - 1) { + next.setEnabled(false); + } + prev.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ProjectTreeNode prevNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) - 1); + if (prevNode != null && prevNode instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) prevNode); + } + } + }); + next.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ProjectTreeNode nextNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) + 1); + if (nextNode != null && nextNode instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) nextNode); + } + } + }); + bookmark.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + if (node.bookmark == null) { + node.getProject().bookmark(node); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); + } else { + node.bookmark.delete(); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); + } + } + }); + + + //Placeholder. Fills the eventual remaining space. + savePane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(savePane, JideBoxLayout.FIX); + return gdeIcon; + } + + + @Override + public void targetUpdated() { + this.icon = new ImageIcon(((GameDataElement) target).getIcon()); + this.name = ((GameDataElement) target).getDesc(); + updateMessage(); + } + + public void updateMessage() { + + //TODO make this a full update of the button panel. + JSONElement node = (JSONElement) target; + if (node.writable) { + if (node.getDataType() == GameSource.Type.altered) { + message.setText(ALTERED_MESSAGE); + } else if (node.getDataType() == GameSource.Type.created) { + message.setText(CREATED_MESSAGE); + } + } else if (node.getProject().alteredContent.gameData.getGameDataElement(node.getClass(), node.id) != null) { + message.setText(ALTERED_EXISTS_MESSAGE); + } else { + message.setText(READ_ONLY_MESSAGE); + } + message.revalidate(); + message.repaint(); + } + + + @SuppressWarnings("unchecked") + public boolean idChanging() { + JSONElement node = (JSONElement) target; + List toModify = new LinkedList(); + List toAlter = new LinkedList(); + for (GameDataElement element : node.getBacklinks()) { + GameDataElement activeElement = element; + if (element instanceof JSONElement) { + activeElement = node.getProject().getGameDataElement((Class) element.getClass(), element.id); + } else if (element instanceof TMXMap) { + activeElement = node.getProject().getMap(element.id); + } else if (element instanceof WorldmapSegment) { + activeElement = node.getProject().getWorldmapSegment(element.id); + } + if (activeElement.writable) { + //No need to alter. Check if we flag a new modification. + if (!activeElement.needsSaving()) { + toModify.add(activeElement); + } + } else { + toAlter.add(activeElement); + } + } + if (!(toModify.isEmpty() && toAlter.isEmpty())) { + IdChangeImpactWizard.Result result = IdChangeImpactWizard.showIdChangeImapctWizard(target, toModify, toAlter); + if (result == IdChangeImpactWizard.Result.ok) { + for (GameDataElement element : toModify) { + element.state = GameDataElement.State.modified; + element.childrenChanged(new ArrayList()); + } + for (GameDataElement element : toAlter) { + if (element instanceof JSONElement) { + node.getProject().makeWritable((JSONElement) element); + } else if (element instanceof TMXMap) { + node.getProject().makeWritable((TMXMap) element); + } else if (element instanceof WorldmapSegment) { + node.getProject().makeWritable((WorldmapSegment) element); + } + } + return true; + } + } else { + return true; + } + return false; + } + + //setText in cancelIdEdit generates to edit events, one replacing the contents with the empty string, and one with the target.id. We want to skip the first one. + public boolean skipNext = false; + + public void cancelIdEdit(final JTextField idField) { + Runnable revertField = new Runnable() { + @Override + public void run() { + skipNext = true; + idField.setText(target.id); + } + }; + SwingUtilities.invokeLater(revertField); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index bbe4ac6..705dbc0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -1,29 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; @@ -34,1575 +10,1584 @@ import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.List; + public class NPCEditor extends JSONElementEditor { - private static final long serialVersionUID = 4001483665523721800L; - - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - private static final String dialogue_tree_id = "Dialogue Tree"; + private static final long serialVersionUID = 4001483665523721800L; - private Common.TimedConditionEffect selectedHitEffectSourceCondition; - private Common.TimedConditionEffect selectedHitEffectTargetCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; - private Common.TimedConditionEffect selectedDeathEffectSourceCondition; - - private JButton npcIcon; - private JTextField idField; - private JTextField nameField; - private JTextField spawnGroupField; - private JTextField factionField; - private JSpinner experienceField; - private MyComboBox dialogueBox; - private MyComboBox droplistBox; - @SuppressWarnings("rawtypes") - private JComboBox monsterClassBox; - private IntegerBasedCheckBox uniqueBox; - @SuppressWarnings("rawtypes") - private JComboBox moveTypeBox; - - private CollapsiblePanel combatTraitPane; - private JSpinner maxHP; - private JSpinner maxAP; - private JSpinner moveCost; - private JSpinner atkDmgMin; - private JSpinner atkDmgMax; - private JSpinner atkCost; - private JSpinner atkChance; - private JSpinner critSkill; - private JSpinner critMult; - private JSpinner blockChance; - private JSpinner dmgRes; + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; + private static final String dialogue_tree_id = "Dialogue Tree"; - private Common.HitEffect hitEffect; - private CollapsiblePanel hitEffectPane; - private JSpinner hitEffectHPMin; - private JSpinner hitEffectHPMax; - private JSpinner hitEffectAPMin; - private JSpinner hitEffectAPMax; - - private SourceTimedConditionsListModel hitSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; - private MyComboBox hitSourceConditionBox; - private JSpinner hitSourceConditionChance; - private JRadioButton hitSourceConditionClear; - private JRadioButton hitSourceConditionApply; - private JRadioButton hitSourceConditionImmunity; - private JSpinner hitSourceConditionMagnitude; - private JRadioButton hitSourceConditionTimed; - private JRadioButton hitSourceConditionForever; - private JSpinner hitSourceConditionDuration; - - private TargetTimedConditionsListModel hitTargetConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitTargetConditionsList; - private MyComboBox hitTargetConditionBox; - private JSpinner hitTargetConditionChance; - private JRadioButton hitTargetConditionClear; - private JRadioButton hitTargetConditionApply; - private JRadioButton hitTargetConditionImmunity; - private JSpinner hitTargetConditionMagnitude; - private JRadioButton hitTargetConditionTimed; - private JRadioButton hitTargetConditionForever; - private JSpinner hitTargetConditionDuration; + private Common.TimedConditionEffect selectedHitEffectSourceCondition; + private Common.TimedConditionEffect selectedHitEffectTargetCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; + private Common.TimedConditionEffect selectedDeathEffectSourceCondition; - private Common.HitReceivedEffect hitReceivedEffect; - private CollapsiblePanel hitReceivedEffectPane; - private JSpinner hitReceivedEffectHPMin; - private JSpinner hitReceivedEffectHPMax; - private JSpinner hitReceivedEffectAPMin; - private JSpinner hitReceivedEffectAPMax; - private JSpinner hitReceivedEffectHPMinTarget; - private JSpinner hitReceivedEffectHPMaxTarget; - private JSpinner hitReceivedEffectAPMinTarget; - private JSpinner hitReceivedEffectAPMaxTarget; - - private SourceTimedConditionsListModel hitReceivedSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedSourceConditionsList; - private MyComboBox hitReceivedSourceConditionBox; - private JSpinner hitReceivedSourceConditionChance; - private JRadioButton hitReceivedSourceConditionClear; - private JRadioButton hitReceivedSourceConditionApply; - private JRadioButton hitReceivedSourceConditionImmunity; - private JSpinner hitReceivedSourceConditionMagnitude; - private JRadioButton hitReceivedSourceConditionTimed; - private JRadioButton hitReceivedSourceConditionForever; - private JSpinner hitReceivedSourceConditionDuration; - - private TargetTimedConditionsListModel hitReceivedTargetConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedTargetConditionsList; - private MyComboBox hitReceivedTargetConditionBox; - private JSpinner hitReceivedTargetConditionChance; - private JRadioButton hitReceivedTargetConditionClear; - private JRadioButton hitReceivedTargetConditionApply; - private JRadioButton hitReceivedTargetConditionImmunity; - private JSpinner hitReceivedTargetConditionMagnitude; - private JRadioButton hitReceivedTargetConditionTimed; - private JRadioButton hitReceivedTargetConditionForever; - private JSpinner hitReceivedTargetConditionDuration; - - private Common.DeathEffect deathEffect; - private CollapsiblePanel deathEffectPane; - private JSpinner deathEffectHPMin; - private JSpinner deathEffectHPMax; - private JSpinner deathEffectAPMin; - private JSpinner deathEffectAPMax; - - private SourceTimedConditionsListModel deathSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList deathSourceConditionsList; - private MyComboBox deathSourceConditionBox; - private JSpinner deathSourceConditionChance; - private JRadioButton deathSourceConditionClear; - private JRadioButton deathSourceConditionApply; - private JRadioButton deathSourceConditionImmunity; - private JSpinner deathSourceConditionMagnitude; - private JRadioButton deathSourceConditionTimed; - private JRadioButton deathSourceConditionForever; - private JSpinner deathSourceConditionDuration; - - private JPanel dialogueGraphPane; - private DialogueGraphView dialogueGraphView; - - public NPCEditor(NPC npc) { - super(npc, npc.getDesc(), npc.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - if (npc.dialogue != null) { - createDialogueGraphView(npc); - addEditorTab(dialogue_tree_id, dialogueGraphPane); - } - } - - public JPanel createDialogueGraphView(final NPC npc) { - dialogueGraphPane = new JPanel(); - dialogueGraphPane.setLayout(new BorderLayout()); - - dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); - dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); - - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - JButton reloadButton = new JButton("Refresh graph"); - buttonPane.add(reloadButton, JideBoxLayout.FIX); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - dialogueGraphPane.add(buttonPane, BorderLayout.NORTH); - - - reloadButton.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - reloadGraphView(npc); - } - }); - - return dialogueGraphPane; - } - - public void reloadGraphView(NPC npc) { - if (npc.dialogue != null) { - if (dialogueGraphPane != null) { - dialogueGraphPane.remove(dialogueGraphView); - dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); - dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); - dialogueGraphPane.revalidate(); - dialogueGraphPane.repaint(); - } else { - createDialogueGraphView(npc); - addEditorTab(dialogue_tree_id, dialogueGraphPane); - } - } else { - if (dialogueGraphPane != null) { - removeEditorTab(dialogue_tree_id); - dialogueGraphPane = null; - dialogueGraphView = null; - } - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public void insertFormViewDataField(JPanel pane) { - final NPC npc = (NPC) target; - - final FieldUpdateListener listener = new NPCFieldUpdater(); - - npcIcon = createButtonPane(pane, npc.getProject(), npc, NPC.class, npc.getImage(), Spritesheet.Category.monster, listener); - - idField = addTextField(pane, "Internal ID: ", npc.id, npc.writable, listener); - nameField = addTranslatableTextField(pane, "Display name: ", npc.name, npc.writable, listener); - spawnGroupField = addTextField(pane, "Spawn group ID: ", npc.spawngroup_id, npc.writable, listener); - factionField = addTextField(pane, "Faction ID: ", npc.faction_id, npc.writable, listener); - experienceField = addIntegerField(pane, "Experience reward: ", npc.getMonsterExperience(), false, false, listener); - dialogueBox = addDialogueBox(pane, npc.getProject(), "Initial phrase: ", npc.dialogue, npc.writable, listener); - droplistBox = addDroplistBox(pane, npc.getProject(), "Droplist / Shop inventory: ", npc.droplist, npc.writable, listener); - monsterClassBox = addEnumValueBox(pane, "Monster class: ", NPC.MonsterClass.values(), npc.monster_class, npc.writable, listener); - uniqueBox = addIntegerBasedCheckBox(pane, "Unique", npc.unique, npc.writable, listener); - moveTypeBox = addEnumValueBox(pane, "Movement type: ", NPC.MovementType.values(), npc.movement_type, npc.writable, listener); - combatTraitPane = new CollapsiblePanel("Combat traits: "); - combatTraitPane.setLayout(new JideBoxLayout(combatTraitPane, JideBoxLayout.PAGE_AXIS, 6)); - maxHP = addIntegerField(combatTraitPane, "Max HP: ", npc.max_hp, 1, false, npc.writable, listener); - maxAP = addIntegerField(combatTraitPane, "Max AP: ", npc.max_ap, 10, false, npc.writable, listener); - moveCost = addIntegerField(combatTraitPane, "Move cost: ", npc.move_cost, 10, false, npc.writable, listener); - atkDmgMin = addIntegerField(combatTraitPane, "Attack Damage min: ", npc.attack_damage_min, false, npc.writable, listener); - atkDmgMax = addIntegerField(combatTraitPane, "Attack Damage max: ", npc.attack_damage_max, false, npc.writable, listener); - atkCost = addIntegerField(combatTraitPane, "Attack cost: ", npc.attack_cost, 10, false, npc.writable, listener); - atkChance = addIntegerField(combatTraitPane, "Attack chance: ", npc.attack_chance, false, npc.writable, listener); - critSkill = addIntegerField(combatTraitPane, "Critical skill: ", npc.critical_skill, false, npc.writable, listener); - critMult = addDoubleField(combatTraitPane, "Critical multiplier: ", npc.critical_multiplier, npc.writable, listener); - blockChance = addIntegerField(combatTraitPane, "Block chance: ", npc.block_chance, false, npc.writable, listener); - dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = npc.hit_effect; - } - hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); - hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); - hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); - hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); - - CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); - hitSourceConditionsList = new JList(hitSourceConditionsListModel); - hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); - updateHitSourceTimedConditionEditorPane(hitSourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitSourceConditionsListModel.addItem(condition); - hitSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectSourceCondition != null) { - hitSourceConditionsListModel.removeItem(selectedHitEffectSourceCondition); - selectedHitEffectSourceCondition = null; - hitSourceConditionsList.clearSelection(); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsPane.add(hitSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); - } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); - hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); - hitTargetConditionsList = new JList(hitTargetConditionsListModel); - hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); - updateHitTargetTimedConditionEditorPane(hitTargetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitTargetConditionsListModel.addItem(condition); - hitTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectTargetCondition != null) { - hitTargetConditionsListModel.removeItem(selectedHitEffectTargetCondition); - selectedHitEffectTargetCondition = null; - hitTargetConditionsList.clearSelection(); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsPane.add(hitTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); - if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { - hitTargetConditionsPane.collapse(); - } - combatTraitPane.add(hitEffectPane, JideBoxLayout.FIX); - - hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); - hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.hit_received_effect == null) { - hitReceivedEffect = new Common.HitReceivedEffect(); - } else { - hitReceivedEffect = npc.hit_received_effect; - } - hitReceivedEffectHPMin = addIntegerField(hitReceivedEffectPane, "NPC HP bonus min: ", hitReceivedEffect.hp_boost_min, true, npc.writable, listener); - hitReceivedEffectHPMax = addIntegerField(hitReceivedEffectPane, "NPC HP bonus max: ", hitReceivedEffect.hp_boost_max, true, npc.writable, listener); - hitReceivedEffectAPMin = addIntegerField(hitReceivedEffectPane, "NPC AP bonus min: ", hitReceivedEffect.ap_boost_min, true, npc.writable, listener); - hitReceivedEffectAPMax = addIntegerField(hitReceivedEffectPane, "NPC AP bonus max: ", hitReceivedEffect.ap_boost_max, true, npc.writable, listener); - hitReceivedEffectHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, npc.writable, listener); - hitReceivedEffectHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, npc.writable, listener); - hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, npc.writable, listener); - hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, npc.writable, listener); - - CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to this NPC: "); - hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); - hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsListModel); - hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); - updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedSourceConditionsListModel.addItem(condition); - hitReceivedSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectSourceCondition != null) { - hitReceivedSourceConditionsListModel.removeItem(selectedHitReceivedEffectSourceCondition); - selectedHitReceivedEffectSourceCondition = null; - hitReceivedSourceConditionsList.clearSelection(); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_source == null || npc.hit_received_effect.conditions_source.isEmpty()) { - hitReceivedSourceConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); - hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); - hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsListModel); - hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); - updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedTargetConditionsListModel.addItem(condition); - hitReceivedTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectTargetCondition != null) { - hitReceivedTargetConditionsListModel.removeItem(selectedHitReceivedEffectTargetCondition); - selectedHitReceivedEffectTargetCondition = null; - hitReceivedTargetConditionsList.clearSelection(); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); - if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_target == null || npc.hit_received_effect.conditions_target.isEmpty()) { - hitReceivedTargetConditionsPane.collapse(); - } - combatTraitPane.add(hitReceivedEffectPane, JideBoxLayout.FIX); + private JButton npcIcon; + private JTextField idField; + private JTextField nameField; + private JTextField spawnGroupField; + private JTextField factionField; + private JSpinner experienceField; + private MyComboBox dialogueBox; + private MyComboBox droplistBox; + @SuppressWarnings("rawtypes") + private JComboBox monsterClassBox; + private IntegerBasedCheckBox uniqueBox; + @SuppressWarnings("rawtypes") + private JComboBox moveTypeBox; - deathEffectPane = new CollapsiblePanel("Effect when killed: "); - deathEffectPane.setLayout(new JideBoxLayout(deathEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.death_effect == null) { - deathEffect = new Common.DeathEffect(); - } else { - deathEffect = npc.death_effect; - } - deathEffectHPMin = addIntegerField(deathEffectPane, "Killer HP bonus min: ", deathEffect.hp_boost_min, true, npc.writable, listener); - deathEffectHPMax = addIntegerField(deathEffectPane, "Killer HP bonus max: ", deathEffect.hp_boost_max, true, npc.writable, listener); - deathEffectAPMin = addIntegerField(deathEffectPane, "Killer AP bonus min: ", deathEffect.ap_boost_min, true, npc.writable, listener); - deathEffectAPMax = addIntegerField(deathEffectPane, "Killer AP bonus max: ", deathEffect.ap_boost_max, true, npc.writable, listener); - - CollapsiblePanel deathSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the killer: "); - deathSourceConditionsPane.setLayout(new JideBoxLayout(deathSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); - deathSourceConditionsList = new JList(deathSourceConditionsListModel); - deathSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - deathSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - deathSourceConditionsPane.add(new JScrollPane(deathSourceConditionsList), JideBoxLayout.FIX); - final JPanel deathSourceTimedConditionsEditorPane = new JPanel(); - final JButton createDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deathSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedDeathEffectSourceCondition = (Common.TimedConditionEffect) deathSourceConditionsList.getSelectedValue(); - updateDeathSourceTimedConditionEditorPane(deathSourceTimedConditionsEditorPane, selectedDeathEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createDeathSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - deathSourceConditionsListModel.addItem(condition); - deathSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteDeathSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedDeathEffectSourceCondition != null) { - deathSourceConditionsListModel.removeItem(selectedDeathEffectSourceCondition); - selectedDeathEffectSourceCondition = null; - deathSourceConditionsList.clearSelection(); - listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createDeathSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteDeathSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - deathSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - deathSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(deathSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - deathSourceConditionsPane.add(deathSourceTimedConditionsEditorPane, JideBoxLayout.FIX); - if (npc.death_effect == null || npc.death_effect.conditions_source == null || npc.death_effect.conditions_source.isEmpty()) { - deathSourceConditionsPane.collapse(); - } - deathEffectPane.add(deathSourceConditionsPane, JideBoxLayout.FIX); - combatTraitPane.add(deathEffectPane, JideBoxLayout.FIX); - - - pane.add(combatTraitPane, JideBoxLayout.FIX); - } - - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitSourceConditionBox != null) { - removeElementListener(hitSourceConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); - - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); - - updateHitSourceTimedConditionWidgets(condition); - - hitSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); - } - }); - hitSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); - } - }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); - } - }); - - hitSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); - } - }); - hitSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + private CollapsiblePanel combatTraitPane; + private JSpinner maxHP; + private JSpinner maxAP; + private JSpinner moveCost; + private JSpinner atkDmgMin; + private JSpinner atkDmgMax; + private JSpinner atkCost; + private JSpinner atkChance; + private JSpinner critSkill; + private JSpinner critMult; + private JSpinner blockChance; + private JSpinner dmgRes; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); - - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); - } + private Common.HitEffect hitEffect; + private CollapsiblePanel hitEffectPane; + private JSpinner hitEffectHPMin; + private JSpinner hitEffectHPMax; + private JSpinner hitEffectAPMin; + private JSpinner hitEffectAPMax; - - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitTargetConditionBox != null) { - removeElementListener(hitTargetConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitTargetConditionClear, JideBoxLayout.FIX); - hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitTargetConditionApply); - radioEffectGroup.add(hitTargetConditionClear); - radioEffectGroup.add(hitTargetConditionImmunity); - - hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitTargetConditionTimed); - radioDurationGroup.add(hitTargetConditionForever); - - updateHitTargetTimedConditionWidgets(condition); - - hitTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); - } - }); - hitTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); - } - }); - hitTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); - } - }); - - hitTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); - } - }); - hitTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + private SourceTimedConditionsListModel hitSourceConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitSourceConditionsList; + private MyComboBox hitSourceConditionBox; + private JSpinner hitSourceConditionChance; + private JRadioButton hitSourceConditionClear; + private JRadioButton hitSourceConditionApply; + private JRadioButton hitSourceConditionImmunity; + private JSpinner hitSourceConditionMagnitude; + private JRadioButton hitSourceConditionTimed; + private JRadioButton hitSourceConditionForever; + private JSpinner hitSourceConditionDuration; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitTargetConditionClear.setSelected(clear); - hitTargetConditionApply.setSelected(!clear && !immunity); - hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitTargetConditionImmunity.setSelected(immunity); - - hitTargetConditionTimed.setSelected(!forever); - hitTargetConditionTimed.setEnabled(!clear); - hitTargetConditionDuration.setEnabled(!clear && !forever); - hitTargetConditionForever.setSelected(forever); - hitTargetConditionForever.setEnabled(!clear); - } - - - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedSourceConditionBox != null) { - removeElementListener(hitReceivedSourceConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); - hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); - hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedSourceConditionApply); - radioEffectGroup.add(hitReceivedSourceConditionClear); - radioEffectGroup.add(hitReceivedSourceConditionImmunity); - - hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); - hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedSourceConditionTimed); - radioDurationGroup.add(hitReceivedSourceConditionForever); - - updateHitReceivedSourceTimedConditionWidgets(condition); - - hitReceivedSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); - } - }); - hitReceivedSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); - } - }); - hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); - } - }); - - hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); - } - }); - hitReceivedSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + private TargetTimedConditionsListModel hitTargetConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitTargetConditionsList; + private MyComboBox hitTargetConditionBox; + private JSpinner hitTargetConditionChance; + private JRadioButton hitTargetConditionClear; + private JRadioButton hitTargetConditionApply; + private JRadioButton hitTargetConditionImmunity; + private JSpinner hitTargetConditionMagnitude; + private JRadioButton hitTargetConditionTimed; + private JRadioButton hitTargetConditionForever; + private JSpinner hitTargetConditionDuration; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedSourceConditionClear.setSelected(clear); - hitReceivedSourceConditionApply.setSelected(!clear && !immunity); - hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedSourceConditionImmunity.setSelected(immunity); - - hitReceivedSourceConditionTimed.setSelected(!forever); - hitReceivedSourceConditionTimed.setEnabled(!clear); - hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); - hitReceivedSourceConditionForever.setSelected(forever); - hitReceivedSourceConditionForever.setEnabled(!clear); - } + private Common.HitReceivedEffect hitReceivedEffect; + private CollapsiblePanel hitReceivedEffectPane; + private JSpinner hitReceivedEffectHPMin; + private JSpinner hitReceivedEffectHPMax; + private JSpinner hitReceivedEffectAPMin; + private JSpinner hitReceivedEffectAPMax; + private JSpinner hitReceivedEffectHPMinTarget; + private JSpinner hitReceivedEffectHPMaxTarget; + private JSpinner hitReceivedEffectAPMinTarget; + private JSpinner hitReceivedEffectAPMaxTarget; - - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedTargetConditionBox != null) { - removeElementListener(hitReceivedTargetConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); - hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); - hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedTargetConditionApply); - radioEffectGroup.add(hitReceivedTargetConditionClear); - radioEffectGroup.add(hitReceivedTargetConditionImmunity); - - hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); - hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedTargetConditionTimed); - radioDurationGroup.add(hitReceivedTargetConditionForever); - - updateHitReceivedTargetTimedConditionWidgets(condition); - - hitReceivedTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); - } - }); - hitReceivedTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); - } - }); - hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); - } - }); - - hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); - } - }); - hitReceivedTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + private SourceTimedConditionsListModel hitReceivedSourceConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedSourceConditionsList; + private MyComboBox hitReceivedSourceConditionBox; + private JSpinner hitReceivedSourceConditionChance; + private JRadioButton hitReceivedSourceConditionClear; + private JRadioButton hitReceivedSourceConditionApply; + private JRadioButton hitReceivedSourceConditionImmunity; + private JSpinner hitReceivedSourceConditionMagnitude; + private JRadioButton hitReceivedSourceConditionTimed; + private JRadioButton hitReceivedSourceConditionForever; + private JSpinner hitReceivedSourceConditionDuration; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - hitReceivedTargetConditionClear.setSelected(clear); - hitReceivedTargetConditionApply.setSelected(!clear && !immunity); - hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedTargetConditionImmunity.setSelected(immunity); - - hitReceivedTargetConditionTimed.setSelected(!forever); - hitReceivedTargetConditionTimed.setEnabled(!clear); - hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); - hitReceivedTargetConditionForever.setSelected(forever); - hitReceivedTargetConditionForever.setEnabled(!clear); - } - - public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (deathSourceConditionBox != null) { - removeElementListener(deathSourceConditionBox); - } - - boolean writable = ((NPC)target).writable; - Project proj = ((NPC)target).getProject(); - - deathSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - deathSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - deathSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(deathSourceConditionClear, JideBoxLayout.FIX); - deathSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(deathSourceConditionApply, JideBoxLayout.FIX); - deathSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - deathSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(deathSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(deathSourceConditionApply); - radioEffectGroup.add(deathSourceConditionClear); - radioEffectGroup.add(deathSourceConditionImmunity); - - deathSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(deathSourceConditionTimed, JideBoxLayout.FIX); - deathSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - deathSourceConditionForever = new JRadioButton("Forever"); - pane.add(deathSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(deathSourceConditionTimed); - radioDurationGroup.add(deathSourceConditionForever); - - updateDeathSourceTimedConditionWidgets(condition); - - deathSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionClear, new Boolean(deathSourceConditionClear.isSelected())); - } - }); - deathSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionApply, new Boolean(deathSourceConditionApply.isSelected())); - } - }); - deathSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionImmunity, new Boolean(deathSourceConditionImmunity.isSelected())); - } - }); - - deathSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionTimed, new Boolean(deathSourceConditionTimed.isSelected())); - } - }); - deathSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionForever, new Boolean(deathSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateDeathSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + private TargetTimedConditionsListModel hitReceivedTargetConditionsListModel; + @SuppressWarnings("rawtypes") + private JList hitReceivedTargetConditionsList; + private MyComboBox hitReceivedTargetConditionBox; + private JSpinner hitReceivedTargetConditionChance; + private JRadioButton hitReceivedTargetConditionClear; + private JRadioButton hitReceivedTargetConditionApply; + private JRadioButton hitReceivedTargetConditionImmunity; + private JSpinner hitReceivedTargetConditionMagnitude; + private JRadioButton hitReceivedTargetConditionTimed; + private JRadioButton hitReceivedTargetConditionForever; + private JSpinner hitReceivedTargetConditionDuration; - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; - - deathSourceConditionClear.setSelected(clear); - deathSourceConditionApply.setSelected(!clear && !immunity); - deathSourceConditionMagnitude.setEnabled(!clear && !immunity); - deathSourceConditionImmunity.setSelected(immunity); - - deathSourceConditionTimed.setSelected(!forever); - deathSourceConditionTimed.setEnabled(!clear); - deathSourceConditionDuration.setEnabled(!clear && !forever); - deathSourceConditionForever.setSelected(forever); - deathSourceConditionForever.setEnabled(!clear); - } + private Common.DeathEffect deathEffect; + private CollapsiblePanel deathEffectPane; + private JSpinner deathEffectHPMin; + private JSpinner deathEffectHPMax; + private JSpinner deathEffectAPMin; + private JSpinner deathEffectAPMax; - public static class TargetTimedConditionsListModel extends OrderedListenerListModel { - public TargetTimedConditionsListModel(Common.HitEffect effect) { - super(effect); - } + private SourceTimedConditionsListModel deathSourceConditionsListModel; + @SuppressWarnings("rawtypes") + private JList deathSourceConditionsList; + private MyComboBox deathSourceConditionBox; + private JSpinner deathSourceConditionChance; + private JRadioButton deathSourceConditionClear; + private JRadioButton deathSourceConditionApply; + private JRadioButton deathSourceConditionImmunity; + private JSpinner deathSourceConditionMagnitude; + private JRadioButton deathSourceConditionTimed; + private JRadioButton deathSourceConditionForever; + private JSpinner deathSourceConditionDuration; - @Override - protected List getItems() { - return source.conditions_target; - } + private JPanel dialogueGraphPane; + private DialogueGraphView dialogueGraphView; - @Override - protected void setItems(List items) { - source.conditions_target = items; - } - } - - public static class SourceTimedConditionsListModel extends OrderedListenerListModel { - public SourceTimedConditionsListModel(Common.DeathEffect effect) { - super(effect); - } + public NPCEditor(NPC npc) { + super(npc, npc.getDesc(), npc.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + if (npc.dialogue != null) { + createDialogueGraphView(npc); + addEditorTab(dialogue_tree_id, dialogueGraphPane); + } + } - @Override - protected List getItems() { - return source.conditions_source; - } + public JPanel createDialogueGraphView(final NPC npc) { + dialogueGraphPane = new JPanel(); + dialogueGraphPane.setLayout(new BorderLayout()); - @Override - protected void setItems(List items) { - source.conditions_source = items; - } - } - - public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); + dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; - - if (effect.condition != null) { + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); + JButton reloadButton = new JButton("Refresh graph"); + buttonPane.add(reloadButton, JideBoxLayout.FIX); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + dialogueGraphPane.add(buttonPane, BorderLayout.NORTH); - boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); - boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); - boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; - - if (clear) { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to clear actor condition "+effect.condition.getDesc()); - } else if (immunity) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText(effect.chance+"% chances to give immunity to "+effect.condition.getDesc()+(forever ? " forever" : " for "+effect.duration+" rounds")); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance+"% chances to give actor condition "+effect.condition.getDesc()+" x"+effect.magnitude+(forever ? " forever" : " for "+effect.duration+" rounds")); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - - public static boolean isNull(Common.HitEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - public static boolean isNull(Common.HitReceivedEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.ap_boost_min_target != null) return false; - if (effect.ap_boost_max_target != null) return false; - if (effect.hp_boost_min_target != null) return false; - if (effect.hp_boost_max_target != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - public static boolean isNull(Common.DeathEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - return true; - } - - public class NPCFieldUpdater implements FieldUpdateListener { - @Override - public void valueChanged(JComponent source, Object value) { - NPC npc = (NPC)target; - boolean updateHit, updateHitReceived, updateDeath; - updateHit = updateHitReceived = updateDeath = false; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - npc.id = (String) value; - NPCEditor.this.name = npc.getDesc(); - npc.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(NPCEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - npc.name = (String) value; - NPCEditor.this.name = npc.getDesc(); - npc.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(NPCEditor.this); - } else if (source == npcIcon) { - npc.icon_id = (String) value; - npc.childrenChanged(new ArrayList()); - NPCEditor.this.icon = new ImageIcon(npc.getProject().getIcon((String) value)); - ATContentStudio.frame.editorChanged(NPCEditor.this); - npcIcon.setIcon(new ImageIcon(npc.getProject().getImage((String) value))); - npcIcon.revalidate(); - npcIcon.repaint(); - } else if (source == spawnGroupField) { - npc.spawngroup_id = (String) value; - } else if (source == factionField) { - npc.faction_id = (String) value; - } else if (source == dialogueBox) { - if (npc.dialogue != null) { - npc.dialogue.removeBacklink(npc); - } - npc.dialogue = (Dialogue) value; - if (npc.dialogue != null) { - npc.dialogue_id =npc.dialogue.id; - npc.dialogue.addBacklink(npc); - } else { - npc.dialogue_id = null; - } - reloadGraphView(npc); - } else if (source == droplistBox) { - if (npc.droplist != null) { - npc.droplist.removeBacklink(npc); - } - npc.droplist = (Droplist) value; - if (npc.droplist != null) { - npc.droplist_id = npc.droplist.id; - npc.droplist.addBacklink(npc); - } else { - npc.droplist_id = null; - } - } else if (source == monsterClassBox) { - npc.monster_class = (NPC.MonsterClass) value; - } else if (source == uniqueBox) { - npc.unique = (Integer) value; - } else if (source == moveTypeBox) { - npc.movement_type = (NPC.MovementType) value; - } else if (source == maxHP) { - npc.max_hp = (Integer) value; - } else if (source == maxAP) { - npc.max_ap = (Integer) value; - } else if (source == moveCost) { - npc.move_cost = (Integer) value; - } else if (source == atkDmgMin) { - npc.attack_damage_min = (Integer) value; - } else if (source == atkDmgMax) { - npc.attack_damage_max = (Integer) value; - } else if (source == atkCost) { - npc.attack_cost = (Integer) value; - } else if (source == atkChance) { - npc.attack_chance = (Integer) value; - } else if (source == critSkill) { - npc.critical_skill = (Integer) value; - } else if (source == critMult) { - npc.critical_multiplier = (Double) value; - } else if (source == blockChance) { - npc.block_chance = (Integer) value; - } else if (source == dmgRes) { - npc.damage_resistance = (Integer) value; - } else if (source == hitEffectHPMin) { - hitEffect.hp_boost_min = (Integer) value; - updateHit = true; - } else if (source == hitEffectHPMax) { - hitEffect.hp_boost_max = (Integer) value; - updateHit = true; - } else if (source == hitEffectAPMin) { - hitEffect.ap_boost_min = (Integer) value; - updateHit = true; - } else if (source == hitEffectAPMax) { - hitEffect.ap_boost_max = (Integer) value; - updateHit = true; - } else if (source == hitSourceConditionsList) { - updateHit = true; - } else if (source == hitSourceConditionBox) { - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.removeBacklink(npc); - } - selectedHitEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.addBacklink(npc); - selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; - } else { - selectedHitEffectSourceCondition.condition_id = null; - } - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - } else if (source == hitSourceConditionClear && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionApply && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionImmunity && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionMagnitude) { - selectedHitEffectSourceCondition.magnitude = (Integer) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionTimed && (Boolean) value) { - selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionForever && (Boolean) value) { - selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionDuration) { - selectedHitEffectSourceCondition.duration = (Integer) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionChance) { - selectedHitEffectSourceCondition.chance = (Double) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - } else if (source == hitTargetConditionsList) { - updateHit = true; - } else if (source == hitTargetConditionBox) { - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition.removeBacklink(npc); - } - selectedHitEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; - selectedHitEffectTargetCondition.condition.addBacklink(npc); - } else { - selectedHitEffectTargetCondition.condition_id = null; - } - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - } else if (source == hitTargetConditionClear && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionApply && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionImmunity && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionMagnitude) { - selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionTimed && (Boolean) value) { - selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionForever && (Boolean) value) { - selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionDuration) { - selectedHitEffectTargetCondition.duration = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionChance) { - selectedHitEffectTargetCondition.chance = (Double) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - } else if (source == hitReceivedEffectHPMin) { - hitReceivedEffect.hp_boost_min = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMax) { - hitReceivedEffect.hp_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMin) { - hitReceivedEffect.ap_boost_min = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMax) { - hitReceivedEffect.ap_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMinTarget) { - hitReceivedEffect.hp_boost_min_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMaxTarget) { - hitReceivedEffect.hp_boost_max_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMinTarget) { - hitReceivedEffect.ap_boost_min_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMaxTarget) { - hitReceivedEffect.ap_boost_max_target = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionBox) { - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.removeBacklink(npc); - } - selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.addBacklink(npc); - selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; - } else { - selectedHitReceivedEffectSourceCondition.condition_id = null; - } - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = null; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionMagnitude) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionDuration) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionChance) { - selectedHitReceivedEffectSourceCondition.chance = (Double) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - } else if (source == hitReceivedTargetConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionBox) { - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition.removeBacklink(npc); - } - selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; - selectedHitReceivedEffectTargetCondition.condition.addBacklink(npc); - } else { - selectedHitReceivedEffectTargetCondition.condition_id = null; - } - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = null; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionMagnitude) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionDuration) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionChance) { - selectedHitReceivedEffectTargetCondition.chance = (Double) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - } else if (source == deathEffectHPMin) { - deathEffect.hp_boost_min = (Integer) value; - updateDeath = true; - } else if (source == deathEffectHPMax) { - deathEffect.hp_boost_max = (Integer) value; - updateDeath = true; - } else if (source == deathEffectAPMin) { - deathEffect.ap_boost_min = (Integer) value; - updateDeath = true; - } else if (source == deathEffectAPMax) { - deathEffect.ap_boost_max = (Integer) value; - updateDeath = true; - } else if (source == deathSourceConditionsList) { - updateDeath = true; - } else if (source == deathSourceConditionBox) { - if (selectedDeathEffectSourceCondition.condition != null) { - selectedDeathEffectSourceCondition.condition.removeBacklink(npc); - } - selectedDeathEffectSourceCondition.condition = (ActorCondition) value; - if (selectedDeathEffectSourceCondition.condition != null) { - selectedDeathEffectSourceCondition.condition.addBacklink(npc); - selectedDeathEffectSourceCondition.condition_id = selectedDeathEffectSourceCondition.condition.id; - } else { - selectedDeathEffectSourceCondition.condition_id = null; - } - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - } else if (source == deathSourceConditionClear && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedDeathEffectSourceCondition.duration = null; - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionApply && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = (Integer) deathSourceConditionMagnitude.getValue(); - selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionImmunity && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionMagnitude) { - selectedDeathEffectSourceCondition.magnitude = (Integer) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionTimed && (Boolean) value) { - selectedDeathEffectSourceCondition.duration = (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionForever && (Boolean) value) { - selectedDeathEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionDuration) { - selectedDeathEffectSourceCondition.duration = (Integer) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - updateDeath = true; - } else if (source == deathSourceConditionChance) { - selectedDeathEffectSourceCondition.chance = (Double) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - } + reloadButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + reloadGraphView(npc); + } + }); - if (updateHit) { - if (isNull(hitEffect)) { - npc.hit_effect = null; - } else { - npc.hit_effect = hitEffect; - } - } - if (updateHitReceived) { - if (isNull(hitReceivedEffect)) { - npc.hit_received_effect = null; - } else { - npc.hit_received_effect = hitReceivedEffect; - } - } - if (updateDeath) { - if (isNull(deathEffect)) { - npc.death_effect = null; - } else { - npc.death_effect = deathEffect; - } - } - - experienceField.setValue(npc.getMonsterExperience()); - - if (npc.state != GameDataElement.State.modified) { - npc.state = GameDataElement.State.modified; - NPCEditor.this.name = npc.getDesc(); - npc.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(NPCEditor.this); - } - updateJsonViewText(npc.toJsonString()); - - } - - } + return dialogueGraphPane; + } + + public void reloadGraphView(NPC npc) { + if (npc.dialogue != null) { + if (dialogueGraphPane != null) { + dialogueGraphPane.remove(dialogueGraphView); + dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); + dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); + dialogueGraphPane.revalidate(); + dialogueGraphPane.repaint(); + } else { + createDialogueGraphView(npc); + addEditorTab(dialogue_tree_id, dialogueGraphPane); + } + } else { + if (dialogueGraphPane != null) { + removeEditorTab(dialogue_tree_id); + dialogueGraphPane = null; + dialogueGraphView = null; + } + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public void insertFormViewDataField(JPanel pane) { + final NPC npc = (NPC) target; + + final FieldUpdateListener listener = new NPCFieldUpdater(); + + npcIcon = createButtonPane(pane, npc.getProject(), npc, NPC.class, npc.getImage(), Spritesheet.Category.monster, listener); + + idField = addTextField(pane, "Internal ID: ", npc.id, npc.writable, listener); + nameField = addTranslatableTextField(pane, "Display name: ", npc.name, npc.writable, listener); + spawnGroupField = addTextField(pane, "Spawn group ID: ", npc.spawngroup_id, npc.writable, listener); + factionField = addTextField(pane, "Faction ID: ", npc.faction_id, npc.writable, listener); + experienceField = addIntegerField(pane, "Experience reward: ", npc.getMonsterExperience(), false, false, listener); + dialogueBox = addDialogueBox(pane, npc.getProject(), "Initial phrase: ", npc.dialogue, npc.writable, listener); + droplistBox = addDroplistBox(pane, npc.getProject(), "Droplist / Shop inventory: ", npc.droplist, npc.writable, listener); + monsterClassBox = addEnumValueBox(pane, "Monster class: ", NPC.MonsterClass.values(), npc.monster_class, npc.writable, listener); + uniqueBox = addIntegerBasedCheckBox(pane, "Unique", npc.unique, npc.writable, listener); + moveTypeBox = addEnumValueBox(pane, "Movement type: ", NPC.MovementType.values(), npc.movement_type, npc.writable, listener); + combatTraitPane = new CollapsiblePanel("Combat traits: "); + combatTraitPane.setLayout(new JideBoxLayout(combatTraitPane, JideBoxLayout.PAGE_AXIS, 6)); + maxHP = addIntegerField(combatTraitPane, "Max HP: ", npc.max_hp, 1, false, npc.writable, listener); + maxAP = addIntegerField(combatTraitPane, "Max AP: ", npc.max_ap, 10, false, npc.writable, listener); + moveCost = addIntegerField(combatTraitPane, "Move cost: ", npc.move_cost, 10, false, npc.writable, listener); + atkDmgMin = addIntegerField(combatTraitPane, "Attack Damage min: ", npc.attack_damage_min, false, npc.writable, listener); + atkDmgMax = addIntegerField(combatTraitPane, "Attack Damage max: ", npc.attack_damage_max, false, npc.writable, listener); + atkCost = addIntegerField(combatTraitPane, "Attack cost: ", npc.attack_cost, 10, false, npc.writable, listener); + atkChance = addIntegerField(combatTraitPane, "Attack chance: ", npc.attack_chance, false, npc.writable, listener); + critSkill = addIntegerField(combatTraitPane, "Critical skill: ", npc.critical_skill, false, npc.writable, listener); + critMult = addDoubleField(combatTraitPane, "Critical multiplier: ", npc.critical_multiplier, npc.writable, listener); + blockChance = addIntegerField(combatTraitPane, "Block chance: ", npc.block_chance, false, npc.writable, listener); + dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); + hitEffectPane = new CollapsiblePanel("Effect on every hit: "); + hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.hit_effect == null) { + hitEffect = new Common.HitEffect(); + } else { + hitEffect = npc.hit_effect; + } + hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); + hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); + hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); + hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); + + CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); + hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); + hitSourceConditionsList = new JList(hitSourceConditionsListModel); + hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); + final JPanel hitSourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); + updateHitSourceTimedConditionEditorPane(hitSourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitSourceConditionsListModel.addItem(condition); + hitSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectSourceCondition != null) { + hitSourceConditionsListModel.removeItem(selectedHitEffectSourceCondition); + selectedHitEffectSourceCondition = null; + hitSourceConditionsList.clearSelection(); + listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitSourceConditionsPane.add(hitSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { + hitSourceConditionsPane.collapse(); + } + hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); + hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); + hitTargetConditionsList = new JList(hitTargetConditionsListModel); + hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); + final JPanel hitTargetTimedConditionsEditorPane = new JPanel(); + final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); + updateHitTargetTimedConditionEditorPane(hitTargetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitTargetConditionsListModel.addItem(condition); + hitTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitEffectTargetCondition != null) { + hitTargetConditionsListModel.removeItem(selectedHitEffectTargetCondition); + selectedHitEffectTargetCondition = null; + hitTargetConditionsList.clearSelection(); + listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitTargetConditionsPane.add(hitTargetTimedConditionsEditorPane, JideBoxLayout.FIX); + hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); + if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { + hitTargetConditionsPane.collapse(); + } + combatTraitPane.add(hitEffectPane, JideBoxLayout.FIX); + + hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); + hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.hit_received_effect == null) { + hitReceivedEffect = new Common.HitReceivedEffect(); + } else { + hitReceivedEffect = npc.hit_received_effect; + } + hitReceivedEffectHPMin = addIntegerField(hitReceivedEffectPane, "NPC HP bonus min: ", hitReceivedEffect.hp_boost_min, true, npc.writable, listener); + hitReceivedEffectHPMax = addIntegerField(hitReceivedEffectPane, "NPC HP bonus max: ", hitReceivedEffect.hp_boost_max, true, npc.writable, listener); + hitReceivedEffectAPMin = addIntegerField(hitReceivedEffectPane, "NPC AP bonus min: ", hitReceivedEffect.ap_boost_min, true, npc.writable, listener); + hitReceivedEffectAPMax = addIntegerField(hitReceivedEffectPane, "NPC AP bonus max: ", hitReceivedEffect.ap_boost_max, true, npc.writable, listener); + hitReceivedEffectHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, npc.writable, listener); + hitReceivedEffectHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, npc.writable, listener); + hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, npc.writable, listener); + hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, npc.writable, listener); + + CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to this NPC: "); + hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); + hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsListModel); + hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); + updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedSourceConditionsListModel.addItem(condition); + hitReceivedSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectSourceCondition != null) { + hitReceivedSourceConditionsListModel.removeItem(selectedHitReceivedEffectSourceCondition); + selectedHitReceivedEffectSourceCondition = null; + hitReceivedSourceConditionsList.clearSelection(); + listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_source == null || npc.hit_received_effect.conditions_source.isEmpty()) { + hitReceivedSourceConditionsPane.collapse(); + } + hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); + final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); + hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); + hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsListModel); + hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); + final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); + final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); + updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + hitReceivedTargetConditionsListModel.addItem(condition); + hitReceivedTargetConditionsList.setSelectedValue(condition, true); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedHitReceivedEffectTargetCondition != null) { + hitReceivedTargetConditionsListModel.removeItem(selectedHitReceivedEffectTargetCondition); + selectedHitReceivedEffectTargetCondition = null; + hitReceivedTargetConditionsList.clearSelection(); + listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); + hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); + if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_target == null || npc.hit_received_effect.conditions_target.isEmpty()) { + hitReceivedTargetConditionsPane.collapse(); + } + combatTraitPane.add(hitReceivedEffectPane, JideBoxLayout.FIX); + + deathEffectPane = new CollapsiblePanel("Effect when killed: "); + deathEffectPane.setLayout(new JideBoxLayout(deathEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.death_effect == null) { + deathEffect = new Common.DeathEffect(); + } else { + deathEffect = npc.death_effect; + } + deathEffectHPMin = addIntegerField(deathEffectPane, "Killer HP bonus min: ", deathEffect.hp_boost_min, true, npc.writable, listener); + deathEffectHPMax = addIntegerField(deathEffectPane, "Killer HP bonus max: ", deathEffect.hp_boost_max, true, npc.writable, listener); + deathEffectAPMin = addIntegerField(deathEffectPane, "Killer AP bonus min: ", deathEffect.ap_boost_min, true, npc.writable, listener); + deathEffectAPMax = addIntegerField(deathEffectPane, "Killer AP bonus max: ", deathEffect.ap_boost_max, true, npc.writable, listener); + + CollapsiblePanel deathSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the killer: "); + deathSourceConditionsPane.setLayout(new JideBoxLayout(deathSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); + deathSourceConditionsList = new JList(deathSourceConditionsListModel); + deathSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); + deathSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + deathSourceConditionsPane.add(new JScrollPane(deathSourceConditionsList), JideBoxLayout.FIX); + final JPanel deathSourceTimedConditionsEditorPane = new JPanel(); + final JButton createDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + deathSourceConditionsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedDeathEffectSourceCondition = (Common.TimedConditionEffect) deathSourceConditionsList.getSelectedValue(); + updateDeathSourceTimedConditionEditorPane(deathSourceTimedConditionsEditorPane, selectedDeathEffectSourceCondition, listener); + } + }); + if (npc.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createDeathSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); + deathSourceConditionsListModel.addItem(condition); + deathSourceConditionsList.setSelectedValue(condition, true); + listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteDeathSourceCondition.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedDeathEffectSourceCondition != null) { + deathSourceConditionsListModel.removeItem(selectedDeathEffectSourceCondition); + selectedDeathEffectSourceCondition = null; + deathSourceConditionsList.clearSelection(); + listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + + listButtonsPane.add(createDeathSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(deleteDeathSourceCondition, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + deathSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); + } + deathSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(deathSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); + deathSourceConditionsPane.add(deathSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + if (npc.death_effect == null || npc.death_effect.conditions_source == null || npc.death_effect.conditions_source.isEmpty()) { + deathSourceConditionsPane.collapse(); + } + deathEffectPane.add(deathSourceConditionsPane, JideBoxLayout.FIX); + combatTraitPane.add(deathEffectPane, JideBoxLayout.FIX); + + + pane.add(combatTraitPane, JideBoxLayout.FIX); + } + + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitSourceConditionBox != null) { + removeElementListener(hitSourceConditionBox); + } + + boolean writable = ((NPC) target).writable; + Project proj = ((NPC) target).getProject(); + + hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitSourceConditionClear, JideBoxLayout.FIX); + hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitSourceConditionApply, JideBoxLayout.FIX); + hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitSourceConditionApply); + radioEffectGroup.add(hitSourceConditionClear); + radioEffectGroup.add(hitSourceConditionImmunity); + + hitSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); + hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitSourceConditionTimed); + radioDurationGroup.add(hitSourceConditionForever); + + updateHitSourceTimedConditionWidgets(condition); + + hitSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + } + }); + hitSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + } + }); + hitSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + } + }); + + hitSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + } + }); + hitSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitSourceConditionClear.setSelected(clear); + hitSourceConditionApply.setSelected(!clear && !immunity); + hitSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitSourceConditionImmunity.setSelected(immunity); + + hitSourceConditionTimed.setSelected(!forever); + hitSourceConditionTimed.setEnabled(!clear); + hitSourceConditionDuration.setEnabled(!clear && !forever); + hitSourceConditionForever.setSelected(forever); + hitSourceConditionForever.setEnabled(!clear); + } + + + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitTargetConditionBox != null) { + removeElementListener(hitTargetConditionBox); + } + + boolean writable = ((NPC) target).writable; + Project proj = ((NPC) target).getProject(); + + hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitTargetConditionClear, JideBoxLayout.FIX); + hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitTargetConditionApply, JideBoxLayout.FIX); + hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitTargetConditionApply); + radioEffectGroup.add(hitTargetConditionClear); + radioEffectGroup.add(hitTargetConditionImmunity); + + hitTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); + hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitTargetConditionTimed); + radioDurationGroup.add(hitTargetConditionForever); + + updateHitTargetTimedConditionWidgets(condition); + + hitTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + } + }); + hitTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + } + }); + hitTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + } + }); + + hitTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + } + }); + hitTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitTargetConditionClear.setSelected(clear); + hitTargetConditionApply.setSelected(!clear && !immunity); + hitTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitTargetConditionImmunity.setSelected(immunity); + + hitTargetConditionTimed.setSelected(!forever); + hitTargetConditionTimed.setEnabled(!clear); + hitTargetConditionDuration.setEnabled(!clear && !forever); + hitTargetConditionForever.setSelected(forever); + hitTargetConditionForever.setEnabled(!clear); + } + + + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedSourceConditionBox != null) { + removeElementListener(hitReceivedSourceConditionBox); + } + + boolean writable = ((NPC) target).writable; + Project proj = ((NPC) target).getProject(); + + hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); + hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); + hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedSourceConditionApply); + radioEffectGroup.add(hitReceivedSourceConditionClear); + radioEffectGroup.add(hitReceivedSourceConditionImmunity); + + hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); + hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedSourceConditionTimed); + radioDurationGroup.add(hitReceivedSourceConditionForever); + + updateHitReceivedSourceTimedConditionWidgets(condition); + + hitReceivedSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); + } + }); + hitReceivedSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); + } + }); + hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); + } + }); + + hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); + } + }); + hitReceivedSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedSourceConditionClear.setSelected(clear); + hitReceivedSourceConditionApply.setSelected(!clear && !immunity); + hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedSourceConditionImmunity.setSelected(immunity); + + hitReceivedSourceConditionTimed.setSelected(!forever); + hitReceivedSourceConditionTimed.setEnabled(!clear); + hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); + hitReceivedSourceConditionForever.setSelected(forever); + hitReceivedSourceConditionForever.setEnabled(!clear); + } + + + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (hitReceivedTargetConditionBox != null) { + removeElementListener(hitReceivedTargetConditionBox); + } + + boolean writable = ((NPC) target).writable; + Project proj = ((NPC) target).getProject(); + + hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); + hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); + hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitReceivedTargetConditionApply); + radioEffectGroup.add(hitReceivedTargetConditionClear); + radioEffectGroup.add(hitReceivedTargetConditionImmunity); + + hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); + hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitReceivedTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitReceivedTargetConditionTimed); + radioDurationGroup.add(hitReceivedTargetConditionForever); + + updateHitReceivedTargetTimedConditionWidgets(condition); + + hitReceivedTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); + } + }); + hitReceivedTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); + } + }); + hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); + } + }); + + hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); + } + }); + hitReceivedTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + hitReceivedTargetConditionClear.setSelected(clear); + hitReceivedTargetConditionApply.setSelected(!clear && !immunity); + hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitReceivedTargetConditionImmunity.setSelected(immunity); + + hitReceivedTargetConditionTimed.setSelected(!forever); + hitReceivedTargetConditionTimed.setEnabled(!clear); + hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); + hitReceivedTargetConditionForever.setSelected(forever); + hitReceivedTargetConditionForever.setEnabled(!clear); + } + + public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + pane.removeAll(); + if (deathSourceConditionBox != null) { + removeElementListener(deathSourceConditionBox); + } + + boolean writable = ((NPC) target).writable; + Project proj = ((NPC) target).getProject(); + + deathSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + deathSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + deathSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(deathSourceConditionClear, JideBoxLayout.FIX); + deathSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(deathSourceConditionApply, JideBoxLayout.FIX); + deathSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + deathSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(deathSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(deathSourceConditionApply); + radioEffectGroup.add(deathSourceConditionClear); + radioEffectGroup.add(deathSourceConditionImmunity); + + deathSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(deathSourceConditionTimed, JideBoxLayout.FIX); + deathSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + deathSourceConditionForever = new JRadioButton("Forever"); + pane.add(deathSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(deathSourceConditionTimed); + radioDurationGroup.add(deathSourceConditionForever); + + updateDeathSourceTimedConditionWidgets(condition); + + deathSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionClear, new Boolean(deathSourceConditionClear.isSelected())); + } + }); + deathSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionApply, new Boolean(deathSourceConditionApply.isSelected())); + } + }); + deathSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionImmunity, new Boolean(deathSourceConditionImmunity.isSelected())); + } + }); + + deathSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionTimed, new Boolean(deathSourceConditionTimed.isSelected())); + } + }); + deathSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(deathSourceConditionForever, new Boolean(deathSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public void updateDeathSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + + boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); + boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); + boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + + deathSourceConditionClear.setSelected(clear); + deathSourceConditionApply.setSelected(!clear && !immunity); + deathSourceConditionMagnitude.setEnabled(!clear && !immunity); + deathSourceConditionImmunity.setSelected(immunity); + + deathSourceConditionTimed.setSelected(!forever); + deathSourceConditionTimed.setEnabled(!clear); + deathSourceConditionDuration.setEnabled(!clear && !forever); + deathSourceConditionForever.setSelected(forever); + deathSourceConditionForever.setEnabled(!clear); + } + + public static class TargetTimedConditionsListModel extends OrderedListenerListModel { + public TargetTimedConditionsListModel(Common.HitEffect effect) { + super(effect); + } + + @Override + protected List getItems() { + return source.conditions_target; + } + + @Override + protected void setItems(List items) { + source.conditions_target = items; + } + } + + public static class SourceTimedConditionsListModel extends OrderedListenerListModel { + public SourceTimedConditionsListModel(Common.DeathEffect effect) { + super(effect); + } + + @Override + protected List getItems() { + return source.conditions_source; + } + + @Override + protected void setItems(List items) { + source.conditions_source = items; + } + } + + public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; + + if (effect.condition != null) { + + boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); + boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); + boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; + + if (clear) { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance + "% chances to clear actor condition " + effect.condition.getDesc()); + } else if (immunity) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText(effect.chance + "% chances to give immunity to " + effect.condition.getDesc() + (forever ? " forever" : " for " + effect.duration + " rounds")); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } + + public static boolean isNull(Common.HitEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + public static boolean isNull(Common.HitReceivedEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.ap_boost_min_target != null) return false; + if (effect.ap_boost_max_target != null) return false; + if (effect.hp_boost_min_target != null) return false; + if (effect.hp_boost_max_target != null) return false; + if (effect.conditions_source != null) return false; + if (effect.conditions_target != null) return false; + return true; + } + + public static boolean isNull(Common.DeathEffect effect) { + if (effect.ap_boost_min != null) return false; + if (effect.ap_boost_max != null) return false; + if (effect.hp_boost_min != null) return false; + if (effect.hp_boost_max != null) return false; + if (effect.conditions_source != null) return false; + return true; + } + + public class NPCFieldUpdater implements FieldUpdateListener { + + @Override + public void valueChanged(JComponent source, Object value) { + NPC npc = (NPC) target; + boolean updateHit, updateHitReceived, updateDeath; + updateHit = updateHitReceived = updateDeath = false; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + npc.id = (String) value; + NPCEditor.this.name = npc.getDesc(); + npc.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(NPCEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + npc.name = (String) value; + NPCEditor.this.name = npc.getDesc(); + npc.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(NPCEditor.this); + } else if (source == npcIcon) { + npc.icon_id = (String) value; + npc.childrenChanged(new ArrayList()); + NPCEditor.this.icon = new ImageIcon(npc.getProject().getIcon((String) value)); + ATContentStudio.frame.editorChanged(NPCEditor.this); + npcIcon.setIcon(new ImageIcon(npc.getProject().getImage((String) value))); + npcIcon.revalidate(); + npcIcon.repaint(); + } else if (source == spawnGroupField) { + npc.spawngroup_id = (String) value; + } else if (source == factionField) { + npc.faction_id = (String) value; + } else if (source == dialogueBox) { + if (npc.dialogue != null) { + npc.dialogue.removeBacklink(npc); + } + npc.dialogue = (Dialogue) value; + if (npc.dialogue != null) { + npc.dialogue_id = npc.dialogue.id; + npc.dialogue.addBacklink(npc); + } else { + npc.dialogue_id = null; + } + reloadGraphView(npc); + } else if (source == droplistBox) { + if (npc.droplist != null) { + npc.droplist.removeBacklink(npc); + } + npc.droplist = (Droplist) value; + if (npc.droplist != null) { + npc.droplist_id = npc.droplist.id; + npc.droplist.addBacklink(npc); + } else { + npc.droplist_id = null; + } + } else if (source == monsterClassBox) { + npc.monster_class = (NPC.MonsterClass) value; + } else if (source == uniqueBox) { + npc.unique = (Integer) value; + } else if (source == moveTypeBox) { + npc.movement_type = (NPC.MovementType) value; + } else if (source == maxHP) { + npc.max_hp = (Integer) value; + } else if (source == maxAP) { + npc.max_ap = (Integer) value; + } else if (source == moveCost) { + npc.move_cost = (Integer) value; + } else if (source == atkDmgMin) { + npc.attack_damage_min = (Integer) value; + } else if (source == atkDmgMax) { + npc.attack_damage_max = (Integer) value; + } else if (source == atkCost) { + npc.attack_cost = (Integer) value; + } else if (source == atkChance) { + npc.attack_chance = (Integer) value; + } else if (source == critSkill) { + npc.critical_skill = (Integer) value; + } else if (source == critMult) { + npc.critical_multiplier = (Double) value; + } else if (source == blockChance) { + npc.block_chance = (Integer) value; + } else if (source == dmgRes) { + npc.damage_resistance = (Integer) value; + } else if (source == hitEffectHPMin) { + hitEffect.hp_boost_min = (Integer) value; + updateHit = true; + } else if (source == hitEffectHPMax) { + hitEffect.hp_boost_max = (Integer) value; + updateHit = true; + } else if (source == hitEffectAPMin) { + hitEffect.ap_boost_min = (Integer) value; + updateHit = true; + } else if (source == hitEffectAPMax) { + hitEffect.ap_boost_max = (Integer) value; + updateHit = true; + } else if (source == hitSourceConditionsList) { + updateHit = true; + } else if (source == hitSourceConditionBox) { + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition.removeBacklink(npc); + } + selectedHitEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitEffectSourceCondition.condition != null) { + selectedHitEffectSourceCondition.condition.addBacklink(npc); + selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; + } else { + selectedHitEffectSourceCondition.condition_id = null; + } + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + } else if (source == hitSourceConditionClear && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = null; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionApply && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionImmunity && (Boolean) value) { + selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionMagnitude) { + selectedHitEffectSourceCondition.magnitude = (Integer) value; + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionTimed && (Boolean) value) { + selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); + if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectSourceCondition.duration = 1; + } + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionForever && (Boolean) value) { + selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionDuration) { + selectedHitEffectSourceCondition.duration = (Integer) value; + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHit = true; + } else if (source == hitSourceConditionChance) { + selectedHitEffectSourceCondition.chance = (Double) value; + hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + } else if (source == hitTargetConditionsList) { + updateHit = true; + } else if (source == hitTargetConditionBox) { + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition.removeBacklink(npc); + } + selectedHitEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; + selectedHitEffectTargetCondition.condition.addBacklink(npc); + } else { + selectedHitEffectTargetCondition.condition_id = null; + } + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitTargetConditionClear && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = null; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionApply && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionImmunity && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionMagnitude) { + selectedHitEffectTargetCondition.magnitude = (Integer) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionTimed && (Boolean) value) { + selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionForever && (Boolean) value) { + selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionDuration) { + selectedHitEffectTargetCondition.duration = (Integer) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionChance) { + selectedHitEffectTargetCondition.chance = (Double) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitReceivedEffectHPMin) { + hitReceivedEffect.hp_boost_min = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectHPMax) { + hitReceivedEffect.hp_boost_max = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMin) { + hitReceivedEffect.ap_boost_min = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMax) { + hitReceivedEffect.ap_boost_max = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectHPMinTarget) { + hitReceivedEffect.hp_boost_min_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectHPMaxTarget) { + hitReceivedEffect.hp_boost_max_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMinTarget) { + hitReceivedEffect.ap_boost_min_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMaxTarget) { + hitReceivedEffect.ap_boost_max_target = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionBox) { + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition.removeBacklink(npc); + } + selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectSourceCondition.condition != null) { + selectedHitReceivedEffectSourceCondition.condition.addBacklink(npc); + selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; + } else { + selectedHitReceivedEffectSourceCondition.condition_id = null; + } + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = null; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionMagnitude) { + selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); + if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectSourceCondition.duration = 1; + } + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { + selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionDuration) { + selectedHitReceivedEffectSourceCondition.duration = (Integer) value; + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateHitReceived = true; + } else if (source == hitReceivedSourceConditionChance) { + selectedHitReceivedEffectSourceCondition.chance = (Double) value; + hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); + } else if (source == hitReceivedTargetConditionsList) { + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionBox) { + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition.removeBacklink(npc); + } + selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; + if (selectedHitReceivedEffectTargetCondition.condition != null) { + selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; + selectedHitReceivedEffectTargetCondition.condition.addBacklink(npc); + } else { + selectedHitReceivedEffectTargetCondition.condition_id = null; + } + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = null; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionMagnitude) { + selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); + if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitReceivedEffectTargetCondition.duration = 1; + } + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { + selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionDuration) { + selectedHitReceivedEffectTargetCondition.duration = (Integer) value; + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateHitReceived = true; + } else if (source == hitReceivedTargetConditionChance) { + selectedHitReceivedEffectTargetCondition.chance = (Double) value; + hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + } else if (source == deathEffectHPMin) { + deathEffect.hp_boost_min = (Integer) value; + updateDeath = true; + } else if (source == deathEffectHPMax) { + deathEffect.hp_boost_max = (Integer) value; + updateDeath = true; + } else if (source == deathEffectAPMin) { + deathEffect.ap_boost_min = (Integer) value; + updateDeath = true; + } else if (source == deathEffectAPMax) { + deathEffect.ap_boost_max = (Integer) value; + updateDeath = true; + } else if (source == deathSourceConditionsList) { + updateDeath = true; + } else if (source == deathSourceConditionBox) { + if (selectedDeathEffectSourceCondition.condition != null) { + selectedDeathEffectSourceCondition.condition.removeBacklink(npc); + } + selectedDeathEffectSourceCondition.condition = (ActorCondition) value; + if (selectedDeathEffectSourceCondition.condition != null) { + selectedDeathEffectSourceCondition.condition.addBacklink(npc); + selectedDeathEffectSourceCondition.condition_id = selectedDeathEffectSourceCondition.condition.id; + } else { + selectedDeathEffectSourceCondition.condition_id = null; + } + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } else if (source == deathSourceConditionClear && (Boolean) value) { + selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedDeathEffectSourceCondition.duration = null; + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionApply && (Boolean) value) { + selectedDeathEffectSourceCondition.magnitude = (Integer) deathSourceConditionMagnitude.getValue(); + selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); + if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedDeathEffectSourceCondition.duration = 1; + } + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionImmunity && (Boolean) value) { + selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); + if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedDeathEffectSourceCondition.duration = 1; + } + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionMagnitude) { + selectedDeathEffectSourceCondition.magnitude = (Integer) value; + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionTimed && (Boolean) value) { + selectedDeathEffectSourceCondition.duration = (Integer) deathSourceConditionDuration.getValue(); + if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedDeathEffectSourceCondition.duration = 1; + } + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionForever && (Boolean) value) { + selectedDeathEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionDuration) { + selectedDeathEffectSourceCondition.duration = (Integer) value; + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeath = true; + } else if (source == deathSourceConditionChance) { + selectedDeathEffectSourceCondition.chance = (Double) value; + deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } + + if (updateHit) { + if (isNull(hitEffect)) { + npc.hit_effect = null; + } else { + npc.hit_effect = hitEffect; + } + } + if (updateHitReceived) { + if (isNull(hitReceivedEffect)) { + npc.hit_received_effect = null; + } else { + npc.hit_received_effect = hitReceivedEffect; + } + } + if (updateDeath) { + if (isNull(deathEffect)) { + npc.death_effect = null; + } else { + npc.death_effect = deathEffect; + } + } + + experienceField.setValue(npc.getMonsterExperience()); + + if (npc.state != GameDataElement.State.modified) { + npc.state = GameDataElement.State.modified; + NPCEditor.this.name = npc.getDesc(); + npc.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(NPCEditor.this); + } + updateJsonViewText(npc.toJsonString()); + + } + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java index 4a90c85..5f43fb8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java @@ -1,26 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; @@ -29,243 +8,251 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; import com.gpl.rpg.atcontentstudio.ui.*; import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.ArrayList; +import java.util.List; + public class QuestEditor extends JSONElementEditor { - private static final long serialVersionUID = 5701667955210615366L; + private static final long serialVersionUID = 5701667955210615366L; - private static final String form_view_id = "Form"; - private static final String json_view_id = "JSON"; - - private QuestStage selectedStage = null; - - private JTextField idField; - private JTextField nameField; - private IntegerBasedCheckBox visibleBox; - private StagesListModel stagesListModel; - private JList stagesList; - -// private JPanel stagesParamPane; - private JSpinner progressField; - private JTextArea logTextField; - private JSpinner xpRewardField; - private IntegerBasedCheckBox finishQuestBox; - - - - public QuestEditor(Quest quest) { - super(quest, quest.getDesc(), quest.getIcon()); - addEditorTab(form_view_id, getFormView()); - addEditorTab(json_view_id, getJSONView()); - } + private static final String form_view_id = "Form"; + private static final String json_view_id = "JSON"; - public void insertFormViewDataField(JPanel pane) { - final Quest quest = ((Quest)target); + private QuestStage selectedStage = null; - final FieldUpdateListener listener = new QuestFieldUpdater(); - - createButtonPane(pane, quest.getProject(), quest, Quest.class, quest.getImage(), null, listener); - + private JTextField idField; + private JTextField nameField; + private IntegerBasedCheckBox visibleBox; + private StagesListModel stagesListModel; + private JList stagesList; - idField = addTextField(pane, "Internal ID: ", quest.id, quest.writable, listener); - nameField = addTranslatableTextField(pane, "Quest Name: ", quest.name, quest.writable, listener); - visibleBox = addIntegerBasedCheckBox(pane, "Visible in quest log", quest.visible_in_log, quest.writable, listener); - - CollapsiblePanel stagesPane = new CollapsiblePanel("Quest stages: "); - stagesPane.setLayout(new JideBoxLayout(stagesPane, JideBoxLayout.PAGE_AXIS)); - stagesListModel = new StagesListModel(quest); - stagesList = new JList(stagesListModel); - stagesList.setCellRenderer(new StagesCellRenderer()); - stagesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - stagesPane.add(new JScrollPane(stagesList), JideBoxLayout.FIX); - final JPanel stagesEditorPane = new JPanel(); - final JButton createStage = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteStage = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - final JButton moveStageUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); - final JButton moveStageDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); - deleteStage.setEnabled(false); - moveStageUp.setEnabled(false); - moveStageDown.setEnabled(false); - stagesList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedStage = (QuestStage) stagesList.getSelectedValue(); - if (selectedStage != null) { - deleteStage.setEnabled(true); - moveStageUp.setEnabled(stagesList.getSelectedIndex() > 0); - moveStageDown.setEnabled(stagesList.getSelectedIndex() < (stagesListModel.getSize() - 1)); - } else { - deleteStage.setEnabled(false); - moveStageUp.setEnabled(false); - moveStageDown.setEnabled(false); - } - updateStageEditorPane(stagesEditorPane, selectedStage, listener); - } - }); - if (quest.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createStage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - QuestStage stage = new QuestStage(quest); - stagesListModel.addItem(stage); - stagesList.setSelectedValue(stage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteStage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.removeItem(selectedStage); - selectedStage = null; - stagesList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveStageUp.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.moveUp(selectedStage); - stagesList.setSelectedValue(selectedStage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveStageDown.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.moveDown(selectedStage); - stagesList.setSelectedValue(selectedStage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createStage, JideBoxLayout.FIX); - listButtonsPane.add(deleteStage, JideBoxLayout.FIX); - listButtonsPane.add(moveStageUp, JideBoxLayout.FIX); - listButtonsPane.add(moveStageDown, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - stagesPane.add(listButtonsPane, JideBoxLayout.FIX); - } - if (quest.stages == null || quest.stages.isEmpty()) { - stagesPane.collapse(); - } - stagesEditorPane.setLayout(new JideBoxLayout(stagesEditorPane, JideBoxLayout.PAGE_AXIS)); - stagesPane.add(stagesEditorPane, JideBoxLayout.FIX); - pane.add(stagesPane, JideBoxLayout.FIX); - - } - - public void updateStageEditorPane(JPanel pane, QuestStage selectedStage, FieldUpdateListener listener) { - pane.removeAll(); - if (selectedStage != null) { - boolean writable = ((Quest)target).writable; - progressField = addIntegerField(pane, "Progress ID: ", selectedStage.progress, false, writable, listener); - logTextField = addTranslatableTextArea(pane, "Log text: ", selectedStage.log_text, writable, listener); - xpRewardField = addIntegerField(pane, "XP Reward: ", selectedStage.exp_reward, false, writable, listener); - finishQuestBox = addIntegerBasedCheckBox(pane, "Finishes quest", selectedStage.finishes_quest, writable, listener); - addBacklinksList(pane, selectedStage, "Elements linking to this quest stage"); - - } - pane.revalidate(); - pane.repaint(); - } + // private JPanel stagesParamPane; + private JSpinner progressField; + private JTextArea logTextField; + private JSpinner xpRewardField; + private IntegerBasedCheckBox finishQuestBox; - public static class StagesListModel extends OrderedListenerListModel { - public StagesListModel(Quest quest) { - super(quest); - } + public QuestEditor(Quest quest) { + super(quest, quest.getDesc(), quest.getIcon()); + addEditorTab(form_view_id, getFormView()); + addEditorTab(json_view_id, getJSONView()); + } - @Override - protected List getItems() { - return source.stages; - } + public void insertFormViewDataField(JPanel pane) { + final Quest quest = ((Quest) target); - @Override - protected void setItems(List items) { - source.stages = items; - } - } - - - public static class StagesCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; + final FieldUpdateListener listener = new QuestFieldUpdater(); - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel)c); - label.setText(((QuestStage)value).getDesc()); - label.setIcon(new ImageIcon(((QuestStage)value).getIcon())); - } - return c; - } - } - - - public class QuestFieldUpdater implements FieldUpdateListener { + createButtonPane(pane, quest.getProject(), quest, Quest.class, quest.getImage(), null, listener); - @Override - public void valueChanged(JComponent source, Object value) { - Quest quest = (Quest) target; - if (source == idField) { - //Events caused by cancel an ID edition. Dismiss. - if (skipNext) { - skipNext = false; - return; - } - if (target.id.equals((String) value)) return; - - if (idChanging()) { - quest.id = (String) value; - QuestEditor.this.name = quest.getDesc(); - quest.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(QuestEditor.this); - } else { - cancelIdEdit(idField); - return; - } - } else if (source == nameField) { - quest.name = (String) value; - QuestEditor.this.name = quest.getDesc(); - quest.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(QuestEditor.this); - } else if (source == visibleBox) { - quest.visible_in_log = (Integer) value; - } else if (source == progressField) { - selectedStage.progress = (Integer) value; - stagesListModel.itemChanged(selectedStage); - } else if (source == logTextField) { - selectedStage.log_text = (String) value; - stagesListModel.itemChanged(selectedStage); - } else if (source == xpRewardField) { - selectedStage.exp_reward = (Integer) value; - stagesListModel.itemChanged(selectedStage); - } else if (source == finishQuestBox) { - selectedStage.finishes_quest = (Integer) value; - stagesListModel.itemChanged(selectedStage); - } - - if (quest.state != GameDataElement.State.modified) { - quest.state = GameDataElement.State.modified; - QuestEditor.this.name = quest.getDesc(); - quest.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(QuestEditor.this); - } - updateJsonViewText(quest.toJsonString()); - } - - - } - + idField = addTextField(pane, "Internal ID: ", quest.id, quest.writable, listener); + nameField = addTranslatableTextField(pane, "Quest Name: ", quest.name, quest.writable, listener); + visibleBox = addIntegerBasedCheckBox(pane, "Visible in quest log", quest.visible_in_log, quest.writable, listener); + + CollapsiblePanel stagesPane = new CollapsiblePanel("Quest stages: "); + stagesPane.setLayout(new JideBoxLayout(stagesPane, JideBoxLayout.PAGE_AXIS)); + stagesListModel = new StagesListModel(quest); + stagesList = new JList(stagesListModel); + stagesList.setCellRenderer(new StagesCellRenderer()); + stagesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + stagesPane.add(new JScrollPane(stagesList), JideBoxLayout.FIX); + final JPanel stagesEditorPane = new JPanel(); + final JButton createStage = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + final JButton deleteStage = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + final JButton moveStageUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); + final JButton moveStageDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); + deleteStage.setEnabled(false); + moveStageUp.setEnabled(false); + moveStageDown.setEnabled(false); + stagesList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedStage = (QuestStage) stagesList.getSelectedValue(); + if (selectedStage != null) { + deleteStage.setEnabled(true); + moveStageUp.setEnabled(stagesList.getSelectedIndex() > 0); + moveStageDown.setEnabled(stagesList.getSelectedIndex() < (stagesListModel.getSize() - 1)); + } else { + deleteStage.setEnabled(false); + moveStageUp.setEnabled(false); + moveStageDown.setEnabled(false); + } + updateStageEditorPane(stagesEditorPane, selectedStage, listener); + } + }); + if (quest.writable) { + JPanel listButtonsPane = new JPanel(); + listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + createStage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + QuestStage stage = new QuestStage(quest); + stagesListModel.addItem(stage); + stagesList.setSelectedValue(stage, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + }); + deleteStage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedStage != null) { + stagesListModel.removeItem(selectedStage); + selectedStage = null; + stagesList.clearSelection(); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + moveStageUp.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (selectedStage != null) { + stagesListModel.moveUp(selectedStage); + stagesList.setSelectedValue(selectedStage, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + moveStageDown.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (selectedStage != null) { + stagesListModel.moveDown(selectedStage); + stagesList.setSelectedValue(selectedStage, true); + listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. + } + } + }); + listButtonsPane.add(createStage, JideBoxLayout.FIX); + listButtonsPane.add(deleteStage, JideBoxLayout.FIX); + listButtonsPane.add(moveStageUp, JideBoxLayout.FIX); + listButtonsPane.add(moveStageDown, JideBoxLayout.FIX); + listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + stagesPane.add(listButtonsPane, JideBoxLayout.FIX); + } + if (quest.stages == null || quest.stages.isEmpty()) { + stagesPane.collapse(); + } + stagesEditorPane.setLayout(new JideBoxLayout(stagesEditorPane, JideBoxLayout.PAGE_AXIS)); + stagesPane.add(stagesEditorPane, JideBoxLayout.FIX); + pane.add(stagesPane, JideBoxLayout.FIX); + + } + + public void updateStageEditorPane(JPanel pane, QuestStage selectedStage, FieldUpdateListener listener) { + pane.removeAll(); + if (selectedStage != null) { + boolean writable = ((Quest) target).writable; + progressField = addIntegerField(pane, "Progress ID: ", selectedStage.progress, false, writable, listener); + logTextField = addTranslatableTextArea(pane, "Log text: ", selectedStage.log_text, writable, listener); + xpRewardField = addIntegerField(pane, "XP Reward: ", selectedStage.exp_reward, false, writable, listener); + finishQuestBox = addIntegerBasedCheckBox(pane, "Finishes quest", selectedStage.finishes_quest, writable, listener); + addBacklinksList(pane, selectedStage, "Elements linking to this quest stage"); + + } + pane.revalidate(); + pane.repaint(); + } + + + public static class StagesListModel extends OrderedListenerListModel { + public StagesListModel(Quest quest) { + super(quest); + } + + @Override + protected List getItems() { + return source.stages; + } + + @Override + protected void setItems(List items) { + source.stages = items; + } + } + + + public static class StagesCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + label.setText(((QuestStage) value).getDesc()); + label.setIcon(new ImageIcon(((QuestStage) value).getIcon())); + } + return c; + } + } + + + public class QuestFieldUpdater implements FieldUpdateListener { + + @Override + public void valueChanged(JComponent source, Object value) { + Quest quest = (Quest) target; + if (source == idField) { + //Events caused by cancel an ID edition. Dismiss. + if (skipNext) { + skipNext = false; + return; + } + if (target.id.equals((String) value)) return; + + if (idChanging()) { + quest.id = (String) value; + QuestEditor.this.name = quest.getDesc(); + quest.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(QuestEditor.this); + } else { + cancelIdEdit(idField); + return; + } + } else if (source == nameField) { + quest.name = (String) value; + QuestEditor.this.name = quest.getDesc(); + quest.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(QuestEditor.this); + } else if (source == visibleBox) { + quest.visible_in_log = (Integer) value; + } else if (source == progressField) { + selectedStage.progress = (Integer) value; + stagesListModel.itemChanged(selectedStage); + } else if (source == logTextField) { + selectedStage.log_text = (String) value; + stagesListModel.itemChanged(selectedStage); + } else if (source == xpRewardField) { + selectedStage.exp_reward = (Integer) value; + stagesListModel.itemChanged(selectedStage); + } else if (source == finishQuestBox) { + selectedStage.finishes_quest = (Integer) value; + stagesListModel.itemChanged(selectedStage); + } + + + if (quest.state != GameDataElement.State.modified) { + quest.state = GameDataElement.State.modified; + QuestEditor.this.name = quest.getDesc(); + quest.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(QuestEditor.this); + } + updateJsonViewText(quest.toJsonString()); + } + + + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java index 61b1da2..0c8a36f 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java @@ -1,24 +1,17 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree; -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Image; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JToolTip; -import javax.swing.SwingConstants; -import javax.swing.ToolTipManager; - +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Workspace; +import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; +import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; +import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DialogueEditor; import com.gpl.rpg.atcontentstudio.utils.TextUtils; +import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; +import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration.WeblateTranslationUnit; +import com.jidesoft.swing.JideBoxLayout; import prefuse.Display; import prefuse.Visualization; import prefuse.action.ActionList; @@ -48,74 +41,71 @@ import prefuse.visual.EdgeItem; import prefuse.visual.VisualItem; import prefuse.visual.expression.InGroupPredicate; -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.DialogueEditor; -import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; -import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration.WeblateTranslationUnit; -import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import java.awt.*; +import java.awt.event.MouseEvent; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; public class DialogueGraphView extends Display { - private static final long serialVersionUID = -6431503090775579301L; - - public static final String GRAPH = "graph"; + private static final long serialVersionUID = -6431503090775579301L; + + public static final String GRAPH = "graph"; public static final String NODES = "graph.nodes"; public static final String EDGES = "graph.edges"; public static final String EDGES_LABELS = "edgesLabels"; - + public static final String LABEL = "label"; public static final String ICON = "icon"; public static final String TARGET = "target"; public static final String REPLY = "reply"; public static final String HIDDEN_REPLY = "hidden_reply"; public static final String HAS_REQS = "has_reqs"; - - private static final String TRANSLATION_LOADING="Loading translation..."; - private String translationHeader="\n---[ Translation from weblate ]---\n"; - - - private static final Schema DECORATOR_SCHEMA = PrefuseLib.getVisualItemSchema(); - - private Dialogue dialogue; - private Image npcIcon; - private Graph graph; - private Boolean translatorMode; - private Map cells = new HashMap(); + private static final String TRANSLATION_LOADING = "Loading translation..."; + private String translationHeader = "\n---[ Translation from weblate ]---\n"; - public DialogueGraphView(Dialogue dialogue, NPC npc) { - super(new Visualization()); - this.dialogue = dialogue; - if (npc != null) { - npcIcon = npc.getIcon(); - } else { - npcIcon = DefaultIcons.getNPCIcon(); - } - translatorMode = Workspace.activeWorkspace.settings.useInternet.getCurrentValue() && Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null; - if (translatorMode) { - translationHeader = "\n---[ Translation in "+Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue()+" ]---\n"; - } - loadGraph(); - // add visual data groups + private static final Schema DECORATOR_SCHEMA = PrefuseLib.getVisualItemSchema(); + + private Dialogue dialogue; + private Image npcIcon; + private Graph graph; + private Boolean translatorMode; + + private Map cells = new HashMap(); + + public DialogueGraphView(Dialogue dialogue, NPC npc) { + super(new Visualization()); + this.dialogue = dialogue; + if (npc != null) { + npcIcon = npc.getIcon(); + } else { + npcIcon = DefaultIcons.getNPCIcon(); + } + translatorMode = Workspace.activeWorkspace.settings.useInternet.getCurrentValue() && Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null; + if (translatorMode) { + translationHeader = "\n---[ Translation in " + Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() + " ]---\n"; + } + loadGraph(); + + // add visual data groups m_vis.addGraph(GRAPH, graph); m_vis.setInteractive(EDGES, null, false); - + LabelRenderer nodeR = new MyLabelRenderer(LABEL); nodeR.setHorizontalTextAlignment(prefuse.Constants.LEFT); - + EdgeRenderer edgeR = new EdgeRenderer(prefuse.Constants.EDGE_TYPE_LINE, prefuse.Constants.EDGE_ARROW_FORWARD); // edgeR.setEdgeType(prefuse.Constants.EDGE_TYPE_CURVE); - + LabelRenderer edgeLabelR = new LabelRenderer(LABEL); edgeLabelR.setRenderType(LabelRenderer.RENDER_TYPE_DRAW); - + DefaultRendererFactory drf = new DefaultRendererFactory(); drf.setDefaultRenderer(nodeR); drf.setDefaultEdgeRenderer(edgeR); @@ -125,27 +115,27 @@ public class DialogueGraphView extends Display { DECORATOR_SCHEMA.setDefault(VisualItem.STROKECOLOR, ColorLib.rgba(0, 0, 0, 0)); DECORATOR_SCHEMA.setDefault(VisualItem.TEXTCOLOR, ColorLib.gray(0)); m_vis.addDecorators(EDGES_LABELS, EDGES, DECORATOR_SCHEMA); - - // set up the visual operators + + // set up the visual operators // first set up all the color actions ColorAction nStrokeColor = new ColorAction(NODES, VisualItem.STROKECOLOR); nStrokeColor.setDefaultColor(ColorLib.gray(100)); - nStrokeColor.add("_hover", ColorLib.rgb(255,100,100)); + nStrokeColor.add("_hover", ColorLib.rgb(255, 100, 100)); StrokeAction nStroke = new EdgesStrokeAction(NODES); - + ColorAction nFill = new NPCPhraseColorAction(NODES, VisualItem.FILLCOLOR); - + ColorAction eEdges = new ConnectedEdgeColorAction(EDGES, VisualItem.STROKECOLOR); ColorAction eArrows = new ConnectedEdgeColorAction(EDGES, VisualItem.FILLCOLOR); ColorAction eEdgesLabels = new ConnectedEdgeColorAction(EDGES_LABELS, VisualItem.TEXTCOLOR); - + StrokeAction eStroke = new EdgesStrokeAction(EDGES); - + FontAction aFont = new FontAction(); ColorAction aFontColor = new ColorAction(NODES, VisualItem.TEXTCOLOR); aFontColor.setDefaultColor(ColorLib.rgb(0, 0, 0)); - - // bundle the color actions + + // bundle the color actions ActionList colors = new ActionList(Activity.INFINITY); colors.add(nStrokeColor); colors.add(nFill); @@ -158,18 +148,18 @@ public class DialogueGraphView extends Display { colors.add(aFontColor); colors.add(new RepaintAction()); m_vis.putAction("colors", colors); - + // now create the main layout routine ActionList layout = new ActionList();//Activity.INFINITY); NodeLinkTreeLayout treeLayout = new NodeLinkTreeLayout(GRAPH, prefuse.Constants.ORIENT_LEFT_RIGHT, 120, translatorMode ? 80 : 40, translatorMode ? 80 : 40); - treeLayout.setLayoutAnchor(new Point2D.Double(25,300)); + treeLayout.setLayoutAnchor(new Point2D.Double(25, 300)); layout.add(treeLayout); layout.add(new EdgesLabelDecoratorLayout(EDGES_LABELS)); layout.add(new RepaintAction()); m_vis.putAction("layout", layout); - + // set up the display - setSize(500,500); + setSize(500, 500); pan(250, 250); setHighQuality(true); addControlListener(new TooltipControl()); @@ -177,399 +167,405 @@ public class DialogueGraphView extends Display { addControlListener(new WheelZoomControl()); addControlListener(new ZoomControl()); addControlListener(new PanControl()); - + // set things running m_vis.run("colors"); m_vis.run("layout"); - } - - public void loadGraph() { - graph = new Graph(true); - graph.addColumn(LABEL, String.class, ""); - graph.addColumn(ICON, Image.class, DefaultIcons.getNullifyIcon()); - graph.addColumn(TARGET, GameDataElement.class, null); - graph.addColumn(REPLY, Dialogue.Reply.class, null); - graph.addColumn(HIDDEN_REPLY, Dialogue.Reply.class, null); - graph.addColumn(HAS_REQS, boolean.class, false); - addDialogue(dialogue, npcIcon); - } - - public Node addDialogue(Dialogue dialogue, Image npcIcon) { - if (cells.get(dialogue) == null) { - if (dialogue.switch_to_npc != null) { - npcIcon = dialogue.switch_to_npc.getIcon(); - } - final Node dNode = graph.addNode(); - cells.put(dialogue, dNode); - String label; - Thread t = null; - if (dialogue.message == null) { - label = "[Selector]"; - } else if (translatorMode) { - label = dialogue.message+translationHeader+TRANSLATION_LOADING; - final String message = dialogue.message; - t = new Thread("Get weblate translation for "+message) { - public void run() { - WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); - dNode.setString(LABEL, message+translationHeader+unit.translatedText); - }; - }; - } else { - label = dialogue.message; - } - dNode.setString(LABEL, label); - if (t != null) t.start(); - dNode.set(ICON, npcIcon); - dNode.set(TARGET, dialogue); - if (dialogue.replies != null) { - Node rNode; - int i = 1; - for (Dialogue.Reply r : dialogue.replies) { - rNode = addReply(dialogue, r, npcIcon); - Edge e = graph.addEdge(dNode, rNode); - e.setString(LABEL, "#"+i++); - e.setBoolean(HAS_REQS, r.requirements != null && !r.requirements.isEmpty()); - } - } - } - return cells.get(dialogue); - } - - public Node addReply(Dialogue d, Dialogue.Reply r, Image npcIcon) { - final Node rNode; - if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) { - //Normal reply... - rNode = graph.addNode(); + } + + public void loadGraph() { + graph = new Graph(true); + graph.addColumn(LABEL, String.class, ""); + graph.addColumn(ICON, Image.class, DefaultIcons.getNullifyIcon()); + graph.addColumn(TARGET, GameDataElement.class, null); + graph.addColumn(REPLY, Dialogue.Reply.class, null); + graph.addColumn(HIDDEN_REPLY, Dialogue.Reply.class, null); + graph.addColumn(HAS_REQS, boolean.class, false); + addDialogue(dialogue, npcIcon); + } + + public Node addDialogue(Dialogue dialogue, Image npcIcon) { + if (cells.get(dialogue) == null) { + if (dialogue.switch_to_npc != null) { + npcIcon = dialogue.switch_to_npc.getIcon(); + } + final Node dNode = graph.addNode(); + cells.put(dialogue, dNode); + String label; + Thread t = null; + if (dialogue.message == null) { + label = "[Selector]"; + } else if (translatorMode) { + label = dialogue.message + translationHeader + TRANSLATION_LOADING; + final String message = dialogue.message; + t = new Thread("Get weblate translation for " + message) { + public void run() { + WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); + dNode.setString(LABEL, message + translationHeader + unit.translatedText); + } + + ; + }; + } else { + label = dialogue.message; + } + dNode.setString(LABEL, label); + if (t != null) t.start(); + dNode.set(ICON, npcIcon); + dNode.set(TARGET, dialogue); + if (dialogue.replies != null) { + Node rNode; + int i = 1; + for (Dialogue.Reply r : dialogue.replies) { + rNode = addReply(dialogue, r, npcIcon); + Edge e = graph.addEdge(dNode, rNode); + e.setString(LABEL, "#" + i++); + e.setBoolean(HAS_REQS, r.requirements != null && !r.requirements.isEmpty()); + } + } + } + return cells.get(dialogue); + } + + public Node addReply(Dialogue d, Dialogue.Reply r, Image npcIcon) { + final Node rNode; + if (r.text != null && !r.text.equals(Dialogue.Reply.GO_NEXT_TEXT)) { + //Normal reply... + rNode = graph.addNode(); // rNode.setString(LABEL, translatorMode ? r.text + "\n---\n" + WeblateIntegration.getTranslationUnit(r.text).translatedText : r.text); - String label; - Thread t = null; - if (translatorMode) { - label = r.text+translationHeader+TRANSLATION_LOADING; - final String message = r.text; - t = new Thread("Get weblate translation for "+message) { - public void run() { - WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); - rNode.setString(LABEL, message+translationHeader+unit.translatedText); - }; - }; - } else { - label = r.text; - } - rNode.setString(LABEL, label); - if (t != null) t.start(); - rNode.set(ICON, DefaultIcons.getHeroIcon()); - rNode.set(TARGET, d); - rNode.set(REPLY, r); - if (r.next_phrase != null) { - //...that leads to another phrase - Node dNode = addDialogue(r.next_phrase, npcIcon); - graph.addEdge(rNode, dNode); - } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { - //...that leads to a key phrase - Node kNode = addKeyPhraseNode(d, r.next_phrase_id); - kNode.set(REPLY, r); - graph.addEdge(rNode, kNode); - } - } else if (r.next_phrase != null) { - //Go directly to next phrase - rNode = addDialogue(r.next_phrase, npcIcon); - //Add a pointer to the hidden reply, in order to fetch requirements later. - rNode.set(HIDDEN_REPLY, r); - } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { - //Go directly to key phrase - rNode = addKeyPhraseNode(d, r.next_phrase_id); - rNode.set(REPLY, r); - } else { - //Incomplete. - rNode = graph.addNode(); - rNode.setString(LABEL, "[Incomplete reply]"); - rNode.set(ICON, DefaultIcons.getNullifyIcon()); - } - return rNode; - } - - public Node addKeyPhraseNode(Dialogue d, String key) { - Node kNode = graph.addNode(); - if (key.equals(Dialogue.Reply.EXIT_PHRASE_ID)) { - kNode.setString(LABEL, "[Ends dialogue]"); - kNode.set(ICON, DefaultIcons.getNullifyIcon()); - } else if (key.equals(Dialogue.Reply.FIGHT_PHRASE_ID)) { - kNode.setString(LABEL, "[Starts fight]"); - kNode.set(ICON, DefaultIcons.getCombatIcon()); - } else if (key.equals(Dialogue.Reply.REMOVE_PHRASE_ID)) { - kNode.setString(LABEL, "[NPC vanishes]"); - kNode.set(ICON, DefaultIcons.getNPCCloseIcon()); - } else if (key.equals(Dialogue.Reply.SHOP_PHRASE_ID)) { - kNode.setString(LABEL, "[Start trading]"); - kNode.set(ICON, DefaultIcons.getGoldIcon()); - } else { - //Should never reach, unless new key phrase ID are added to the model, but not here... - kNode.setString(LABEL, "[WTF !!]"+key); - } - kNode.set(TARGET, d); - return kNode; - } - - class MyLabelRenderer extends LabelRenderer { - public MyLabelRenderer(String label) { - super(label); - } + String label; + Thread t = null; + if (translatorMode) { + label = r.text + translationHeader + TRANSLATION_LOADING; + final String message = r.text; + t = new Thread("Get weblate translation for " + message) { + public void run() { + WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(message); + rNode.setString(LABEL, message + translationHeader + unit.translatedText); + } - @Override - protected Image getImage(VisualItem item) { - return (Image) item.get(ICON); - } - - @Override - protected String getText(VisualItem item) { - return TextUtils.wordWrap(super.getText(item), 40); - } + ; + }; + } else { + label = r.text; + } + rNode.setString(LABEL, label); + if (t != null) t.start(); + rNode.set(ICON, DefaultIcons.getHeroIcon()); + rNode.set(TARGET, d); + rNode.set(REPLY, r); + if (r.next_phrase != null) { + //...that leads to another phrase + Node dNode = addDialogue(r.next_phrase, npcIcon); + graph.addEdge(rNode, dNode); + } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { + //...that leads to a key phrase + Node kNode = addKeyPhraseNode(d, r.next_phrase_id); + kNode.set(REPLY, r); + graph.addEdge(rNode, kNode); + } + } else if (r.next_phrase != null) { + //Go directly to next phrase + rNode = addDialogue(r.next_phrase, npcIcon); + //Add a pointer to the hidden reply, in order to fetch requirements later. + rNode.set(HIDDEN_REPLY, r); + } else if (Dialogue.Reply.KEY_PHRASE_ID.contains(r.next_phrase_id)) { + //Go directly to key phrase + rNode = addKeyPhraseNode(d, r.next_phrase_id); + rNode.set(REPLY, r); + } else { + //Incomplete. + rNode = graph.addNode(); + rNode.setString(LABEL, "[Incomplete reply]"); + rNode.set(ICON, DefaultIcons.getNullifyIcon()); + } + return rNode; + } - } - - class ConnectedEdgeColorAction extends ColorAction { + public Node addKeyPhraseNode(Dialogue d, String key) { + Node kNode = graph.addNode(); + if (key.equals(Dialogue.Reply.EXIT_PHRASE_ID)) { + kNode.setString(LABEL, "[Ends dialogue]"); + kNode.set(ICON, DefaultIcons.getNullifyIcon()); + } else if (key.equals(Dialogue.Reply.FIGHT_PHRASE_ID)) { + kNode.setString(LABEL, "[Starts fight]"); + kNode.set(ICON, DefaultIcons.getCombatIcon()); + } else if (key.equals(Dialogue.Reply.REMOVE_PHRASE_ID)) { + kNode.setString(LABEL, "[NPC vanishes]"); + kNode.set(ICON, DefaultIcons.getNPCCloseIcon()); + } else if (key.equals(Dialogue.Reply.SHOP_PHRASE_ID)) { + kNode.setString(LABEL, "[Start trading]"); + kNode.set(ICON, DefaultIcons.getGoldIcon()); + } else { + //Should never reach, unless new key phrase ID are added to the model, but not here... + kNode.setString(LABEL, "[WTF !!]" + key); + } + kNode.set(TARGET, d); + return kNode; + } - final int outgoing = ColorLib.rgb(255, 100, 100); - final int incoming = ColorLib.rgb(100, 255, 100); - final int none = ColorLib.gray(100); - - public ConnectedEdgeColorAction(String group, String field) { - super(group, field); - } - - @Override - public int getColor(VisualItem item) { - if (item instanceof DecoratorItem) { - item = ((DecoratorItem) item).getDecoratedItem(); - } - if (item instanceof EdgeItem) { - if (((EdgeItem) item).getSourceItem().isHover()) { - return outgoing; - } else if (((EdgeItem) item).getTargetItem().isHover()) { - return incoming; - } - } + class MyLabelRenderer extends LabelRenderer { + public MyLabelRenderer(String label) { + super(label); + } - return none; - } - } - - class NPCPhraseColorAction extends ColorAction { - - final int none = ColorLib.gray(255); - final int hover = ColorLib.gray(200); - final int has_rewards = ColorLib.rgb(255, 255, 0); - final int has_rewards_hover = ColorLib.rgb(200, 200, 0); - - - public NPCPhraseColorAction(String group, String field) { - super(group, field); - } - - @Override - public int getColor(VisualItem item) { - // Change color for Dialogues, not replies. - if (item.get(TARGET) != null && item.get(REPLY) == null) { - Dialogue d = (Dialogue) item.get(TARGET); - if (d.rewards != null && !d.rewards.isEmpty()) { - if (item.isHover()) { - return has_rewards_hover; - } else { - return has_rewards; - } - } - } - if (item.isHover()) { - return hover; - } else { - return none; - } - } - } - - class EdgesStrokeAction extends StrokeAction { - - public final BasicStroke req_stroke = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); - public final BasicStroke hover_stroke = new BasicStroke(3.0f); - public final BasicStroke hover_req_stroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); - - public EdgesStrokeAction(String group) { - super(group); - } - - @Override - public BasicStroke getStroke(VisualItem item) { - if (item.getBoolean(HAS_REQS)) { - if (item instanceof EdgeItem) { - if (((EdgeItem) item).getSourceItem().isHover()) { - return hover_req_stroke; - } else if (((EdgeItem) item).getTargetItem().isHover()) { - return hover_req_stroke; - } - } - return req_stroke; - } else { - if (item.isHover()) { - return hover_stroke; - } else if (item instanceof EdgeItem) { - if (((EdgeItem) item).getSourceItem().isHover()) { - return hover_stroke; - } else if (((EdgeItem) item).getTargetItem().isHover()) { - return hover_stroke; - } - } - } - return super.getStroke(item); - } - - } - - class EdgesLabelDecoratorLayout extends Layout { - public EdgesLabelDecoratorLayout(String group) { - super(group); - } - public void run(double frac) { - Iterator iter = m_vis.items(m_group); - while ( iter.hasNext() ) { - DecoratorItem decorator = (DecoratorItem)iter.next(); - if( decorator.getDecoratedItem() instanceof EdgeItem) { - EdgeItem edgeItem = (EdgeItem) decorator.getDecoratedItem(); - double deltaX = edgeItem.getTargetItem().getX() - edgeItem.getSourceItem().getX(); - double deltaY = edgeItem.getTargetItem().getY() - edgeItem.getSourceItem().getY(); - double hypo = Math.hypot(deltaX, deltaY); - - double edgePropX = deltaX / hypo; - double edgePropY = deltaY / hypo; - - Point2D start = new Point2D.Double(edgeItem.getSourceItem().getBounds().getCenterX(), edgeItem.getSourceItem().getBounds().getCenterY()); - Point2D end = new Point2D.Double(edgeItem.getTargetItem().getBounds().getCenterX(), edgeItem.getTargetItem().getBounds().getCenterY()); - Point2D[] realStart = new Point2D[]{new Point2D.Double(), new Point2D.Double()}; + @Override + protected Image getImage(VisualItem item) { + return (Image) item.get(ICON); + } + + @Override + protected String getText(VisualItem item) { + return TextUtils.wordWrap(super.getText(item), 40); + } + + } + + class ConnectedEdgeColorAction extends ColorAction { + + final int outgoing = ColorLib.rgb(255, 100, 100); + final int incoming = ColorLib.rgb(100, 255, 100); + final int none = ColorLib.gray(100); + + public ConnectedEdgeColorAction(String group, String field) { + super(group, field); + } + + @Override + public int getColor(VisualItem item) { + if (item instanceof DecoratorItem) { + item = ((DecoratorItem) item).getDecoratedItem(); + } + if (item instanceof EdgeItem) { + if (((EdgeItem) item).getSourceItem().isHover()) { + return outgoing; + } else if (((EdgeItem) item).getTargetItem().isHover()) { + return incoming; + } + } + + return none; + } + } + + class NPCPhraseColorAction extends ColorAction { + + final int none = ColorLib.gray(255); + final int hover = ColorLib.gray(200); + final int has_rewards = ColorLib.rgb(255, 255, 0); + final int has_rewards_hover = ColorLib.rgb(200, 200, 0); + + + public NPCPhraseColorAction(String group, String field) { + super(group, field); + } + + @Override + public int getColor(VisualItem item) { + // Change color for Dialogues, not replies. + if (item.get(TARGET) != null && item.get(REPLY) == null) { + Dialogue d = (Dialogue) item.get(TARGET); + if (d.rewards != null && !d.rewards.isEmpty()) { + if (item.isHover()) { + return has_rewards_hover; + } else { + return has_rewards; + } + } + } + if (item.isHover()) { + return hover; + } else { + return none; + } + } + } + + class EdgesStrokeAction extends StrokeAction { + + public final BasicStroke req_stroke = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); + public final BasicStroke hover_stroke = new BasicStroke(3.0f); + public final BasicStroke hover_req_stroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 1.0f, new float[]{3.5f, 2.5f}, 1.0f); + + public EdgesStrokeAction(String group) { + super(group); + } + + @Override + public BasicStroke getStroke(VisualItem item) { + if (item.getBoolean(HAS_REQS)) { + if (item instanceof EdgeItem) { + if (((EdgeItem) item).getSourceItem().isHover()) { + return hover_req_stroke; + } else if (((EdgeItem) item).getTargetItem().isHover()) { + return hover_req_stroke; + } + } + return req_stroke; + } else { + if (item.isHover()) { + return hover_stroke; + } else if (item instanceof EdgeItem) { + if (((EdgeItem) item).getSourceItem().isHover()) { + return hover_stroke; + } else if (((EdgeItem) item).getTargetItem().isHover()) { + return hover_stroke; + } + } + } + return super.getStroke(item); + } + + } + + class EdgesLabelDecoratorLayout extends Layout { + public EdgesLabelDecoratorLayout(String group) { + super(group); + } + + public void run(double frac) { + Iterator iter = m_vis.items(m_group); + while (iter.hasNext()) { + DecoratorItem decorator = (DecoratorItem) iter.next(); + if (decorator.getDecoratedItem() instanceof EdgeItem) { + EdgeItem edgeItem = (EdgeItem) decorator.getDecoratedItem(); + double deltaX = edgeItem.getTargetItem().getX() - edgeItem.getSourceItem().getX(); + double deltaY = edgeItem.getTargetItem().getY() - edgeItem.getSourceItem().getY(); + double hypo = Math.hypot(deltaX, deltaY); + + double edgePropX = deltaX / hypo; + double edgePropY = deltaY / hypo; + + Point2D start = new Point2D.Double(edgeItem.getSourceItem().getBounds().getCenterX(), edgeItem.getSourceItem().getBounds().getCenterY()); + Point2D end = new Point2D.Double(edgeItem.getTargetItem().getBounds().getCenterX(), edgeItem.getTargetItem().getBounds().getCenterY()); + Point2D[] realStart = new Point2D[]{new Point2D.Double(), new Point2D.Double()}; // Point2D[] realEnd = new Point2D[]{new Point2D.Double(), new Point2D.Double()}; - - int i = GraphicsLib.intersectLineRectangle(start, end, edgeItem.getSourceItem().getBounds(), realStart); - if (i > 0) { - start = realStart[0]; - } + + int i = GraphicsLib.intersectLineRectangle(start, end, edgeItem.getSourceItem().getBounds(), realStart); + if (i > 0) { + start = realStart[0]; + } // i = GraphicsLib.intersectLineRectangle(start, end, edgeItem.getTargetItem().getBounds(), realEnd); // if (i > 0) { // end = realEnd[0]; // } - - double coef = 20 * Math.atan(hypo / 100.0) + 20; - - setX(decorator, null, start.getX() + coef * edgePropX + 6 * Math.random() - 3); - setY(decorator, null, start.getY() + coef * edgePropY + 6 * Math.random() - 3); - } else { - VisualItem decoratedItem = decorator.getDecoratedItem(); - Rectangle2D bounds = decoratedItem.getBounds(); - double x = bounds.getCenterX(); - double y = bounds.getCenterY(); - setX(decorator, null, x + 10 * Math.random() - 5); - setY(decorator, null, y + 10 * Math.random() - 5); - } - } - } - } - - class DoubleClickControl extends ControlAdapter { - @Override - public void itemClicked(VisualItem item, MouseEvent e) { - if (e.getClickCount() == 2) { - if (item.get(TARGET) != null) { - ATContentStudio.frame.openEditor((GameDataElement)item.get(TARGET)); - } - } - } - } - - class TooltipControl extends ControlAdapter { - - @Override - public void itemEntered(VisualItem item, MouseEvent e) { - if (item.get(TARGET) != null) { - tooltippedItem = item; - if (!tooltipActivated) { - setToolTipText(""); - ToolTipManager.sharedInstance().registerComponent(DialogueGraphView.this); - ToolTipManager.sharedInstance().setEnabled(true); - tooltipActivated = true; - } - } - } - @Override - public void itemExited(VisualItem item, MouseEvent e) { - //Hides the tooltip... - ToolTipManager.sharedInstance().setEnabled(false); - ToolTipManager.sharedInstance().unregisterComponent(DialogueGraphView.this); - tooltipActivated = false; - } - } - - JToolTip tt = null; - private VisualItem tooltippedItem = null; - private VisualItem lastTTItem = null; + + double coef = 20 * Math.atan(hypo / 100.0) + 20; + + setX(decorator, null, start.getX() + coef * edgePropX + 6 * Math.random() - 3); + setY(decorator, null, start.getY() + coef * edgePropY + 6 * Math.random() - 3); + } else { + VisualItem decoratedItem = decorator.getDecoratedItem(); + Rectangle2D bounds = decoratedItem.getBounds(); + double x = bounds.getCenterX(); + double y = bounds.getCenterY(); + setX(decorator, null, x + 10 * Math.random() - 5); + setY(decorator, null, y + 10 * Math.random() - 5); + } + } + } + } + + class DoubleClickControl extends ControlAdapter { + @Override + public void itemClicked(VisualItem item, MouseEvent e) { + if (e.getClickCount() == 2) { + if (item.get(TARGET) != null) { + ATContentStudio.frame.openEditor((GameDataElement) item.get(TARGET)); + } + } + } + } + + class TooltipControl extends ControlAdapter { + + @Override + public void itemEntered(VisualItem item, MouseEvent e) { + if (item.get(TARGET) != null) { + tooltippedItem = item; + if (!tooltipActivated) { + setToolTipText(""); + ToolTipManager.sharedInstance().registerComponent(DialogueGraphView.this); + ToolTipManager.sharedInstance().setEnabled(true); + tooltipActivated = true; + } + } + } + + @Override + public void itemExited(VisualItem item, MouseEvent e) { + //Hides the tooltip... + ToolTipManager.sharedInstance().setEnabled(false); + ToolTipManager.sharedInstance().unregisterComponent(DialogueGraphView.this); + tooltipActivated = false; + } + } + + JToolTip tt = null; + private VisualItem tooltippedItem = null; + private VisualItem lastTTItem = null; private boolean tooltipActivated = false; - - @Override - public Point getToolTipLocation(MouseEvent event) { - return new Point(event.getX() + 5, event.getY() + 5); - } - - @Override - public JToolTip createToolTip() { - if (tt == null) tt = super.createToolTip(); - if (tooltippedItem == lastTTItem) { - return tt; - } - tt = super.createToolTip(); - lastTTItem = tooltippedItem; - tt.setLayout(new BorderLayout()); - JPanel content = new JPanel(); - content.setLayout(new JideBoxLayout(content, JideBoxLayout.PAGE_AXIS)); - JLabel label; - if (tooltippedItem != null) { - Object target = tooltippedItem.get(TARGET); - if (target != null) { - if (target instanceof Dialogue) { - Dialogue d = (Dialogue) target; - label = new JLabel(new ImageIcon(DefaultIcons.getDialogueIcon())); - label.setText(d.id); - content.add(label, JideBoxLayout.FIX); - Object replObj = tooltippedItem.get(REPLY); - if (replObj == null) { - replObj = tooltippedItem.get(HIDDEN_REPLY); - } - if (replObj != null && replObj instanceof Dialogue.Reply) { - Dialogue.Reply r = (Dialogue.Reply) replObj; - if (r.requirements != null && !r.requirements.isEmpty()) { - JLabel reqTitle = new JLabel("--Requirements--", SwingConstants.CENTER); - content.add(reqTitle, JideBoxLayout.FIX); - for (Requirement req : r.requirements) { - label = new JLabel("", SwingConstants.CENTER); - DialogueEditor.decorateRequirementJLabel(label, req); - content.add(label, JideBoxLayout.FIX); - } - } - } - if (d.rewards != null && !d.rewards.isEmpty()) { - JLabel rewTitle = new JLabel("--Rewards--", SwingConstants.CENTER); - rewTitle.setAlignmentY(CENTER_ALIGNMENT); - content.add(rewTitle, JideBoxLayout.FIX); - for (Dialogue.Reward r : d.rewards) { - label = new JLabel("", SwingConstants.CENTER); - DialogueEditor.decorateRewardJLabel(label, r); - content.add(label, JideBoxLayout.FIX); - } - } - } - } - - } - - tt.add(content, BorderLayout.CENTER); - tt.setPreferredSize(tt.getLayout().preferredLayoutSize(tt)); - return tt; - } + + @Override + public Point getToolTipLocation(MouseEvent event) { + return new Point(event.getX() + 5, event.getY() + 5); + } + + @Override + public JToolTip createToolTip() { + if (tt == null) tt = super.createToolTip(); + if (tooltippedItem == lastTTItem) { + return tt; + } + tt = super.createToolTip(); + lastTTItem = tooltippedItem; + tt.setLayout(new BorderLayout()); + JPanel content = new JPanel(); + content.setLayout(new JideBoxLayout(content, JideBoxLayout.PAGE_AXIS)); + JLabel label; + if (tooltippedItem != null) { + Object target = tooltippedItem.get(TARGET); + if (target != null) { + if (target instanceof Dialogue) { + Dialogue d = (Dialogue) target; + label = new JLabel(new ImageIcon(DefaultIcons.getDialogueIcon())); + label.setText(d.id); + content.add(label, JideBoxLayout.FIX); + Object replObj = tooltippedItem.get(REPLY); + if (replObj == null) { + replObj = tooltippedItem.get(HIDDEN_REPLY); + } + if (replObj != null && replObj instanceof Dialogue.Reply) { + Dialogue.Reply r = (Dialogue.Reply) replObj; + if (r.requirements != null && !r.requirements.isEmpty()) { + JLabel reqTitle = new JLabel("--Requirements--", SwingConstants.CENTER); + content.add(reqTitle, JideBoxLayout.FIX); + for (Requirement req : r.requirements) { + label = new JLabel("", SwingConstants.CENTER); + DialogueEditor.decorateRequirementJLabel(label, req); + content.add(label, JideBoxLayout.FIX); + } + } + } + if (d.rewards != null && !d.rewards.isEmpty()) { + JLabel rewTitle = new JLabel("--Rewards--", SwingConstants.CENTER); + rewTitle.setAlignmentY(CENTER_ALIGNMENT); + content.add(rewTitle, JideBoxLayout.FIX); + for (Dialogue.Reward r : d.rewards) { + label = new JLabel("", SwingConstants.CENTER); + DialogueEditor.decorateRewardJLabel(label, r); + content.add(label, JideBoxLayout.FIX); + } + } + } + } + + } + + tt.add(content, BorderLayout.CENTER); + tt.setPreferredSize(tt.getLayout().preferredLayoutSize(tt)); + return tt; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java b/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java index 593cb04..5167320 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/MapColorFilters.java @@ -1,116 +1,113 @@ package com.gpl.rpg.atcontentstudio.ui.map; -import java.awt.Color; -import java.awt.Composite; -import java.awt.Graphics2D; -import java.awt.Rectangle; - import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.ui.tools.MatrixComposite; +import java.awt.*; + public class MapColorFilters { - public static void applyColorfilter(TMXMap.ColorFilter colorFilter, Graphics2D g2d) { - Composite oldComp = g2d.getComposite(); - Rectangle clip = g2d.getClipBounds(); - MatrixComposite newComp = null; - float f; - switch(colorFilter) { - case black20: - f=0.8f; - newComp = new MatrixComposite(new float[]{ - f, 0.00f, 0.00f, 0.0f, 0.0f, - 0.00f, f, 0.00f, 0.0f, 0.0f, - 0.00f, 0.00f, f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case black40: - f=0.6f; - newComp = new MatrixComposite(new float[]{ - f, 0.00f, 0.00f, 0.0f, 0.0f, - 0.00f, f, 0.00f, 0.0f, 0.0f, - 0.00f, 0.00f, f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case black60: - f=0.4f; - newComp = new MatrixComposite(new float[]{ - f, 0.00f, 0.00f, 0.0f, 0.0f, - 0.00f, f, 0.00f, 0.0f, 0.0f, - 0.00f, 0.00f, f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case black80: - f=0.2f; - newComp = new MatrixComposite(new float[]{ - f, 0.00f, 0.00f, 0.0f, 0.0f, - 0.00f, f, 0.00f, 0.0f, 0.0f, - 0.00f, 0.00f, f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case bw: - newComp = new MatrixComposite(new float[]{ - 0.33f, 0.59f, 0.11f, 0.0f, 0.0f, - 0.33f, 0.59f, 0.11f, 0.0f, 0.0f, - 0.33f, 0.59f, 0.11f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case invert: - newComp = new MatrixComposite(new float[]{ - -1.00f, 0.00f, 0.00f, 0.0f, 255.0f, - 0.00f, -1.00f, 0.00f, 0.0f, 255.0f, - 0.00f, 0.00f, -1.00f, 0.0f, 255.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case redtint: - newComp = new MatrixComposite(new float[]{ - 1.20f, 0.20f, 0.20f, 0.0f, 25.0f, - 0.00f, 0.80f, 0.00f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.80f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case greentint: - newComp = new MatrixComposite(new float[]{ - 0.85f, 0.00f, 0.00f, 0.0f, 0.0f, - 0.15f, 1.15f, 0.15f, 0.0f, 15.0f, - 0.00f, 0.00f, 0.85f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case bluetint: - newComp = new MatrixComposite(new float[]{ - 0.70f, 0.00f, 0.00f, 0.0f, 0.0f, - 0.00f, 0.70f, 0.00f, 0.0f, 0.0f, - 0.30f, 0.30f, 1.30f, 0.0f, 40.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - case none: - f=1f; - newComp = new MatrixComposite(new float[]{ - f, 0.00f, 0.00f, 0.0f, 0.0f, - 0.00f, f, 0.00f, 0.0f, 0.0f, - 0.00f, 0.00f, f, 0.0f, 0.0f, - 0.00f, 0.00f, 0.00f, 1.0f, 0.0f - }); - break; - default: - break; - - } - if (newComp != null) { - g2d.setComposite(newComp); - g2d.setPaint(new Color(1.0f, 1.0f, 1.0f, 1.0f)); - g2d.fill(clip); - g2d.setComposite(oldComp); - } - } + public static void applyColorfilter(TMXMap.ColorFilter colorFilter, Graphics2D g2d) { + Composite oldComp = g2d.getComposite(); + Rectangle clip = g2d.getClipBounds(); + MatrixComposite newComp = null; + float f; + switch (colorFilter) { + case black20: + f = 0.8f; + newComp = new MatrixComposite(new float[]{ + f, 0.00f, 0.00f, 0.0f, 0.0f, + 0.00f, f, 0.00f, 0.0f, 0.0f, + 0.00f, 0.00f, f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case black40: + f = 0.6f; + newComp = new MatrixComposite(new float[]{ + f, 0.00f, 0.00f, 0.0f, 0.0f, + 0.00f, f, 0.00f, 0.0f, 0.0f, + 0.00f, 0.00f, f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case black60: + f = 0.4f; + newComp = new MatrixComposite(new float[]{ + f, 0.00f, 0.00f, 0.0f, 0.0f, + 0.00f, f, 0.00f, 0.0f, 0.0f, + 0.00f, 0.00f, f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case black80: + f = 0.2f; + newComp = new MatrixComposite(new float[]{ + f, 0.00f, 0.00f, 0.0f, 0.0f, + 0.00f, f, 0.00f, 0.0f, 0.0f, + 0.00f, 0.00f, f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case bw: + newComp = new MatrixComposite(new float[]{ + 0.33f, 0.59f, 0.11f, 0.0f, 0.0f, + 0.33f, 0.59f, 0.11f, 0.0f, 0.0f, + 0.33f, 0.59f, 0.11f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case invert: + newComp = new MatrixComposite(new float[]{ + -1.00f, 0.00f, 0.00f, 0.0f, 255.0f, + 0.00f, -1.00f, 0.00f, 0.0f, 255.0f, + 0.00f, 0.00f, -1.00f, 0.0f, 255.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case redtint: + newComp = new MatrixComposite(new float[]{ + 1.20f, 0.20f, 0.20f, 0.0f, 25.0f, + 0.00f, 0.80f, 0.00f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.80f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case greentint: + newComp = new MatrixComposite(new float[]{ + 0.85f, 0.00f, 0.00f, 0.0f, 0.0f, + 0.15f, 1.15f, 0.15f, 0.0f, 15.0f, + 0.00f, 0.00f, 0.85f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case bluetint: + newComp = new MatrixComposite(new float[]{ + 0.70f, 0.00f, 0.00f, 0.0f, 0.0f, + 0.00f, 0.70f, 0.00f, 0.0f, 0.0f, + 0.30f, 0.30f, 1.30f, 0.0f, 40.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + case none: + f = 1f; + newComp = new MatrixComposite(new float[]{ + f, 0.00f, 0.00f, 0.0f, 0.0f, + 0.00f, f, 0.00f, 0.0f, 0.0f, + 0.00f, 0.00f, f, 0.0f, 0.0f, + 0.00f, 0.00f, 0.00f, 1.0f, 0.0f + }); + break; + default: + break; + + } + if (newComp != null) { + g2d.setComposite(newComp); + g2d.setPaint(new Color(1.0f, 1.0f, 1.0f, 1.0f)); + g2d.fill(clip); + g2d.setComposite(oldComp); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index 69fc64c..7a354e9 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -1,2523 +1,2462 @@ package com.gpl.rpg.atcontentstudio.ui.map; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionAdapter; -import java.awt.event.MouseMotionListener; -import java.io.File; -import java.util.*; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.BorderFactory; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultComboBoxModel; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JSplitPane; -import javax.swing.JTextField; -import javax.swing.JToggleButton; -import javax.swing.JToolTip; -import javax.swing.JTree; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.ScrollPaneConstants; -import javax.swing.Scrollable; -import javax.swing.SwingConstants; -import javax.swing.ToolTipManager; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; -import javax.swing.event.TreeModelListener; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; - -import com.gpl.rpg.atcontentstudio.ui.*; -import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; -import org.fife.ui.rsyntaxtextarea.SyntaxConstants; - -import tiled.view.MapRenderer; -import tiled.view.OrthogonalRenderer; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.JSONElement; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; -import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; -import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; -import com.gpl.rpg.atcontentstudio.model.gamedata.Requirement; -import com.gpl.rpg.atcontentstudio.model.maps.ContainerArea; -import com.gpl.rpg.atcontentstudio.model.maps.KeyArea; -import com.gpl.rpg.atcontentstudio.model.maps.MapChange; -import com.gpl.rpg.atcontentstudio.model.maps.MapObject; -import com.gpl.rpg.atcontentstudio.model.maps.MapObjectGroup; -import com.gpl.rpg.atcontentstudio.model.maps.ReplaceArea; -import com.gpl.rpg.atcontentstudio.model.maps.RestArea; -import com.gpl.rpg.atcontentstudio.model.maps.ScriptArea; -import com.gpl.rpg.atcontentstudio.model.maps.SignArea; -import com.gpl.rpg.atcontentstudio.model.maps.SpawnArea; -import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.maps.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; +import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.utils.DesktopIntegration; import com.gpl.rpg.atcontentstudio.utils.FileUtils; import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideTabbedPane; - -public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListener{ - - private static final long serialVersionUID = -3079451876618342442L; - - - Map editorTabs = new LinkedHashMap(); - JideTabbedPane editorTabsHolder; - - private JButton reload; - - private RSyntaxTextArea editorPane; - - private IntegerBasedCheckBox outsideBox; - @SuppressWarnings("rawtypes") - private JComboBox colorFilterBox; - private LayerListModel layerListModel; - @SuppressWarnings("rawtypes") - private JList layerList; - private tiled.core.MapLayer selectedLayer; - private JButton addTileLayer; - private JButton addObjectGroup; - private JButton deleteLayer; - - private JPanel layerDetailsPane; - private BooleanBasedCheckBox layerVisibleBox; - private JCheckBox groupActiveForNewGame; - private JTextField layerNameField; - private MapObjectsListModel groupObjectsListModel; - @SuppressWarnings("rawtypes") - private JList groupObjectsList; - private MapObject selectedMapObject; - private JButton addMapchange; - private JButton addSpawn; - private JButton addRest; - private JButton addKey; - private JButton addReplace; - private JButton addScript; - private JButton addContainer; - private JButton addSign; - private JButton deleteObject; - - private JPanel mapObjectSettingsPane; - @SuppressWarnings("rawtypes") - private JComboBox droplistBox; - @SuppressWarnings("rawtypes") - private JComboBox dialogueBox; - @SuppressWarnings("rawtypes") - private JComboBox mapBox; - private JTextField areaField; - @SuppressWarnings("rawtypes") - private JComboBox targetAreaCombo; - @SuppressWarnings("rawtypes") - private JComboBox evaluateTriggerBox; - private JSpinner quantityField; - private JSpinner respawnSpeedField; - private JCheckBox spawnActiveForNewGame; - private JCheckBox spawnIgnoreAreas; - private JTextField spawngroupField; - @SuppressWarnings("rawtypes") - private JList npcList; - private SpawnGroupNpcListModel npcListModel; - - @SuppressWarnings("rawtypes") - private JComboBox requirementTypeCombo; - private JPanel requirementParamsPane; - @SuppressWarnings("rawtypes") - private JComboBox requirementObj; - private JComponent requirementObjId; - private JComponent requirementValue; - private BooleanBasedCheckBox requirementNegated; - - @SuppressWarnings("rawtypes") - private JList replacementsList; - private ReplacementsListModel replacementsListModel; - private ReplaceArea.Replacement selectedReplacement; - private JButton addReplacement; - private JButton deleteReplacement; - private JPanel replacementEditPane; - @SuppressWarnings("rawtypes") - private JComboBox sourceLayer; - @SuppressWarnings("rawtypes") - private JComboBox targetLayer; - - private TMXViewer tmxViewer; - - public TMXMapEditor(TMXMap map) { - this.target = map; - this.name = map.getDesc(); - this.icon = new ImageIcon(DefaultIcons.getTiledIconIcon()); - - map.addMapChangedOnDiskListener(this); - - setLayout(new BorderLayout()); - editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); - editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); - editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); - editorTabsHolder.setShowCloseButtonOnTab(false); - add(editorTabsHolder, BorderLayout.CENTER); - - JScrollPane tmxScroller = new JScrollPane(getTmxEditorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - JScrollPane xmlScroller = new JScrollPane(getXmlEditorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - //JScrollPane replScroller = new JScrollPane(getReplacementSimulatorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - xmlScroller.getVerticalScrollBar().setUnitIncrement(16); - editorTabsHolder.add("TMX", tmxScroller); - editorTabsHolder.add("XML", xmlScroller); - //editorTabsHolder.add("Replacements", replScroller); - editorTabsHolder.add("Testing", getReplacementSimulatorPane()); - - } - - - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public JPanel getTmxEditorPane() { - final TMXMap map = (TMXMap) target; - final FieldUpdateListener listener = new MapFieldUpdater(); - - ScrollablePanel pane = new ScrollablePanel(); - pane.setScrollableWidth( ScrollablePanel.ScrollableSizeHint.FIT ); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - - addLabelField(pane, "TMX File: ", ((TMXMap)target).tmxFile.getAbsolutePath()); - createButtonPane(pane, map.getProject(), map, listener); - outsideBox = addIntegerBasedCheckBox(pane, "Map is outdoors", map.outside, map.writable, listener); - colorFilterBox = addEnumValueBox(pane, "Color Filter", TMXMap.ColorFilter.values(), map.colorFilter, map.writable, listener); - - JSplitPane layersViewSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); - layerListModel = new LayerListModel(map); - layerList = new JList(layerListModel); - layerList.setCellRenderer(new LayerListRenderer()); - layerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - JScrollPane layerListScroller = new JScrollPane(layerList); - layerListScroller.getVerticalScrollBar().setUnitIncrement(16); - layerList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedLayer = (tiled.core.MapLayer) layerList.getSelectedValue(); - selectedMapObject = null; - if (selectedLayer != null && map.writable) { - deleteLayer.setEnabled(true); - } else { - deleteLayer.setEnabled(false); - } - updateLayerDetailsPane(layerDetailsPane, selectedLayer, listener); - listener.valueChanged(layerList, selectedLayer); - } - }); - JPanel layersListPane = new JPanel(); - layersListPane.setLayout(new JideBoxLayout(layersListPane, JideBoxLayout.PAGE_AXIS, 6)); - layersListPane.add(layerListScroller, JideBoxLayout.VARY); - addTileLayer = new JButton(new ImageIcon(DefaultIcons.getCreateTileLayerIcon())); - addTileLayer.setToolTipText("Create new tile layer (graphics layer)."); - addTileLayer.setEnabled(map.writable); - addTileLayer.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - tiled.core.TileLayer layer = new tiled.core.TileLayer(map.tmxMap.getWidth(), map.tmxMap.getHeight()); - layerListModel.addObject(layer); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addObjectGroup = new JButton(new ImageIcon(DefaultIcons.getCreateObjectGroupIcon())); - addObjectGroup.setToolTipText("Create new object group."); - addObjectGroup.setEnabled(map.writable); - addObjectGroup.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - layerListModel.addObject(new tiled.core.ObjectGroup()); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - deleteLayer = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deleteLayer.setToolTipText("Delete selected layer/group."); - deleteLayer.setEnabled(false); - deleteLayer.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - layerListModel.removeObject(selectedLayer); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - JPanel layersButtonsPane = new JPanel(); - layersButtonsPane.setLayout(new JideBoxLayout(layersButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - layersButtonsPane.add(addTileLayer, JideBoxLayout.FIX); - layersButtonsPane.add(addObjectGroup, JideBoxLayout.FIX); - layersButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - layersButtonsPane.add(deleteLayer, JideBoxLayout.FIX); - layersListPane.add(layersButtonsPane, JideBoxLayout.FIX); - layersViewSplitPane.setLeftComponent(layersListPane); - layerDetailsPane = new JPanel(); - layerDetailsPane.setLayout(new JideBoxLayout(layerDetailsPane, JideBoxLayout.PAGE_AXIS, 6)); - layersViewSplitPane.setRightComponent(layerDetailsPane); - pane.add(layersViewSplitPane, JideBoxLayout.FIX); - - tmxViewer = new TMXViewer(((TMXMap)target), listener); - JScrollPane tmxScroller = new JScrollPane(tmxViewer); - tmxScroller.getVerticalScrollBar().setUnitIncrement(16); - tmxScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); - tmxScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); - pane.add(tmxScroller, JideBoxLayout.FIX); - - addTMXMapSpritesheetsList(pane, ((TMXMap)target)); - - addBacklinksList(pane, map); - - pane.add(new JPanel(), JideBoxLayout.VARY); - return pane; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void updateLayerDetailsPane(JPanel pane, tiled.core.MapLayer selected, final FieldUpdateListener listener) { - final TMXMap map = (TMXMap)target; - pane.removeAll(); - if (selected == null) { - return; - } else if (selected instanceof tiled.core.TileLayer) { - layerNameField = addTextField(pane, "Layer name: ", selected.getName(), map.writable, listener); - layerVisibleBox = addBooleanBasedCheckBox(pane, "Visible", selected.isVisible(), true, listener); - pane.add(new JPanel(), JideBoxLayout.VARY); - } else if (selected instanceof tiled.core.ObjectGroup) { - JSplitPane objectGroupDetailsSplitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); - JPanel groupDetailPane = new JPanel(); - groupDetailPane.setLayout(new JideBoxLayout(groupDetailPane, JideBoxLayout.PAGE_AXIS, 6)); - objectGroupDetailsSplitter.setLeftComponent(groupDetailPane); - layerNameField = addTextField(groupDetailPane, "Group name: ", selected.getName(), map.writable, listener); - layerVisibleBox = addBooleanBasedCheckBox(groupDetailPane, "Visible", selected.isVisible(), true, listener); - MapObjectGroup objGroup = null; - for (MapObjectGroup group : map.groups) { - if (group.tmxGroup == selected) { - objGroup = group; - break; - } - } - groupActiveForNewGame = addBooleanBasedCheckBox(groupDetailPane, "Active for new game", objGroup.active, map.writable, listener); - groupObjectsListModel = new MapObjectsListModel(objGroup); - groupObjectsList = new JList(groupObjectsListModel); - groupObjectsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - groupObjectsList.setCellRenderer(new GroupObjectsRenderer()); - JScrollPane groupObjectsScroller = new JScrollPane(groupObjectsList); - groupObjectsScroller.getVerticalScrollBar().setUnitIncrement(16); - groupDetailPane.add(groupObjectsScroller, JideBoxLayout.VARY); - groupObjectsList.addListSelectionListener(new ListSelectionListener() { - - @Override - public void valueChanged(ListSelectionEvent e) { - selectedMapObject = (MapObject) groupObjectsList.getSelectedValue(); - updateMapObjectSettingsPane(mapObjectSettingsPane, selectedMapObject, listener); - listener.valueChanged(groupObjectsList, selectedMapObject); - if (selectedMapObject != null && map.writable) { - deleteObject.setEnabled(true); - } else { - deleteObject.setEnabled(false); - } - } - }); - - addMapchange = new JButton(new ImageIcon(DefaultIcons.getCreateMapchangeIcon())); - addMapchange.setToolTipText("Create new mapchange area."); - addMapchange.setEnabled(map.writable); - addMapchange.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newMapchange(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addSpawn = new JButton(new ImageIcon(DefaultIcons.getCreateSpawnareaIcon())); - addSpawn.setToolTipText("Create new spawn area."); - addSpawn.setEnabled(map.writable); - addSpawn.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newSpawnArea(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addRest = new JButton(new ImageIcon(DefaultIcons.getCreateRestIcon())); - addRest.setToolTipText("Create new rest area."); - addRest.setEnabled(map.writable); - addRest.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newRest(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addKey = new JButton(new ImageIcon(DefaultIcons.getCreateKeyIcon())); - addKey.setToolTipText("Create new key area."); - addKey.setEnabled(map.writable); - addKey.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newKey(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addReplace = new JButton(new ImageIcon(DefaultIcons.getCreateReplaceIcon())); - addReplace.setToolTipText("Create new replace area."); - addReplace.setEnabled(map.writable); - addReplace.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newReplace(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addScript = new JButton(new ImageIcon(DefaultIcons.getCreateScriptIcon())); - addScript.setToolTipText("Create new script area."); - addScript.setEnabled(map.writable); - addScript.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newScript(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addContainer = new JButton(new ImageIcon(DefaultIcons.getCreateContainerIcon())); - addContainer.setToolTipText("Create new container."); - addContainer.setEnabled(map.writable); - addContainer.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newContainer(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - addSign = new JButton(new ImageIcon(DefaultIcons.getCreateSignIcon())); - addSign.setToolTipText("Create new sign post."); - addSign.setEnabled(map.writable); - addSign.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.addObject(MapObject.newSign(new tiled.core.MapObject(0, 0, 32, 32), map)); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - deleteObject = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deleteObject.setToolTipText("Delete selected map object."); - deleteObject.setEnabled(false); - deleteObject.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - groupObjectsListModel.removeObject(selectedMapObject); - map.state = GameDataElement.State.modified; - map.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - targetUpdated(); - } - }); - - JPanel groupButtonsPane1 = new JPanel(); - groupButtonsPane1.setLayout(new JideBoxLayout(groupButtonsPane1, JideBoxLayout.LINE_AXIS, 6)); - groupButtonsPane1.add(addMapchange, JideBoxLayout.FIX); - groupButtonsPane1.add(addSpawn, JideBoxLayout.FIX); - groupButtonsPane1.add(addRest, JideBoxLayout.FIX); - groupButtonsPane1.add(addKey, JideBoxLayout.FIX); - groupButtonsPane1.add(new JPanel(), JideBoxLayout.VARY); - JPanel groupButtonsPane2 = new JPanel(); - groupButtonsPane2.setLayout(new JideBoxLayout(groupButtonsPane2, JideBoxLayout.LINE_AXIS, 6)); - groupButtonsPane2.add(addReplace, JideBoxLayout.FIX); - groupButtonsPane2.add(addScript, JideBoxLayout.FIX); - groupButtonsPane2.add(addContainer, JideBoxLayout.FIX); - groupButtonsPane2.add(addSign, JideBoxLayout.FIX); - groupButtonsPane2.add(new JPanel(), JideBoxLayout.VARY); - groupButtonsPane2.add(deleteObject, JideBoxLayout.FIX); - groupDetailPane.add(groupButtonsPane1, JideBoxLayout.FIX); - groupDetailPane.add(groupButtonsPane2, JideBoxLayout.FIX); - - mapObjectSettingsPane = new JPanel(); - mapObjectSettingsPane.setLayout(new JideBoxLayout(mapObjectSettingsPane, JideBoxLayout.PAGE_AXIS, 6)); - JScrollPane mapObjectSettingsScroller = new JScrollPane(mapObjectSettingsPane); - mapObjectSettingsScroller.getVerticalScrollBar().setUnitIncrement(16); - objectGroupDetailsSplitter.setRightComponent(mapObjectSettingsScroller); - pane.add(objectGroupDetailsSplitter, JideBoxLayout.VARY); - } - pane.revalidate(); - pane.repaint(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void updateMapObjectSettingsPane(JPanel pane, final MapObject selected, final FieldUpdateListener listener) { - pane.removeAll(); - boolean needVary = true; - if (selected instanceof ContainerArea) { - droplistBox = addDroplistBox(pane, ((TMXMap)target).getProject(), "Droplist: ", ((ContainerArea)selected).droplist, ((TMXMap)target).writable, listener); - } else if (selected instanceof KeyArea) { - areaField = addTextField(pane, "Area ID: ", ((KeyArea)selected).name, ((TMXMap)target).writable, listener); - dialogueBox = addDialogueBox(pane, ((TMXMap)target).getProject(), "Message when locked: ", ((KeyArea)selected).dialogue, ((TMXMap)target).writable, listener); - requirementTypeCombo = addEnumValueBox(pane, "Requirement type: ", Requirement.RequirementType.values(), ((KeyArea)selected).requirement.type, ((TMXMap)target).writable, listener); - requirementParamsPane = new JPanel(); - requirementParamsPane.setLayout(new JideBoxLayout(requirementParamsPane, JideBoxLayout.PAGE_AXIS, 6)); - pane.add(requirementParamsPane, JideBoxLayout.FIX); - updateRequirementParamsPane(requirementParamsPane, ((KeyArea)selected).requirement, listener); - } else if (selected instanceof MapChange) { - areaField = addTextField(pane, "Area ID: ", ((MapChange)selected).name, ((TMXMap)target).writable, listener); - mapBox = addMapBox(pane, ((TMXMap)target).getProject(), "Target map: ", ((MapChange)selected).map, ((TMXMap)target).writable, listener); - targetAreaCombo = new JComboBox(); - if (((MapChange)selected).map != null) { - ((MapChange)selected).map.link(); - targetAreaCombo.setModel(new DefaultComboBoxModel((((MapChange)selected).map.getMapchangesNames().toArray()))); - } - targetAreaCombo.setEditable(false); - targetAreaCombo.setEnabled(((TMXMap)target).writable); - targetAreaCombo.setSelectedItem(((MapChange)selected).place_id); - JPanel tACPane = new JPanel(); - tACPane.setLayout(new JideBoxLayout(tACPane, JideBoxLayout.LINE_AXIS, 6)); - tACPane.add(new JLabel("Target mapchange area ID: "), JideBoxLayout.FIX); - tACPane.add(targetAreaCombo, JideBoxLayout.VARY); - JButton nullifyTargetArea = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tACPane.add(nullifyTargetArea, JideBoxLayout.FIX); - nullifyTargetArea.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - targetAreaCombo.setSelectedItem(null); - listener.valueChanged(targetAreaCombo, null); - } - }); - targetAreaCombo.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(targetAreaCombo, targetAreaCombo.getSelectedItem()); - } - }); - pane.add(tACPane, JideBoxLayout.FIX); - } else if (selected instanceof ReplaceArea) { - areaField = addTextField(pane, "Area ID: ", ((ReplaceArea)selected).name, ((TMXMap)target).writable, listener); - requirementTypeCombo = addEnumValueBox(pane, "Requirement type: ", Requirement.RequirementType.values(), ((ReplaceArea)selected).requirement.type, ((TMXMap)target).writable, listener); - requirementParamsPane = new JPanel(); - requirementParamsPane.setLayout(new JideBoxLayout(requirementParamsPane, JideBoxLayout.PAGE_AXIS, 6)); - pane.add(requirementParamsPane, JideBoxLayout.FIX); - updateRequirementParamsPane(requirementParamsPane, ((ReplaceArea)selected).requirement, listener); - - CollapsiblePanel replacementListPane = new CollapsiblePanel("Replacements"); - replacementListPane.setLayout(new JideBoxLayout(replacementListPane, JideBoxLayout.PAGE_AXIS)); - replacementsListModel = new ReplacementsListModel((ReplaceArea) selected); - replacementsList = new JList(replacementsListModel); - replacementsList.setCellRenderer(new ReplacementsListRenderer((ReplaceArea) selected)); - replacementListPane.add(new JScrollPane(replacementsList), JideBoxLayout.VARY); - - JPanel replacementListButtonsPane = new JPanel(); - replacementListButtonsPane.setLayout(new JideBoxLayout(replacementListButtonsPane, JideBoxLayout.LINE_AXIS)); - addReplacement = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - replacementListButtonsPane.add(addReplacement, JideBoxLayout.FIX); - addReplacement.setEnabled(((TMXMap)target).writable); - addReplacement.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - replacementsListModel.addObject(null, null); - } - }); - deleteReplacement = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - replacementListButtonsPane.add(deleteReplacement, JideBoxLayout.FIX); - deleteReplacement.setEnabled(false); - deleteReplacement.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - replacementsListModel.removeObject(selectedReplacement); - } - }); - replacementListButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - replacementListPane.add(replacementListButtonsPane, JideBoxLayout.FIX); - - replacementEditPane = new JPanel(); - replacementListPane.add(replacementEditPane, JideBoxLayout.FIX); - - pane.add(new JScrollPane(replacementListPane), JideBoxLayout.VARY); - - - replacementsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedReplacement = (ReplaceArea.Replacement)replacementsList.getSelectedValue(); - updateReplacementsEditPane(replacementEditPane, (ReplaceArea)selected, selectedReplacement, listener); - deleteReplacement.setEnabled(((TMXMap)target).writable); - } - }); - - - - } else if (selected instanceof RestArea) { - areaField = addTextField(pane, "Area ID: ", ((RestArea)selected).name, ((TMXMap)target).writable, listener); - } else if (selected instanceof ScriptArea) { - evaluateTriggerBox = addEnumValueBox(pane, "Evaluate on every: ", ScriptArea.EvaluationTrigger.values(), ((ScriptArea)selected).trigger_type, ((TMXMap)target).writable, listener); - dialogueBox = addDialogueBox(pane, ((TMXMap)target).getProject(), "Script: ", ((ScriptArea)selected).dialogue, ((TMXMap)target).writable, listener); - } else if (selected instanceof SignArea) { - dialogueBox = addDialogueBox(pane, ((TMXMap)target).getProject(), "Message: ", ((SignArea)selected).dialogue, ((TMXMap)target).writable, listener); - } else if (selected instanceof SpawnArea) { - areaField = addTextField(pane, "Spawn area ID: ", ((SpawnArea)selected).name, ((TMXMap)target).writable, listener); - spawngroupField = addTextField(pane, "Spawn group ID: ", ((SpawnArea)selected).spawngroup_id, ((TMXMap)target).writable, listener); - quantityField = addIntegerField(pane, "Number of spawned NPCs: ", ((SpawnArea)selected).quantity, false, ((TMXMap)target).writable, listener); - respawnSpeedField = addIntegerField(pane, "Respawn-Speed of NPCs: ", ((SpawnArea)selected).respawnSpeed, false, ((TMXMap)target).writable, listener); - spawnActiveForNewGame = addBooleanBasedCheckBox(pane, "Active in a new game: ", ((SpawnArea)selected).active, ((TMXMap)target).writable, listener); - spawnIgnoreAreas = addBooleanBasedCheckBox(pane, "Monsters can walk on other game objects: ", ((SpawnArea)selected).ignoreAreas, ((TMXMap)target).writable, listener); - npcListModel = new SpawnGroupNpcListModel((SpawnArea) selected); - npcList = new JList(npcListModel); - npcList.setCellRenderer(new GDERenderer(true, ((TMXMap)target).writable)); - npcList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - npcList.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - ATContentStudio.frame.openEditor((JSONElement)npcList.getSelectedValue()); - ATContentStudio.frame.selectInTree((JSONElement)npcList.getSelectedValue()); - } - } - }); - npcList.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - ATContentStudio.frame.openEditor((JSONElement)npcList.getSelectedValue()); - ATContentStudio.frame.selectInTree((JSONElement)npcList.getSelectedValue()); - } - } - }); - JScrollPane npcListScroller = new JScrollPane(npcList); - npcListScroller.getVerticalScrollBar().setUnitIncrement(16); - pane.add(npcListScroller, JideBoxLayout.VARY); - needVary = false; - } - if (needVary) pane.add(new JPanel(), JideBoxLayout.VARY); - pane.revalidate(); - pane.repaint(); - } - - public void updateRequirementParamsPane(JPanel pane, Requirement requirement, FieldUpdateListener listener) { - boolean writable = ((TMXMap)target).writable; - Project project = ((TMXMap)target).getProject(); - pane.removeAll(); - if (requirement.type != null) { - switch (requirement.type) { - case consumedBonemeals: - case spentGold: - requirementObj = null; - requirementObjId = null; - requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); - break; - case random: - requirementObj = null; - requirementObjId = addChanceField(pane, "Chance: ", requirement.required_obj_id, "50/100", writable, listener); - requirementValue = null; - break; - case hasActorCondition: - requirementObj = addActorConditionBox(pane, project, "Actor Condition: ", (ActorCondition) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = null; - break; - case inventoryKeep: - case inventoryRemove: - case usedItem: - case wear: - case wearRemove: - requirementObj = addItemBox(pane, project, "Item: ", (Item) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); - break; - case killedMonster: - requirementObj = addNPCBox(pane, project, "Monster: ", (NPC) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); - break; - case questLatestProgress: - case questProgress: - requirementObj = addQuestBox(pane, project, "Quest: ", (Quest) requirement.required_obj, writable, listener); - requirementObjId = null; - requirementValue = addQuestStageBox(pane, project, "Quest stage: ", requirement.required_value, writable, listener, (Quest) requirement.required_obj, requirementObj); - break; - case skillLevel: - Requirement.SkillID skillId = null; - try { - skillId = requirement.required_obj_id == null ? null : Requirement.SkillID.valueOf(requirement.required_obj_id); - } catch(IllegalArgumentException e) {} - requirementObj = addEnumValueBox(pane, "Skill ID:", Requirement.SkillID.values(), skillId, writable, listener); - requirementObjId = null;//addTextField(pane, "Skill ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Level: ", requirement.required_value, false, writable, listener); - break; - case timerElapsed: - requirementObj = null; - requirementObjId = addTextField(pane, "Timer ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Timer value: ", requirement.required_value, false, writable, listener); - break; - case factionScore: - requirementObj = null; - requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Minimum score: ", requirement.required_value, true, writable, listener); - break; - case factionScoreEquals: - requirementObj = null; - requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Exact value: ", requirement.required_value, true, writable, listener); - break; - case date: - requirementObj = null; - requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Minimum date value: ", requirement.required_value, true, writable, listener); - break; - case dateEquals: - requirementObj = null; - requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Exact date value: ", requirement.required_value, true, writable, listener); - break; - case time: - requirementObj = null; - requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Minimum time value: ", requirement.required_value, true, writable, listener); - break; - case timeEquals: - requirementObj = null; - requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); - requirementValue = addIntegerField(pane, "Exact time value: ", requirement.required_value, true, writable, listener); - break; - } - } - requirementNegated = addBooleanBasedCheckBox(pane, "Negate this requirement.", requirement.negated, writable, listener); - pane.revalidate(); - pane.repaint(); - } - - public void updateReplacementsEditPane(JPanel pane, ReplaceArea area, ReplaceArea.Replacement replacement, final FieldUpdateListener listener) { - boolean writable = ((TMXMap)target).writable; - pane.removeAll(); - - sourceLayer = new JComboBox(new ReplacementsLayersComboModel(area, true, replacement.sourceLayer)); - targetLayer = new JComboBox(new ReplacementsLayersComboModel(area, false, replacement.targetLayer)); - - sourceLayer.setEnabled(writable); - targetLayer.setEnabled(writable); - - sourceLayer.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceLayer, sourceLayer.getModel().getSelectedItem()); - } - }); - targetLayer.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(targetLayer, targetLayer.getModel().getSelectedItem()); - } - }); - - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.LINE_AXIS)); - pane.add(new JLabel("Replace "), JideBoxLayout.FIX); - pane.add(sourceLayer, JideBoxLayout.FIX); - pane.add(new JLabel(" by "), JideBoxLayout.FIX); - pane.add(targetLayer, JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - } - - public JPanel getXmlEditorPane() { - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - editorPane = new RSyntaxTextArea(); - editorPane.setText(((TMXMap)target).toXml()); - editorPane.setEditable(false); - editorPane.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML); - editorPane.setFont(editorPane.getFont().deriveFont(ATContentStudio.SCALING * editorPane.getFont().getSize())); - pane.add(editorPane, JideBoxLayout.VARY); - - return pane; - } - - public void updateXmlViewText(String text) { - editorPane.setText(text); - } - - - - public JPanel getReplacementSimulatorPane() { - JPanel replacementSimulator = new JPanel(); - replacementSimulator.setLayout(new JideBoxLayout(replacementSimulator, JideBoxLayout.PAGE_AXIS)); - JPanel toolsPane = new JPanel(); - toolsPane.setLayout(new JideBoxLayout(toolsPane, JideBoxLayout.LINE_AXIS)); - final JCheckBox walkableVisibleBox = new JCheckBox("Show \""+TMXMap.WALKABLE_LAYER_NAME+"\" layer."); - final JCheckBox showHeroBox = new JCheckBox("Show hero on walkable tiles under the mouse pointer."); - final JCheckBox showTooltipBox = new JCheckBox("Show tooltip with stack of tiles."); - JPanel areasActivationPane = new JPanel(); - areasActivationPane.setLayout(new JideBoxLayout(areasActivationPane, JideBoxLayout.PAGE_AXIS)); - TreeModel areasTreeModel = new ReplaceAreasActivationTreeModel(); - final JTree areasTree = new JTree(areasTreeModel); - areasTree.setEditable(false); - areasTree.setRootVisible(false); - areasTree.setCellRenderer(new ReplaceAreasActivationTreeCellRenderer()); - areasActivationPane.add(new JScrollPane(areasTree), JideBoxLayout.FIX); - final JToggleButton activate = new JToggleButton("Activate ReplaceArea(s)"); - areasActivationPane.add(activate, JideBoxLayout.VARY); - final TMXReplacementViewer viewer = new TMXReplacementViewer((TMXMap)target); - JPanel activateAndViewPane = new JPanel(); - activateAndViewPane.setLayout(new JideBoxLayout(activateAndViewPane, JideBoxLayout.LINE_AXIS)); - - activateAndViewPane.add(areasActivationPane, JideBoxLayout.FIX); - activateAndViewPane.add(new JScrollPane(viewer), JideBoxLayout.VARY); - - toolsPane.add(walkableVisibleBox, JideBoxLayout.FIX); - toolsPane.add(showTooltipBox, JideBoxLayout.FIX); - toolsPane.add(showHeroBox, JideBoxLayout.FIX); - toolsPane.add(new JPanel(), JideBoxLayout.VARY); - - replacementSimulator.add(toolsPane, JideBoxLayout.FIX); - replacementSimulator.add(activateAndViewPane, JideBoxLayout.VARY); - - walkableVisibleBox.setSelected(viewer.showWalkable); - walkableVisibleBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - viewer.showWalkable = walkableVisibleBox.isSelected(); - viewer.revalidate(); - viewer.repaint(); - } - }); - - showHeroBox.setSelected(viewer.showHeroWithMouse); - showHeroBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - viewer.showHeroWithMouse = showHeroBox.isSelected(); - } - }); - showTooltipBox.setSelected(viewer.showTooltip); - showTooltipBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - viewer.showTooltip = showTooltipBox.isSelected(); - } - }); - activate.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (areasTree.getSelectionPaths() == null) return; - for (TreePath paths : areasTree.getSelectionPaths()) { - Object target = paths.getLastPathComponent(); - if (target instanceof ReplaceArea) { - viewer.activeReplacements.put((ReplaceArea) target, activate.isSelected()); - viewer.updateLayers(); - viewer.revalidate(); - viewer.repaint(); - } else if (target instanceof MapObjectGroup) { - for (MapObject obj : ((MapObjectGroup)target).mapObjects) { - if (obj instanceof ReplaceArea) { - viewer.activeReplacements.put((ReplaceArea) obj, activate.isSelected()); - } - viewer.updateLayers(); - viewer.revalidate(); - viewer.repaint(); - } - } - - } - } - }); - areasTree.addTreeSelectionListener(new TreeSelectionListener() { - @Override - public void valueChanged(TreeSelectionEvent e) { - ReplaceArea oldHighlight = viewer.highlighted; - viewer.highlighted = null; - if (areasTree.getSelectionPaths() == null) return; - for (TreePath paths : areasTree.getSelectionPaths()) { - Object target = paths.getLastPathComponent(); - if (target instanceof ReplaceArea) { - activate.setSelected(viewer.activeReplacements.get((ReplaceArea) target)); - viewer.highlighted = (ReplaceArea)target; - } else if (target instanceof MapObjectGroup) { - for (MapObject obj : ((MapObjectGroup)target).mapObjects) { - activate.setSelected(true); - if (obj instanceof ReplaceArea) { - if (!viewer.activeReplacements.get((ReplaceArea) obj)) { - activate.setSelected(false); - } - } - } - } - } - if (oldHighlight != viewer.highlighted) { - viewer.revalidate(); - viewer.repaint(); - } - } - }); - - return replacementSimulator; - } - - public class ReplaceAreasActivationTreeModel implements TreeModel { - - @Override - public Object getRoot() { - return target; - } - - @Override - public Object getChild(Object parent, int index) { - int i = index; - if (parent instanceof TMXMap) { - for (MapObjectGroup group : ((TMXMap)parent).groups) { - for (MapObject obj : group.mapObjects) { - if (obj instanceof ReplaceArea) { - if (i == 0) return group; - i--; - break; - } - } - } - } else if (parent instanceof MapObjectGroup) { - for (MapObject obj : ((MapObjectGroup)parent).mapObjects) { - if (obj instanceof ReplaceArea) { - if (i == 0) return obj; - i--; - } - } - } - return null; - } - - @Override - public int getChildCount(Object parent) { - int count = 0; - if (parent instanceof TMXMap) { - for (MapObjectGroup group : ((TMXMap)parent).groups) { - for (MapObject obj : group.mapObjects) { - if (obj instanceof ReplaceArea) { - count++; - break; - } - } - } - } else if (parent instanceof MapObjectGroup) { - for (MapObject obj : ((MapObjectGroup)parent).mapObjects) { - if (obj instanceof ReplaceArea) { - count++; - } - } - } - return count; - } - - @Override - public boolean isLeaf(Object node) { - return node instanceof ReplaceArea; - } - - @Override - public void valueForPathChanged(TreePath path, Object newValue) { - // TODO Auto-generated method stub - - } - - @Override - public int getIndexOfChild(Object parent, Object child) { - int index = 0; - if (parent instanceof TMXMap) { - for (MapObjectGroup group : ((TMXMap)parent).groups) { - if (group == child) return index; - for (MapObject obj : group.mapObjects) { - if (obj instanceof ReplaceArea) { - index++; - break; - } - } - } - } else if (parent instanceof MapObjectGroup) { - for (MapObject obj : ((MapObjectGroup)parent).mapObjects) { - if (obj == child) return index; - if (obj instanceof ReplaceArea) { - index++; - } - } - } - return index; - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addTreeModelListener(TreeModelListener l) { - listeners.add(l); - } - - @Override - public void removeTreeModelListener(TreeModelListener l) { - listeners.remove(l); - } - - } - - public class ReplaceAreasActivationTreeCellRenderer extends DefaultTreeCellRenderer { - - private static final long serialVersionUID = 3988638353699460533L; - - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { - Component c = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); - - if (c instanceof JLabel) { - JLabel label = (JLabel)c; - - if (value instanceof MapObjectGroup) { - label.setText(((MapObjectGroup)value).name); - label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); - } else if (value instanceof ReplaceArea) { - label.setText(((ReplaceArea)value).name); - label.setIcon(new ImageIcon(DefaultIcons.getReplaceIcon())); - } - } - - return c; - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static JList addTMXMapSpritesheetsList(JPanel pane, TMXMap tmxMap) { - final JList list = new JList(new TMXMapSpritesheetsListModel(tmxMap)); - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - ATContentStudio.frame.openEditor((Spritesheet)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((Spritesheet)list.getSelectedValue()); - } - } - }); - list.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - ATContentStudio.frame.openEditor((Spritesheet)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((Spritesheet)list.getSelectedValue()); - } - } - }); - list.setCellRenderer(new SpritesheetCellRenderer(true)); - JScrollPane scroller = new JScrollPane(list); - scroller.setBorder(BorderFactory.createTitledBorder("Spritesheets used in this map.")); - pane.add(scroller, JideBoxLayout.FIX); - return list; - } - - @SuppressWarnings("rawtypes") - public class LayerListModel implements ListenerListModel { - - public TMXMap map; - - public LayerListModel(TMXMap map) { - this.map = map; - } - - @Override - public int getSize() { - return map.tmxMap.getLayerCount(); - } - - @Override - public Object getElementAt(int index) { - return map.tmxMap.getLayer(index); - } - - - public void objectChanged(tiled.core.MapLayer layer) { - int index = map.tmxMap.getLayerIndex(layer); - notifyListeners(ListDataEvent.CONTENTS_CHANGED, index, index); - - } - - public void addObject(tiled.core.MapLayer layer) { - map.addLayer(layer); - int index = map.tmxMap.getLayerIndex(layer); - notifyListeners(ListDataEvent.INTERVAL_ADDED, index, index); - } - - public void removeObject(tiled.core.MapLayer layer) { - int index = map.tmxMap.getLayerIndex(layer); - map.removeLayer(layer); - notifyListeners(ListDataEvent.INTERVAL_REMOVED, index, index); - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public List getListeners() { - return listeners; - } - } - - public class LayerListRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -6182599528961565957L; - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = (JLabel)c; - tiled.core.MapLayer layer = (tiled.core.MapLayer)value; - label.setText(layer.getName()); - if (layer instanceof tiled.core.TileLayer) { - label.setIcon(new ImageIcon(DefaultIcons.getTileLayerIcon())); - } else if (layer instanceof tiled.core.ObjectGroup) { - label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); - } - } - return c; - } - } - - public class ReplacementsListModel extends OrderedListenerListModel { - public ReplacementsListModel(ReplaceArea area) { - super(area); - } - @Override - protected List getItems() { - return source.replacements; - } - - @Override - protected void setItems(List items) { - source.replacements = items; - } - - public void addObject(String source, String target) { - ReplaceArea.Replacement repl = this.source.createReplacement(source, target); - addObject(repl); - } - } - - public class ReplacementsListRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -6182599528961565957L; - public ReplaceArea area; - public ReplacementsListRenderer(ReplaceArea area) { - super(); - this.area = area; - } - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = (JLabel)c; - ReplaceArea.Replacement repl = (ReplaceArea.Replacement)value; - label.setText(repl.sourceLayer+" -> "+repl.targetLayer); - } - return c; - } - } - - public class ReplacementsLayersComboModel implements ComboBoxModel { - ReplaceArea area; - boolean modelForSource; - - public List availableLayers = new ArrayList(); - - public String selected; - - public ReplacementsLayersComboModel(ReplaceArea area, boolean modelForSource, String selected) { - this.area = area; - this.modelForSource = modelForSource; - this.selected = selected; - - availableLayers.add(null); - for (tiled.core.MapLayer layer : ((TMXMap)target).tmxMap.getLayers()) { - if (layer instanceof tiled.core.TileLayer) { - if (modelForSource && !TMXMap.isPaintedLayerName(layer.getName())) { - continue; - } - if (modelForSource && area.hasReplacementFor(layer.getName()) && !layer.getName().equals(selected)) { - continue; - } - availableLayers.add(layer.getName()); - } - } - - } - @Override - public String getElementAt(int index) { - return availableLayers.get(index); - } - @Override - public Object getSelectedItem() { - return selected; - } - @Override - public int getSize() { - return availableLayers.size(); - } - - List listeners = new CopyOnWriteArrayList(); - @Override - public void addListDataListener(ListDataListener l) { - listeners.add(l); - } - - @Override - public void removeListDataListener(ListDataListener l) { - listeners.remove(l); - } - @Override - public void setSelectedItem(Object anItem) { - selected = (String)anItem; - } - } - - public class MapObjectsListModel extends OrderedListenerListModel { - public MapObjectsListModel(MapObjectGroup group) { - super(group); - } - - @Override - protected List getItems() { - return source.mapObjects; - } - - @Override - protected void setItems(List items) { - source.mapObjects = items; - } - } - - public class GroupObjectsRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -6182599528961565957L; - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - ((JLabel)c).setText(((MapObject)value).name); - ((JLabel)c).setIcon(new ImageIcon(((MapObject)value).getIcon())); - } - return c; - } - } - - - public class SpawnGroupNpcListModel extends OrderedListenerListModel { - public SpawnGroupNpcListModel(SpawnArea area) { - super(area); - } - - @Override - protected List getItems() { - return source.spawnGroup; - } - - @Override - protected void setItems(List items) { - source.spawnGroup = items; - } - } - - - public class TMXViewer extends JPanel implements Scrollable { - - private static final long serialVersionUID = 2845032142029325865L; - - - public tiled.core.MapObject highlighted = null; - private MapRenderer renderer; - private FieldUpdateListener listener; - private TMXMap map; - - public boolean resizing = false; - public boolean moving = false; - - public Rectangle getResizeHitArea() { - //16x16 px square in the lower right corner of area - return new Rectangle(selectedMapObject.x + selectedMapObject.w - 16, selectedMapObject.y + selectedMapObject.h - 16, 16, 16); - } - - - public Rectangle getMoveHitArea() { - //16x16 px square in the upper left corner of area - return new Rectangle(selectedMapObject.x, selectedMapObject.y, 16, 16); - } - - public Rectangle getSelectHitArea(MapObject obj) { - //16x16 px square in the upper left corner of area - return new Rectangle(obj.x, obj.y, 16, 16); - } - - public TMXViewer(final TMXMap map, FieldUpdateListener listener) { - this.listener = listener; - renderer = createRenderer(map.tmxMap); - this.map = map; - - setPreferredSize(renderer.getMapSize()); - setOpaque(true); - - addMouseListener(new MouseAdapter() { - - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - if (!moving && !resizing) { - select: for (MapObjectGroup group : map.groups) { - if (group.visible) { - for (MapObject obj : group.mapObjects) { - if (getSelectHitArea(obj).contains(e.getPoint())) { - TMXMapEditor.this.selectMapObject(obj); - break select; - } - } - } - } - } - } - } - }); - - if (((TMXMap)target).writable) { - addMouseListener(new MouseAdapter() { - - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - resizing = false; - moving = false; - } - } - - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - if (selectedMapObject != null && selectedLayer.isVisible()) { - if (getResizeHitArea().contains(e.getPoint())) { - resizing = true; - } else if (getMoveHitArea().contains(e.getPoint())) { - moving = true; - } - } - } - } - - }); - - addMouseMotionListener(new MouseMotionListener() { - @Override - public void mouseMoved(MouseEvent e) { - if (selectedMapObject == null) return; - if (!resizing && !moving) { - if (getResizeHitArea().contains(e.getPoint())) { - setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)); - } else if (getMoveHitArea().contains(e.getPoint())) { - setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); - } else { - setCursor(Cursor.getDefaultCursor()); - } - } - } - - @Override - public void mouseDragged(MouseEvent e) { - if (selectedMapObject == null) return; - boolean valueChanged = false; - if (resizing) { - Point p = getClosestTileCorner(e.getPoint()); - if (p.x > selectedMapObject.x) { - int oldW = selectedMapObject.w; - selectedMapObject.w = Math.min(p.x - selectedMapObject.x, map.tmxMap.getWidth() * map.tmxMap.getTileWidth()); - if (selectedMapObject.w != oldW) valueChanged = true; - } - if (p.y > selectedMapObject.y) { - int oldH = selectedMapObject.h; - selectedMapObject.h = Math.min(p.y - selectedMapObject.y, map.tmxMap.getHeight() * map.tmxMap.getTileHeight()); - if (selectedMapObject.h != oldH) valueChanged = true; - } - } else if (moving) { - Point p = getClosestTileCorner(e.getPoint()); - if (p.x + selectedMapObject.w <= map.tmxMap.getWidth() * map.tmxMap.getTileWidth()) { - int oldX = selectedMapObject.x; - selectedMapObject.x = Math.max(p.x, 0); - if (selectedMapObject.x != oldX) valueChanged = true; - } - if (p.y + selectedMapObject.h <= map.tmxMap.getHeight() * map.tmxMap.getTileHeight()) { - int oldY = selectedMapObject.y; - selectedMapObject.y = Math.max(p.y, 0); - if (selectedMapObject.y != oldY) valueChanged = true; - } - } - if (valueChanged) { - TMXViewer.this.listener.valueChanged(TMXViewer.this, null); - TMXViewer.this.revalidate(); - TMXViewer.this.repaint(); - } - } - }); - } - } - - public void setHighlight(tiled.core.MapObject selected) { - highlighted = selected; - invalidate(); - } - - public void paintComponent(Graphics g) { - final Graphics2D g2d = (Graphics2D) g.create(); - final Rectangle clip = g2d.getClipBounds(); - - - // Draw a gray background - g2d.setPaint(new Color(100, 100, 100)); - g2d.fill(clip); - - // Draw each tile map layer - for (tiled.core.MapLayer layer : ((TMXMap)target).tmxMap) { - if (layer instanceof tiled.core.TileLayer && layer.isVisible()) { - renderer.paintTileLayer(g2d, (tiled.core.TileLayer) layer); - } - } - - if (map.colorFilter != null) { - MapColorFilters.applyColorfilter(map.colorFilter, g2d); - } - - - // Draw each map object layer - boolean paintSelected = false; - for (tiled.core.MapLayer layer : ((TMXMap)target).tmxMap) { - if (layer instanceof tiled.core.ObjectGroup && layer.isVisible()) { - paintSelected |= paintObjectGroup(g2d, (tiled.core.ObjectGroup) layer); - } - } - - - - if (paintSelected) { - //TODO make this less ugly..... visually speaking. - g2d.setColor(new Color(190, 20, 20)); - g2d.drawRect(selectedMapObject.x + selectedMapObject.w - 16, selectedMapObject.y + selectedMapObject.h - 16, 15, 15); - g2d.drawRect(selectedMapObject.x + selectedMapObject.w - 12, selectedMapObject.y + selectedMapObject.h - 12, 11, 11); - drawObject(selectedMapObject, g2d, new Color(190, 20, 20)); - } - - g2d.dispose(); - } - - private boolean paintObjectGroup(Graphics2D g2d, tiled.core.ObjectGroup layer) { - boolean paintSelected = false; - for (MapObjectGroup group : ((TMXMap)target).groups) { - if (group.tmxGroup == layer) { - for (MapObject object : group.mapObjects) { - if (object == selectedMapObject) { - paintSelected = true; - continue; - } else { - drawObject(object, g2d, new Color(20, 20, 190)); - } - } - break; - } - } - return paintSelected; - } - - private MapRenderer createRenderer(tiled.core.Map map) { - switch (map.getOrientation()) { - case tiled.core.Map.ORIENTATION_ORTHOGONAL: - return new OrthogonalRenderer(map); - default: - return null; - } - } - - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } - - public int getScrollableUnitIncrement(Rectangle visibleRect, - int orientation, int direction) { - if (orientation == SwingConstants.HORIZONTAL) - return ((TMXMap)target).tmxMap.getTileWidth(); - else - return ((TMXMap)target).tmxMap.getTileHeight(); - } - - public int getScrollableBlockIncrement(Rectangle visibleRect, - int orientation, int direction) { - if (orientation == SwingConstants.HORIZONTAL) { - final int tileWidth = ((TMXMap)target).tmxMap.getTileWidth(); - return (visibleRect.width / tileWidth - 1) * tileWidth; - } else { - final int tileHeight = ((TMXMap)target).tmxMap.getTileHeight(); - return (visibleRect.height / tileHeight - 1) * tileHeight; - } - } - - public boolean getScrollableTracksViewportWidth() { - return false; - } - - public boolean getScrollableTracksViewportHeight() { - return false; - } - - } - - public static class TMXMapSpritesheetsListModel implements ListenerCollectionModel { - TMXMap map; - - public TMXMapSpritesheetsListModel(TMXMap map) { - this.map = map; - } - @Override - public Collection getElements() { - return map.usedSpritesheets; - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public List getListeners() { - return listeners; - } - } - - public static class SpritesheetCellRenderer extends DefaultListCellRenderer { - - private static final long serialVersionUID = 6819681566800482793L; - - private boolean includeType; - - public SpritesheetCellRenderer(boolean includeType) { - super(); - this.includeType = includeType; - - } - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value == null) { - label.setText("none"); - } else { - if (includeType && ((Spritesheet)value).getDataType() != null) { - label.setText(((Spritesheet)value).getDataType().toString()+"/"+((Spritesheet)value).getDesc()); - } else { - label.setText(((Spritesheet)value).getDesc()); - } - if (((Spritesheet)value).getIcon() == null) { - Notification.addError("Unable to find icon for "+((Spritesheet)value).getDesc()); - } else { - label.setIcon(new ImageIcon(((Spritesheet)value).getIcon())); - } - } - return label; - } - } - - @Override - public void targetUpdated() { - this.name = ((TMXMap)target).getDesc(); - updateMessage(); - updateXmlViewText(((TMXMap)target).toXml()); - tmxViewer.repaint(); - tmxViewer.revalidate(); - } - - - - - protected void selectMapObject(MapObject obj) { - for (MapObjectGroup group : ((TMXMap)target).groups) { - if (group.mapObjects.contains(obj)) { - layerList.setSelectedValue(group.tmxGroup, true); - groupObjectsList.setSelectedValue(obj, true); - } - } - } - - public JButton createButtonPane(JPanel pane, final Project proj, final TMXMap map, final FieldUpdateListener listener) { - JPanel savePane = new JPanel(); - savePane.setLayout(new JideBoxLayout(savePane, JideBoxLayout.LINE_AXIS, 6)); - final JButton gdeIcon = new JButton(new ImageIcon(DefaultIcons.getTiledIconImage())); - savePane.add(gdeIcon, JideBoxLayout.FIX); - if (map.writable) { - gdeIcon.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (map.needsSaving()) { - int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You have unsaved changes in ATCS.\nYou'd better save your changes in ATCS before opening this map with the external editor.\nDo you want to save before opening the file?", "Save before opening?", JOptionPane.YES_NO_CANCEL_OPTION); - if (confirm == JOptionPane.CANCEL_OPTION) return; - if (confirm == JOptionPane.YES_OPTION) { - map.save(); - ATContentStudio.frame.nodeChanged(map); - } - } - DesktopIntegration.openTmxMap(map.tmxFile); - } - }); - reload = new JButton("Reload"); - reload.setEnabled(map.changedOnDisk); - savePane.add(reload, JideBoxLayout.FIX); - reload.addActionListener(new ActionListener() { - - @Override - public void actionPerformed(ActionEvent e) { - if (map.needsSaving()) { - int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You modified this map in ATCS. All ATCS-made changes will be lost if you confirm.\n On the other hand, if you save using ATCS, all external changes will be lost.\n Do you want to reload?", "Confirm reload?", JOptionPane.OK_CANCEL_OPTION); - if (confirm == JOptionPane.CANCEL_OPTION) return; - } - reload.setEnabled(false); - (new Thread(){ - public void run() { - map.reload(); - } - }).start(); - } - }); - if (map.getDataType() == GameSource.Type.altered) { - savePane.add(message = new JLabel(ALTERED_MESSAGE), JideBoxLayout.FIX); - } else if (map.getDataType() == GameSource.Type.created) { - savePane.add(message = new JLabel(CREATED_MESSAGE), JideBoxLayout.FIX); - } - JButton save = new JButton(SAVE); - save.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (map.state != TMXMap.State.saved) { - if (map.changedOnDisk) { - int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You modified this map in an external tool. All external changes will be lost if you confirm.\n On the other hand, if you reload in ATCS, all ATCS-made changes will be lost.\n Do you want to save?", "Confirm save?", JOptionPane.OK_CANCEL_OPTION); - if (confirm == JOptionPane.CANCEL_OPTION) return; - File backup = FileUtils.backupFile(map.tmxFile); - if (backup != null) { - JOptionPane.showMessageDialog(TMXMapEditor.this, "The externally-modified file was backed up as "+backup.getAbsolutePath(), "File backed up", JOptionPane.INFORMATION_MESSAGE); - } else { - JOptionPane.showMessageDialog(TMXMapEditor.this, "The externally-modified file could not be backed up.", "File backup failed", JOptionPane.ERROR_MESSAGE); - } - } - map.save(); - ATContentStudio.frame.nodeChanged(map); - } - } - }); - savePane.add(save, JideBoxLayout.FIX); - JButton delete = new JButton(DELETE); - if (map.getDataType() == GameSource.Type.altered) { - delete.setText(REVERT); - } - delete.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ATContentStudio.frame.closeEditor(map); - map.childrenRemoved(new ArrayList()); - map.delete(); - GameDataElement newOne = map.getProject().getMap(map.id); - for (GameDataElement backlink : map.getBacklinks()) { - backlink.elementChanged(map, newOne); - } - } - }); - savePane.add(delete, JideBoxLayout.FIX); - final JButton bookmark = new JButton(new ImageIcon(map.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); - savePane.add(bookmark, JideBoxLayout.FIX); - bookmark.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - if (map.bookmark == null) { - map.getProject().bookmark(map); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); - } else { - map.bookmark.delete(); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); - } - } - }); - } else { - if (proj.getMap(map.id) != map) { - savePane.add(message = new JLabel(ALTERED_EXISTS_MESSAGE), JideBoxLayout.FIX); - JButton makeWritable = new JButton(GO_TO_ALTERED); - makeWritable.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (map.getProject().getMap(map.id) != map) { - ATContentStudio.frame.openEditor(map.getProject().getMap(map.id)); - ATContentStudio.frame.closeEditor(map); - ATContentStudio.frame.selectInTree(map.getProject().getMap(map.id)); - } - } - }); - savePane.add(makeWritable, JideBoxLayout.FIX); - - } else { - savePane.add(message = new JLabel(READ_ONLY_MESSAGE), JideBoxLayout.FIX); - JButton makeWritable = new JButton(ALTER); - makeWritable.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (map.getProject().getMap(map.id) == map) { - map.getProject().makeWritable(map); - } - if (map.getProject().getMap(map.id) != map) { - ATContentStudio.frame.openEditor(map.getProject().getMap(map.id)); - ATContentStudio.frame.closeEditor(map); - ATContentStudio.frame.selectInTree(map.getProject().getMap(map.id)); - } - } - }); - savePane.add(makeWritable, JideBoxLayout.FIX); - } - } - JButton prev = new JButton(new ImageIcon(DefaultIcons.getArrowLeftIcon())); - JButton next = new JButton(new ImageIcon(DefaultIcons.getArrowRightIcon())); - savePane.add(prev, JideBoxLayout.FIX); - savePane.add(next, JideBoxLayout.FIX); - if (map.getParent().getIndex(map) == 0) { - prev.setEnabled(false); - } - if (map.getParent().getIndex(map) == map.getParent().getChildCount() - 1) { - next.setEnabled(false); - } - prev.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ProjectTreeNode prevNode = (ProjectTreeNode) map.getParent().getChildAt(map.getParent().getIndex(map) - 1); - if (prevNode != null && prevNode instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement) prevNode); - } - } - }); - next.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ProjectTreeNode nextNode = (ProjectTreeNode) map.getParent().getChildAt(map.getParent().getIndex(map) + 1); - if (nextNode != null && nextNode instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement) nextNode); - } - } - }); - final JButton bookmark = new JButton(new ImageIcon(map.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); - savePane.add(bookmark, JideBoxLayout.FIX); - bookmark.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - if (map.bookmark == null) { - map.getProject().bookmark(map); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); - } else { - map.bookmark.delete(); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); - } - } - }); - //Placeholder. Fills the eventual remaining space. - savePane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(savePane, JideBoxLayout.FIX); - return gdeIcon; - } - - - private int skipAreaFieldEvents = 0; - - public class MapFieldUpdater implements FieldUpdateListener { - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public void valueChanged(JComponent source, Object value) { - TMXMap map = (TMXMap) target; - boolean modified = true; - if (source == layerNameField) { - selectedLayer.setName((String) value); - if (selectedLayer instanceof tiled.core.ObjectGroup){ - map.getGroup((tiled.core.ObjectGroup) selectedLayer).name = (String) value; - } - layerListModel.objectChanged(selectedLayer); - } else if (source == layerVisibleBox) { - selectedLayer.setVisible(layerVisibleBox.isSelected()); - if (selectedLayer instanceof tiled.core.ObjectGroup) { - map.getGroup((tiled.core.ObjectGroup) selectedLayer).visible = layerVisibleBox.isSelected(); - } - modified = false; - tmxViewer.revalidate(); - tmxViewer.repaint(); - } else if (source == groupActiveForNewGame) { - if (selectedLayer instanceof tiled.core.ObjectGroup) { - map.getGroup((tiled.core.ObjectGroup) selectedLayer).active = groupActiveForNewGame.isSelected(); - } - modified = true; - } else if (source == layerList) { - modified = false; - tmxViewer.revalidate(); - tmxViewer.repaint(); - } else if (source == groupObjectsList) { - modified = false; - tmxViewer.revalidate(); - tmxViewer.repaint(); - } else if (source == areaField) { - if (skipAreaFieldEvents > 0) skipAreaFieldEvents--; - else { - selectedMapObject.name = (String) value; - if (selectedMapObject instanceof KeyArea) { - KeyArea area = (KeyArea) selectedMapObject; - if (area.oldSchoolRequirement) { - area.oldSchoolRequirement = false; - } - } else if (selectedMapObject instanceof ReplaceArea) { - ReplaceArea area = (ReplaceArea) selectedMapObject; - if (area.oldSchoolRequirement) { - area.oldSchoolRequirement = false; - } - } - groupObjectsListModel.objectChanged(selectedMapObject); - } - } else if (source == spawngroupField) { - if (selectedMapObject instanceof SpawnArea) { - SpawnArea area = (SpawnArea)selectedMapObject; - if (area.spawnGroup != null && !area.spawnGroup.isEmpty()) { - for (NPC npc : area.spawnGroup) { - npc.removeBacklink(map); - } - } - area.spawngroup_id = (String) value; - selectedMapObject.link(); - npcList.setModel(new SpawnGroupNpcListModel(area)); - groupObjectsListModel.objectChanged(area); - npcList.revalidate(); - npcList.repaint(); - tmxViewer.revalidate(); - tmxViewer.repaint(); - } - } else if (source == targetAreaCombo) { - if (selectedMapObject instanceof MapChange) { - MapChange area = (MapChange) selectedMapObject; - area.place_id = (String) value; - } - } else if (source == outsideBox) { - map.outside = (Integer)value; - } else if (source == colorFilterBox) { - map.colorFilter = (TMXMap.ColorFilter) value; - tmxViewer.revalidate(); - tmxViewer.repaint(); - } else if (source == droplistBox) { - if (selectedMapObject instanceof ContainerArea) { - ContainerArea area = (ContainerArea)selectedMapObject; - if (area.droplist != null) { - area.droplist.removeBacklink(map); - } - area.droplist = (Droplist) value; - if (area.droplist != null) { - area.name = area.droplist.id; - } else { - area.name = null; - } - groupObjectsListModel.objectChanged(area); - tmxViewer.revalidate(); - tmxViewer.repaint(); - } - } else if (source == dialogueBox) { - if (selectedMapObject instanceof KeyArea) { - KeyArea area = (KeyArea) selectedMapObject; - if (area.dialogue != null) { - area.dialogue.removeBacklink(map); - } - area.dialogue = (Dialogue) value; - if (area.dialogue != null) { - area.dialogue_id = area.dialogue.id; - } else { - area.dialogue_id = null; - } - tmxViewer.revalidate(); - tmxViewer.repaint(); - } else if (selectedMapObject instanceof ScriptArea) { - ScriptArea area = (ScriptArea) selectedMapObject; - if (area.dialogue != null) { - area.dialogue.removeBacklink(map); - } - area.dialogue = (Dialogue) value; - if (area.dialogue != null) { - area.name = area.dialogue.id; - } else { - area.name = null; - } - groupObjectsListModel.objectChanged(area); - tmxViewer.revalidate(); - tmxViewer.repaint(); - } else if (selectedMapObject instanceof SignArea) { - SignArea area = (SignArea) selectedMapObject; - if (area.dialogue != null) { - area.dialogue.removeBacklink(map); - } - area.dialogue = (Dialogue) value; - if (area.dialogue != null) { - area.name = area.dialogue.id; - } else { - area.name = null; - } - groupObjectsListModel.objectChanged(area); - tmxViewer.revalidate(); - tmxViewer.repaint(); - } - } else if (source == mapBox) { - if (selectedMapObject instanceof MapChange) { - MapChange area = (MapChange) selectedMapObject; - if (area.map != null) { - area.map.removeBacklink(map); - } - area.map = (TMXMap) value; - if (area.map != null) { - area.map_id = area.map.id; - targetAreaCombo.setModel(new DefaultComboBoxModel((area.map.getMapchangesNames().toArray()))); - } else { - area.map_id = null; - } - tmxViewer.revalidate(); - tmxViewer.repaint(); - } - } else if (source == evaluateTriggerBox) { - if (selectedMapObject instanceof ScriptArea) { - ScriptArea area = (ScriptArea) selectedMapObject; - area.trigger_type = (ScriptArea.EvaluationTrigger) value; - } - } else if (source == quantityField) { - if (selectedMapObject instanceof SpawnArea) { - SpawnArea area = (SpawnArea) selectedMapObject; - area.quantity = (Integer) value; - } - } else if (source == respawnSpeedField) { - if (selectedMapObject instanceof SpawnArea) { - SpawnArea area = (SpawnArea) selectedMapObject; - area.respawnSpeed = (Integer) value; - } - } else if (source == spawnActiveForNewGame) { - if (selectedMapObject instanceof SpawnArea) { - SpawnArea area = (SpawnArea) selectedMapObject; - area.active = (Boolean) value; - } - } else if (source == spawnIgnoreAreas) { - if (selectedMapObject instanceof SpawnArea) { - SpawnArea area = (SpawnArea) selectedMapObject; - area.ignoreAreas = (Boolean) value; - } - } else if (source == requirementTypeCombo) { - if (selectedMapObject instanceof KeyArea) { - KeyArea area = (KeyArea) selectedMapObject; - area.requirement.changeType((Requirement.RequirementType)requirementTypeCombo.getSelectedItem()); - updateRequirementParamsPane(requirementParamsPane, area.requirement, this); - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } else if (selectedMapObject instanceof ReplaceArea) { - ReplaceArea area = (ReplaceArea) selectedMapObject; - area.requirement.changeType((Requirement.RequirementType)requirementTypeCombo.getSelectedItem()); - updateRequirementParamsPane(requirementParamsPane, area.requirement, this); - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } - } else if (source == requirementObj) { - if (selectedMapObject instanceof KeyArea) { - KeyArea area = (KeyArea) selectedMapObject; - if (area.requirement.type == Requirement.RequirementType.skillLevel) { - area.requirement.required_obj_id = value == null ? null : value.toString(); - } else { - area.requirement.required_obj = (GameDataElement) value; - if (area.requirement.required_obj != null) { - area.requirement.required_obj_id = area.requirement.required_obj.id; - } else { - area.requirement.required_obj_id = null; - } - } - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } else if (selectedMapObject instanceof ReplaceArea) { - ReplaceArea area = (ReplaceArea) selectedMapObject; - if (area.requirement.type == Requirement.RequirementType.skillLevel) { - area.requirement.required_obj_id = value == null ? null : value.toString(); - } else { - area.requirement.required_obj = (GameDataElement) value; - if (area.requirement.required_obj != null) { - area.requirement.required_obj_id = area.requirement.required_obj.id; - } else { - area.requirement.required_obj_id = null; - } - } - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } - } else if (source == requirementObjId) { - if (selectedMapObject instanceof KeyArea) { - KeyArea area = (KeyArea) selectedMapObject; - area.requirement.required_obj_id = (String) value; - area.requirement.required_obj = null; - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } else if (selectedMapObject instanceof ReplaceArea) { - ReplaceArea area = (ReplaceArea) selectedMapObject; - area.requirement.required_obj_id = (String) value; - area.requirement.required_obj = null; - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } - } else if (source == requirementValue) { - if (selectedMapObject instanceof KeyArea) { - KeyArea area = (KeyArea) selectedMapObject; - Quest quest = null; - QuestStage stage; - if (requirementValue instanceof JComboBox) { - quest = ((Quest)area.requirement.required_obj); - if (quest != null && area.requirement.required_value != null) { - stage = quest.getStage(area.requirement.required_value); - if (stage != null) stage.removeBacklink(map); - } - } - area.requirement.required_value = (Integer) value; - if (quest != null) { - stage = quest.getStage(area.requirement.required_value); - if (stage != null) stage.addBacklink(map); - } - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } else if (selectedMapObject instanceof ReplaceArea) { - ReplaceArea area = (ReplaceArea) selectedMapObject; - Quest quest = null; - QuestStage stage; - if (requirementValue instanceof JComboBox) { - quest = ((Quest)area.requirement.required_obj); - if (quest != null && area.requirement.required_value != null) { - stage = quest.getStage(area.requirement.required_value); - if (stage != null) stage.removeBacklink(map); - } - } - area.requirement.required_value = (Integer) value; - if (quest != null) { - stage = quest.getStage(area.requirement.required_value); - if (stage != null) stage.addBacklink(map); - } - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } - } else if (source == requirementNegated) { - if (selectedMapObject instanceof KeyArea) { - KeyArea area = (KeyArea) selectedMapObject; - area.requirement.negated = (Boolean) value; - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } else if (selectedMapObject instanceof ReplaceArea) { - ReplaceArea area = (ReplaceArea) selectedMapObject; - area.requirement.negated = (Boolean) value; - if (area.oldSchoolRequirement) { - area.updateNameFromRequirementChange(); - skipAreaFieldEvents+=2; - areaField.setText(area.name); - } - } - } else if (source == sourceLayer) { - selectedReplacement.sourceLayer = (String)value; - replacementsListModel.objectChanged(selectedReplacement); - groupObjectsListModel.objectChanged(selectedMapObject); - } else if (source == targetLayer) { - selectedReplacement.targetLayer = (String)value; - replacementsListModel.objectChanged(selectedReplacement); - groupObjectsListModel.objectChanged(selectedMapObject); - } - if (modified) { - if (map.state != GameDataElement.State.modified) { - map.state = GameDataElement.State.modified; - ATContentStudio.frame.editorChanged(TMXMapEditor.this); - } - map.childrenChanged(new ArrayList()); - } - } - } - - - public void updateMessage() { - - //TODO make this a full update of the button panel. - TMXMap node = (TMXMap) target; - if (node.writable) { - if (node.getDataType() == GameSource.Type.altered) { - message.setText(ALTERED_MESSAGE); - } else if (node.getDataType() == GameSource.Type.created) { - message.setText(CREATED_MESSAGE); - } - } else if (node.getProject().getMap(node.id) != node) { - message.setText(ALTERED_EXISTS_MESSAGE); - } else { - message.setText(READ_ONLY_MESSAGE); - } - message.revalidate(); - message.repaint(); - } - - public class TMXReplacementViewer extends JPanel implements Scrollable { - - private static final long serialVersionUID = 2845032142029325865L; - private TMXMap map; - public ReplaceArea highlighted = null; - public boolean showWalkable = true; - public boolean showHeroWithMouse = true; - public boolean showTooltip = true; - private OrthogonalRenderer renderer; - - private String groundName, objectsName, aboveName, topName, walkableName; - private Map layersByName = new LinkedHashMap(); - private tiled.core.TileLayer ground, objects, above, top, walkable; - - private Map> replacementsForLayer = new LinkedHashMap>(); - public Map activeReplacements = new LinkedHashMap(); - - private boolean tooltipActivated = true; - - public TMXReplacementViewer(final TMXMap map) { - this.map = map; - renderer = createRenderer(map.tmxMap); - - init(); - - setPreferredSize(renderer.getMapSize()); - setOpaque(true); - - addMouseMotionListener(new MouseMotionAdapter() { - @Override - public void mouseMoved(MouseEvent e) { - Point oldTooltippedTile = new Point(tooltippedTile); - tooltippedTile.setLocation(e.getX() / 32, e.getY() / 32); - if (!showTooltip || !((TMXMap)target).tmxMap.contains(tooltippedTile.x, tooltippedTile.y)) { - if (tooltipActivated) { - //Hides the tooltip... - ToolTipManager.sharedInstance().setEnabled(false); - ToolTipManager.sharedInstance().unregisterComponent(TMXReplacementViewer.this); - tooltipActivated = false; - } - } else { - if (showTooltip && !tooltipActivated) { - ToolTipManager.sharedInstance().registerComponent(TMXReplacementViewer.this); - ToolTipManager.sharedInstance().setEnabled(true); - tooltipActivated = true; - } - } - if (showHeroWithMouse && (oldTooltippedTile.x != tooltippedTile.x || oldTooltippedTile.y != tooltippedTile.y) ) { - TMXReplacementViewer.this.revalidate(); - TMXReplacementViewer.this.repaint(); - } - } - }); - - ToolTipManager.sharedInstance().registerComponent(this); - setToolTipText(""); - - } - - public void init() { - groundName = objectsName = aboveName = walkableName = topName = null; - layersByName.clear(); - ground = objects = above = walkable = top = null; - replacementsForLayer.clear(); - - for (tiled.core.MapLayer layer : map.tmxMap.getLayers()) { - if (layer instanceof tiled.core.TileLayer) { - layersByName.put(layer.getName(), (tiled.core.TileLayer)layer); - if (TMXMap.GROUND_LAYER_NAME.equalsIgnoreCase(layer.getName())) { - groundName = layer.getName(); - } else if (TMXMap.OBJECTS_LAYER_NAME.equalsIgnoreCase(layer.getName())) { - objectsName = layer.getName(); - } else if (TMXMap.ABOVE_LAYER_NAME.equalsIgnoreCase(layer.getName())) { - aboveName = layer.getName(); - } else if (TMXMap.TOP_LAYER_NAME.equalsIgnoreCase(layer.getName())) { - topName = layer.getName(); - } else if (TMXMap.WALKABLE_LAYER_NAME.equalsIgnoreCase(layer.getName())) { - walkableName = layer.getName(); - } - } - } - - for (MapObjectGroup group : map.groups) { - for (MapObject object : group.mapObjects) { - if (object instanceof ReplaceArea) { - ReplaceArea area = (ReplaceArea)object; - if (!activeReplacements.containsKey(area)) { - activeReplacements.put(area, true); - } - - if(area.replacements != null) { - for (ReplaceArea.Replacement repl : area.replacements) { - if (replacementsForLayer.get(repl.sourceLayer) == null) { - replacementsForLayer.put(repl.sourceLayer, new ArrayList()); - } - replacementsForLayer.get(repl.sourceLayer).add(area); - } - } - } - } - } - updateLayers(); - } - - public void updateLayers() { - ground = mergeReplacements(groundName); - objects = mergeReplacements(objectsName); - above = mergeReplacements(aboveName); - top = mergeReplacements(topName); - walkable = mergeReplacements(walkableName); - } - - private tiled.core.TileLayer mergeReplacements(String layerName) { - tiled.core.TileLayer merged = null; - if (layerName != null && layersByName.get(layerName) != null) { - tiled.core.TileLayer original = layersByName.get(layerName); - merged = new tiled.core.TileLayer(original.getBounds()); - merged.copyFrom(original); - if (replacementsForLayer.containsKey(layerName)) { - for (ReplaceArea area : replacementsForLayer.get(layerName)) { - if (activeReplacements.get(area)) { - String targetName = null; - for (ReplaceArea.Replacement repl : area.replacements) { - if (layerName.equals(repl.sourceLayer)) { - targetName = repl.targetLayer; - } - } - if (targetName != null) { - for (int x = area.x / 32; x < (area.x + area.w) / 32; x++) { - for (int y = area.y / 32; y < (area.y + area.h) / 32; y++) { - merged.setTileAt(x, y, layersByName.get(targetName).getTileAt(x, y)); - } - } - } - } - } - } - } - return merged; - } - - public void setHighlight(ReplaceArea selected) { - highlighted = selected; - invalidate(); - } - - public void paintComponent(Graphics g) { - final Graphics2D g2d = (Graphics2D) g.create(); - final Rectangle clip = g2d.getClipBounds(); - - // Draw a gray background - g2d.setPaint(new Color(100, 100, 100)); - g2d.fill(clip); - - // Draw each tile map layer - - if (ground != null) { - renderer.paintTileLayer(g2d, ground); - } - - if (objects != null) { - renderer.paintTileLayer(g2d, objects); - } - - if (showHeroWithMouse && tooltippedTile != null && ((TMXMap)target).tmxMap.contains(tooltippedTile.x, tooltippedTile.y) && - walkable != null && walkable.getTileAt(tooltippedTile.x, tooltippedTile.y) == null) { - g2d.drawImage(DefaultIcons.getHeroImage(), tooltippedTile.x * 32, tooltippedTile.y * 32, 32, 32, null); - } - - if (above != null) { - renderer.paintTileLayer(g2d, above); - } - - if (top != null) { - renderer.paintTileLayer(g2d, top); - } - if (walkable != null && showWalkable) { - renderer.paintTileLayer(g2d, walkable); - } - - if (map.colorFilter != null) { - MapColorFilters.applyColorfilter(map.colorFilter, g2d); - } - - - if (highlighted != null) { - drawObject(highlighted, g2d, new Color(190, 20, 20)); - } - - g2d.dispose(); - } - - - - private OrthogonalRenderer createRenderer(tiled.core.Map map) { - return new OrthogonalRenderer(map); - } - - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } - - public int getScrollableUnitIncrement(Rectangle visibleRect, - int orientation, int direction) { - if (orientation == SwingConstants.HORIZONTAL) - return ((TMXMap)target).tmxMap.getTileWidth(); - else - return ((TMXMap)target).tmxMap.getTileHeight(); - } - - public int getScrollableBlockIncrement(Rectangle visibleRect, - int orientation, int direction) { - if (orientation == SwingConstants.HORIZONTAL) { - final int tileWidth = ((TMXMap)target).tmxMap.getTileWidth(); - return (visibleRect.width / tileWidth - 1) * tileWidth; - } else { - final int tileHeight = ((TMXMap)target).tmxMap.getTileHeight(); - return (visibleRect.height / tileHeight - 1) * tileHeight; - } - } - - public boolean getScrollableTracksViewportWidth() { - return false; - } - - public boolean getScrollableTracksViewportHeight() { - return false; - } - - JLabel noTileGround = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); - JLabel noTileObjects = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); - JLabel noTileAbove = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); - JLabel noTileTop = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); - { - noTileGround.setPreferredSize(new Dimension(32, 32)); - noTileObjects.setPreferredSize(new Dimension(32, 32)); - noTileAbove.setPreferredSize(new Dimension(32, 32)); - noTileTop.setPreferredSize(new Dimension(32, 32)); - } - Point tooltippedTile = new Point(); - JToolTip tt = null; - Point lastTTTile = null; - - @Override - public JToolTip createToolTip() { - if (tooltippedTile.equals(lastTTTile)) { - return tt; - } - if (!((TMXMap)target).tmxMap.contains(tooltippedTile.x, tooltippedTile.y)) { - return super.createToolTip(); - } - tt = super.createToolTip(); - lastTTTile = new Point(tooltippedTile); - tt.setLayout(new BorderLayout()); - JPanel content = new JPanel(); - content.setLayout(new JideBoxLayout(content, JideBoxLayout.PAGE_AXIS)); - if (tooltippedTile != null) { - tiled.core.Tile tile; - Image tileImage; - JLabel label; - - if (top != null && top.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { - tile = top.getTileAt(tooltippedTile.x, tooltippedTile.y); - tileImage = tile.getImage(); - } else { - tile = null; - tileImage = null; - } - if (tileImage != null) { - label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); - label.setPreferredSize(new Dimension(32,32)); - content.add(label, JideBoxLayout.FIX); - //Fix when (if?) Top is advertised publicly. +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; +import tiled.view.MapRenderer; +import tiled.view.OrthogonalRenderer; + +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.tree.DefaultTreeCellRenderer; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; +import java.awt.*; +import java.awt.event.*; +import java.io.File; +import java.util.List; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; + +public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListener { + + private static final long serialVersionUID = -3079451876618342442L; + + + Map editorTabs = new LinkedHashMap(); + JideTabbedPane editorTabsHolder; + + private JButton reload; + + private RSyntaxTextArea editorPane; + + private IntegerBasedCheckBox outsideBox; + @SuppressWarnings("rawtypes") + private JComboBox colorFilterBox; + private LayerListModel layerListModel; + @SuppressWarnings("rawtypes") + private JList layerList; + private tiled.core.MapLayer selectedLayer; + private JButton addTileLayer; + private JButton addObjectGroup; + private JButton deleteLayer; + + private JPanel layerDetailsPane; + private BooleanBasedCheckBox layerVisibleBox; + private JCheckBox groupActiveForNewGame; + private JTextField layerNameField; + private MapObjectsListModel groupObjectsListModel; + @SuppressWarnings("rawtypes") + private JList groupObjectsList; + private MapObject selectedMapObject; + private JButton addMapchange; + private JButton addSpawn; + private JButton addRest; + private JButton addKey; + private JButton addReplace; + private JButton addScript; + private JButton addContainer; + private JButton addSign; + private JButton deleteObject; + + private JPanel mapObjectSettingsPane; + @SuppressWarnings("rawtypes") + private JComboBox droplistBox; + @SuppressWarnings("rawtypes") + private JComboBox dialogueBox; + @SuppressWarnings("rawtypes") + private JComboBox mapBox; + private JTextField areaField; + @SuppressWarnings("rawtypes") + private JComboBox targetAreaCombo; + @SuppressWarnings("rawtypes") + private JComboBox evaluateTriggerBox; + private JSpinner quantityField; + private JSpinner respawnSpeedField; + private JCheckBox spawnActiveForNewGame; + private JCheckBox spawnIgnoreAreas; + private JTextField spawngroupField; + @SuppressWarnings("rawtypes") + private JList npcList; + private SpawnGroupNpcListModel npcListModel; + + @SuppressWarnings("rawtypes") + private JComboBox requirementTypeCombo; + private JPanel requirementParamsPane; + @SuppressWarnings("rawtypes") + private JComboBox requirementObj; + private JComponent requirementObjId; + private JComponent requirementValue; + private BooleanBasedCheckBox requirementNegated; + + @SuppressWarnings("rawtypes") + private JList replacementsList; + private ReplacementsListModel replacementsListModel; + private ReplaceArea.Replacement selectedReplacement; + private JButton addReplacement; + private JButton deleteReplacement; + private JPanel replacementEditPane; + @SuppressWarnings("rawtypes") + private JComboBox sourceLayer; + @SuppressWarnings("rawtypes") + private JComboBox targetLayer; + + private TMXViewer tmxViewer; + + public TMXMapEditor(TMXMap map) { + this.target = map; + this.name = map.getDesc(); + this.icon = new ImageIcon(DefaultIcons.getTiledIconIcon()); + + map.addMapChangedOnDiskListener(this); + + setLayout(new BorderLayout()); + editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); + editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); + editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); + editorTabsHolder.setShowCloseButtonOnTab(false); + add(editorTabsHolder, BorderLayout.CENTER); + + JScrollPane tmxScroller = new JScrollPane(getTmxEditorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + JScrollPane xmlScroller = new JScrollPane(getXmlEditorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + //JScrollPane replScroller = new JScrollPane(getReplacementSimulatorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + xmlScroller.getVerticalScrollBar().setUnitIncrement(16); + editorTabsHolder.add("TMX", tmxScroller); + editorTabsHolder.add("XML", xmlScroller); + //editorTabsHolder.add("Replacements", replScroller); + editorTabsHolder.add("Testing", getReplacementSimulatorPane()); + + } + + + @SuppressWarnings({"unchecked", "rawtypes"}) + public JPanel getTmxEditorPane() { + final TMXMap map = (TMXMap) target; + final FieldUpdateListener listener = new MapFieldUpdater(); + + ScrollablePanel pane = new ScrollablePanel(); + pane.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.FIT); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + + addLabelField(pane, "TMX File: ", ((TMXMap) target).tmxFile.getAbsolutePath()); + createButtonPane(pane, map.getProject(), map, listener); + outsideBox = addIntegerBasedCheckBox(pane, "Map is outdoors", map.outside, map.writable, listener); + colorFilterBox = addEnumValueBox(pane, "Color Filter", TMXMap.ColorFilter.values(), map.colorFilter, map.writable, listener); + + JSplitPane layersViewSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); + layerListModel = new LayerListModel(map); + layerList = new JList(layerListModel); + layerList.setCellRenderer(new LayerListRenderer()); + layerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + JScrollPane layerListScroller = new JScrollPane(layerList); + layerListScroller.getVerticalScrollBar().setUnitIncrement(16); + layerList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedLayer = (tiled.core.MapLayer) layerList.getSelectedValue(); + selectedMapObject = null; + if (selectedLayer != null && map.writable) { + deleteLayer.setEnabled(true); + } else { + deleteLayer.setEnabled(false); + } + updateLayerDetailsPane(layerDetailsPane, selectedLayer, listener); + listener.valueChanged(layerList, selectedLayer); + } + }); + JPanel layersListPane = new JPanel(); + layersListPane.setLayout(new JideBoxLayout(layersListPane, JideBoxLayout.PAGE_AXIS, 6)); + layersListPane.add(layerListScroller, JideBoxLayout.VARY); + addTileLayer = new JButton(new ImageIcon(DefaultIcons.getCreateTileLayerIcon())); + addTileLayer.setToolTipText("Create new tile layer (graphics layer)."); + addTileLayer.setEnabled(map.writable); + addTileLayer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + tiled.core.TileLayer layer = new tiled.core.TileLayer(map.tmxMap.getWidth(), map.tmxMap.getHeight()); + layerListModel.addObject(layer); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addObjectGroup = new JButton(new ImageIcon(DefaultIcons.getCreateObjectGroupIcon())); + addObjectGroup.setToolTipText("Create new object group."); + addObjectGroup.setEnabled(map.writable); + addObjectGroup.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + layerListModel.addObject(new tiled.core.ObjectGroup()); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + deleteLayer = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + deleteLayer.setToolTipText("Delete selected layer/group."); + deleteLayer.setEnabled(false); + deleteLayer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + layerListModel.removeObject(selectedLayer); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + JPanel layersButtonsPane = new JPanel(); + layersButtonsPane.setLayout(new JideBoxLayout(layersButtonsPane, JideBoxLayout.LINE_AXIS, 6)); + layersButtonsPane.add(addTileLayer, JideBoxLayout.FIX); + layersButtonsPane.add(addObjectGroup, JideBoxLayout.FIX); + layersButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + layersButtonsPane.add(deleteLayer, JideBoxLayout.FIX); + layersListPane.add(layersButtonsPane, JideBoxLayout.FIX); + layersViewSplitPane.setLeftComponent(layersListPane); + layerDetailsPane = new JPanel(); + layerDetailsPane.setLayout(new JideBoxLayout(layerDetailsPane, JideBoxLayout.PAGE_AXIS, 6)); + layersViewSplitPane.setRightComponent(layerDetailsPane); + pane.add(layersViewSplitPane, JideBoxLayout.FIX); + + tmxViewer = new TMXViewer(((TMXMap) target), listener); + JScrollPane tmxScroller = new JScrollPane(tmxViewer); + tmxScroller.getVerticalScrollBar().setUnitIncrement(16); + tmxScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); + tmxScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); + pane.add(tmxScroller, JideBoxLayout.FIX); + + addTMXMapSpritesheetsList(pane, ((TMXMap) target)); + + addBacklinksList(pane, map); + + pane.add(new JPanel(), JideBoxLayout.VARY); + return pane; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + public void updateLayerDetailsPane(JPanel pane, tiled.core.MapLayer selected, final FieldUpdateListener listener) { + final TMXMap map = (TMXMap) target; + pane.removeAll(); + if (selected == null) { + return; + } else if (selected instanceof tiled.core.TileLayer) { + layerNameField = addTextField(pane, "Layer name: ", selected.getName(), map.writable, listener); + layerVisibleBox = addBooleanBasedCheckBox(pane, "Visible", selected.isVisible(), true, listener); + pane.add(new JPanel(), JideBoxLayout.VARY); + } else if (selected instanceof tiled.core.ObjectGroup) { + JSplitPane objectGroupDetailsSplitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); + JPanel groupDetailPane = new JPanel(); + groupDetailPane.setLayout(new JideBoxLayout(groupDetailPane, JideBoxLayout.PAGE_AXIS, 6)); + objectGroupDetailsSplitter.setLeftComponent(groupDetailPane); + layerNameField = addTextField(groupDetailPane, "Group name: ", selected.getName(), map.writable, listener); + layerVisibleBox = addBooleanBasedCheckBox(groupDetailPane, "Visible", selected.isVisible(), true, listener); + MapObjectGroup objGroup = null; + for (MapObjectGroup group : map.groups) { + if (group.tmxGroup == selected) { + objGroup = group; + break; + } + } + groupActiveForNewGame = addBooleanBasedCheckBox(groupDetailPane, "Active for new game", objGroup.active, map.writable, listener); + groupObjectsListModel = new MapObjectsListModel(objGroup); + groupObjectsList = new JList(groupObjectsListModel); + groupObjectsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + groupObjectsList.setCellRenderer(new GroupObjectsRenderer()); + JScrollPane groupObjectsScroller = new JScrollPane(groupObjectsList); + groupObjectsScroller.getVerticalScrollBar().setUnitIncrement(16); + groupDetailPane.add(groupObjectsScroller, JideBoxLayout.VARY); + groupObjectsList.addListSelectionListener(new ListSelectionListener() { + + @Override + public void valueChanged(ListSelectionEvent e) { + selectedMapObject = (MapObject) groupObjectsList.getSelectedValue(); + updateMapObjectSettingsPane(mapObjectSettingsPane, selectedMapObject, listener); + listener.valueChanged(groupObjectsList, selectedMapObject); + if (selectedMapObject != null && map.writable) { + deleteObject.setEnabled(true); + } else { + deleteObject.setEnabled(false); + } + } + }); + + addMapchange = new JButton(new ImageIcon(DefaultIcons.getCreateMapchangeIcon())); + addMapchange.setToolTipText("Create new mapchange area."); + addMapchange.setEnabled(map.writable); + addMapchange.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newMapchange(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addSpawn = new JButton(new ImageIcon(DefaultIcons.getCreateSpawnareaIcon())); + addSpawn.setToolTipText("Create new spawn area."); + addSpawn.setEnabled(map.writable); + addSpawn.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newSpawnArea(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addRest = new JButton(new ImageIcon(DefaultIcons.getCreateRestIcon())); + addRest.setToolTipText("Create new rest area."); + addRest.setEnabled(map.writable); + addRest.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newRest(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addKey = new JButton(new ImageIcon(DefaultIcons.getCreateKeyIcon())); + addKey.setToolTipText("Create new key area."); + addKey.setEnabled(map.writable); + addKey.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newKey(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addReplace = new JButton(new ImageIcon(DefaultIcons.getCreateReplaceIcon())); + addReplace.setToolTipText("Create new replace area."); + addReplace.setEnabled(map.writable); + addReplace.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newReplace(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addScript = new JButton(new ImageIcon(DefaultIcons.getCreateScriptIcon())); + addScript.setToolTipText("Create new script area."); + addScript.setEnabled(map.writable); + addScript.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newScript(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addContainer = new JButton(new ImageIcon(DefaultIcons.getCreateContainerIcon())); + addContainer.setToolTipText("Create new container."); + addContainer.setEnabled(map.writable); + addContainer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newContainer(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + addSign = new JButton(new ImageIcon(DefaultIcons.getCreateSignIcon())); + addSign.setToolTipText("Create new sign post."); + addSign.setEnabled(map.writable); + addSign.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.addObject(MapObject.newSign(new tiled.core.MapObject(0, 0, 32, 32), map)); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + deleteObject = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + deleteObject.setToolTipText("Delete selected map object."); + deleteObject.setEnabled(false); + deleteObject.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + groupObjectsListModel.removeObject(selectedMapObject); + map.state = GameDataElement.State.modified; + map.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + targetUpdated(); + } + }); + + JPanel groupButtonsPane1 = new JPanel(); + groupButtonsPane1.setLayout(new JideBoxLayout(groupButtonsPane1, JideBoxLayout.LINE_AXIS, 6)); + groupButtonsPane1.add(addMapchange, JideBoxLayout.FIX); + groupButtonsPane1.add(addSpawn, JideBoxLayout.FIX); + groupButtonsPane1.add(addRest, JideBoxLayout.FIX); + groupButtonsPane1.add(addKey, JideBoxLayout.FIX); + groupButtonsPane1.add(new JPanel(), JideBoxLayout.VARY); + JPanel groupButtonsPane2 = new JPanel(); + groupButtonsPane2.setLayout(new JideBoxLayout(groupButtonsPane2, JideBoxLayout.LINE_AXIS, 6)); + groupButtonsPane2.add(addReplace, JideBoxLayout.FIX); + groupButtonsPane2.add(addScript, JideBoxLayout.FIX); + groupButtonsPane2.add(addContainer, JideBoxLayout.FIX); + groupButtonsPane2.add(addSign, JideBoxLayout.FIX); + groupButtonsPane2.add(new JPanel(), JideBoxLayout.VARY); + groupButtonsPane2.add(deleteObject, JideBoxLayout.FIX); + groupDetailPane.add(groupButtonsPane1, JideBoxLayout.FIX); + groupDetailPane.add(groupButtonsPane2, JideBoxLayout.FIX); + + mapObjectSettingsPane = new JPanel(); + mapObjectSettingsPane.setLayout(new JideBoxLayout(mapObjectSettingsPane, JideBoxLayout.PAGE_AXIS, 6)); + JScrollPane mapObjectSettingsScroller = new JScrollPane(mapObjectSettingsPane); + mapObjectSettingsScroller.getVerticalScrollBar().setUnitIncrement(16); + objectGroupDetailsSplitter.setRightComponent(mapObjectSettingsScroller); + pane.add(objectGroupDetailsSplitter, JideBoxLayout.VARY); + } + pane.revalidate(); + pane.repaint(); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public void updateMapObjectSettingsPane(JPanel pane, final MapObject selected, final FieldUpdateListener listener) { + pane.removeAll(); + boolean needVary = true; + if (selected instanceof ContainerArea) { + droplistBox = addDroplistBox(pane, ((TMXMap) target).getProject(), "Droplist: ", ((ContainerArea) selected).droplist, ((TMXMap) target).writable, listener); + } else if (selected instanceof KeyArea) { + areaField = addTextField(pane, "Area ID: ", ((KeyArea) selected).name, ((TMXMap) target).writable, listener); + dialogueBox = addDialogueBox(pane, ((TMXMap) target).getProject(), "Message when locked: ", ((KeyArea) selected).dialogue, ((TMXMap) target).writable, listener); + requirementTypeCombo = addEnumValueBox(pane, "Requirement type: ", Requirement.RequirementType.values(), ((KeyArea) selected).requirement.type, ((TMXMap) target).writable, listener); + requirementParamsPane = new JPanel(); + requirementParamsPane.setLayout(new JideBoxLayout(requirementParamsPane, JideBoxLayout.PAGE_AXIS, 6)); + pane.add(requirementParamsPane, JideBoxLayout.FIX); + updateRequirementParamsPane(requirementParamsPane, ((KeyArea) selected).requirement, listener); + } else if (selected instanceof MapChange) { + areaField = addTextField(pane, "Area ID: ", ((MapChange) selected).name, ((TMXMap) target).writable, listener); + mapBox = addMapBox(pane, ((TMXMap) target).getProject(), "Target map: ", ((MapChange) selected).map, ((TMXMap) target).writable, listener); + targetAreaCombo = new JComboBox(); + if (((MapChange) selected).map != null) { + ((MapChange) selected).map.link(); + targetAreaCombo.setModel(new DefaultComboBoxModel((((MapChange) selected).map.getMapchangesNames().toArray()))); + } + targetAreaCombo.setEditable(false); + targetAreaCombo.setEnabled(((TMXMap) target).writable); + targetAreaCombo.setSelectedItem(((MapChange) selected).place_id); + JPanel tACPane = new JPanel(); + tACPane.setLayout(new JideBoxLayout(tACPane, JideBoxLayout.LINE_AXIS, 6)); + tACPane.add(new JLabel("Target mapchange area ID: "), JideBoxLayout.FIX); + tACPane.add(targetAreaCombo, JideBoxLayout.VARY); + JButton nullifyTargetArea = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tACPane.add(nullifyTargetArea, JideBoxLayout.FIX); + nullifyTargetArea.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + targetAreaCombo.setSelectedItem(null); + listener.valueChanged(targetAreaCombo, null); + } + }); + targetAreaCombo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(targetAreaCombo, targetAreaCombo.getSelectedItem()); + } + }); + pane.add(tACPane, JideBoxLayout.FIX); + } else if (selected instanceof ReplaceArea) { + areaField = addTextField(pane, "Area ID: ", ((ReplaceArea) selected).name, ((TMXMap) target).writable, listener); + requirementTypeCombo = addEnumValueBox(pane, "Requirement type: ", Requirement.RequirementType.values(), ((ReplaceArea) selected).requirement.type, ((TMXMap) target).writable, listener); + requirementParamsPane = new JPanel(); + requirementParamsPane.setLayout(new JideBoxLayout(requirementParamsPane, JideBoxLayout.PAGE_AXIS, 6)); + pane.add(requirementParamsPane, JideBoxLayout.FIX); + updateRequirementParamsPane(requirementParamsPane, ((ReplaceArea) selected).requirement, listener); + + CollapsiblePanel replacementListPane = new CollapsiblePanel("Replacements"); + replacementListPane.setLayout(new JideBoxLayout(replacementListPane, JideBoxLayout.PAGE_AXIS)); + replacementsListModel = new ReplacementsListModel((ReplaceArea) selected); + replacementsList = new JList(replacementsListModel); + replacementsList.setCellRenderer(new ReplacementsListRenderer((ReplaceArea) selected)); + replacementListPane.add(new JScrollPane(replacementsList), JideBoxLayout.VARY); + + JPanel replacementListButtonsPane = new JPanel(); + replacementListButtonsPane.setLayout(new JideBoxLayout(replacementListButtonsPane, JideBoxLayout.LINE_AXIS)); + addReplacement = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + replacementListButtonsPane.add(addReplacement, JideBoxLayout.FIX); + addReplacement.setEnabled(((TMXMap) target).writable); + addReplacement.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + replacementsListModel.addObject(null, null); + } + }); + deleteReplacement = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + replacementListButtonsPane.add(deleteReplacement, JideBoxLayout.FIX); + deleteReplacement.setEnabled(false); + deleteReplacement.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + replacementsListModel.removeObject(selectedReplacement); + } + }); + replacementListButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + replacementListPane.add(replacementListButtonsPane, JideBoxLayout.FIX); + + replacementEditPane = new JPanel(); + replacementListPane.add(replacementEditPane, JideBoxLayout.FIX); + + pane.add(new JScrollPane(replacementListPane), JideBoxLayout.VARY); + + + replacementsList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedReplacement = (ReplaceArea.Replacement) replacementsList.getSelectedValue(); + updateReplacementsEditPane(replacementEditPane, (ReplaceArea) selected, selectedReplacement, listener); + deleteReplacement.setEnabled(((TMXMap) target).writable); + } + }); + + + } else if (selected instanceof RestArea) { + areaField = addTextField(pane, "Area ID: ", ((RestArea) selected).name, ((TMXMap) target).writable, listener); + } else if (selected instanceof ScriptArea) { + evaluateTriggerBox = addEnumValueBox(pane, "Evaluate on every: ", ScriptArea.EvaluationTrigger.values(), ((ScriptArea) selected).trigger_type, ((TMXMap) target).writable, listener); + dialogueBox = addDialogueBox(pane, ((TMXMap) target).getProject(), "Script: ", ((ScriptArea) selected).dialogue, ((TMXMap) target).writable, listener); + } else if (selected instanceof SignArea) { + dialogueBox = addDialogueBox(pane, ((TMXMap) target).getProject(), "Message: ", ((SignArea) selected).dialogue, ((TMXMap) target).writable, listener); + } else if (selected instanceof SpawnArea) { + areaField = addTextField(pane, "Spawn area ID: ", ((SpawnArea) selected).name, ((TMXMap) target).writable, listener); + spawngroupField = addTextField(pane, "Spawn group ID: ", ((SpawnArea) selected).spawngroup_id, ((TMXMap) target).writable, listener); + quantityField = addIntegerField(pane, "Number of spawned NPCs: ", ((SpawnArea) selected).quantity, false, ((TMXMap) target).writable, listener); + respawnSpeedField = addIntegerField(pane, "Respawn-Speed of NPCs: ", ((SpawnArea) selected).respawnSpeed, false, ((TMXMap) target).writable, listener); + spawnActiveForNewGame = addBooleanBasedCheckBox(pane, "Active in a new game: ", ((SpawnArea) selected).active, ((TMXMap) target).writable, listener); + spawnIgnoreAreas = addBooleanBasedCheckBox(pane, "Monsters can walk on other game objects: ", ((SpawnArea) selected).ignoreAreas, ((TMXMap) target).writable, listener); + npcListModel = new SpawnGroupNpcListModel((SpawnArea) selected); + npcList = new JList(npcListModel); + npcList.setCellRenderer(new GDERenderer(true, ((TMXMap) target).writable)); + npcList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + npcList.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + ATContentStudio.frame.openEditor((JSONElement) npcList.getSelectedValue()); + ATContentStudio.frame.selectInTree((JSONElement) npcList.getSelectedValue()); + } + } + }); + npcList.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + ATContentStudio.frame.openEditor((JSONElement) npcList.getSelectedValue()); + ATContentStudio.frame.selectInTree((JSONElement) npcList.getSelectedValue()); + } + } + }); + JScrollPane npcListScroller = new JScrollPane(npcList); + npcListScroller.getVerticalScrollBar().setUnitIncrement(16); + pane.add(npcListScroller, JideBoxLayout.VARY); + needVary = false; + } + if (needVary) pane.add(new JPanel(), JideBoxLayout.VARY); + pane.revalidate(); + pane.repaint(); + } + + public void updateRequirementParamsPane(JPanel pane, Requirement requirement, FieldUpdateListener listener) { + boolean writable = ((TMXMap) target).writable; + Project project = ((TMXMap) target).getProject(); + pane.removeAll(); + if (requirement.type != null) { + switch (requirement.type) { + case consumedBonemeals: + case spentGold: + requirementObj = null; + requirementObjId = null; + requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); + break; + case random: + requirementObj = null; + requirementObjId = addChanceField(pane, "Chance: ", requirement.required_obj_id, "50/100", writable, listener); + requirementValue = null; + break; + case hasActorCondition: + requirementObj = addActorConditionBox(pane, project, "Actor Condition: ", (ActorCondition) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = null; + break; + case inventoryKeep: + case inventoryRemove: + case usedItem: + case wear: + case wearRemove: + requirementObj = addItemBox(pane, project, "Item: ", (Item) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); + break; + case killedMonster: + requirementObj = addNPCBox(pane, project, "Monster: ", (NPC) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = addIntegerField(pane, "Quantity: ", requirement.required_value, false, writable, listener); + break; + case questLatestProgress: + case questProgress: + requirementObj = addQuestBox(pane, project, "Quest: ", (Quest) requirement.required_obj, writable, listener); + requirementObjId = null; + requirementValue = addQuestStageBox(pane, project, "Quest stage: ", requirement.required_value, writable, listener, (Quest) requirement.required_obj, requirementObj); + break; + case skillLevel: + Requirement.SkillID skillId = null; + try { + skillId = requirement.required_obj_id == null ? null : Requirement.SkillID.valueOf(requirement.required_obj_id); + } catch (IllegalArgumentException e) { + } + requirementObj = addEnumValueBox(pane, "Skill ID:", Requirement.SkillID.values(), skillId, writable, listener); + requirementObjId = null;//addTextField(pane, "Skill ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Level: ", requirement.required_value, false, writable, listener); + break; + case timerElapsed: + requirementObj = null; + requirementObjId = addTextField(pane, "Timer ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Timer value: ", requirement.required_value, false, writable, listener); + break; + case factionScore: + requirementObj = null; + requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Minimum score: ", requirement.required_value, true, writable, listener); + break; + case factionScoreEquals: + requirementObj = null; + requirementObjId = addTextField(pane, "Faction ID:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Exact value: ", requirement.required_value, true, writable, listener); + break; + case date: + requirementObj = null; + requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Minimum date value: ", requirement.required_value, true, writable, listener); + break; + case dateEquals: + requirementObj = null; + requirementObjId = addTextField(pane, "Date type YYYYMMTT:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Exact date value: ", requirement.required_value, true, writable, listener); + break; + case time: + requirementObj = null; + requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Minimum time value: ", requirement.required_value, true, writable, listener); + break; + case timeEquals: + requirementObj = null; + requirementObjId = addTextField(pane, "Time type HHMMSS:", requirement.required_obj_id, writable, listener); + requirementValue = addIntegerField(pane, "Exact time value: ", requirement.required_value, true, writable, listener); + break; + } + } + requirementNegated = addBooleanBasedCheckBox(pane, "Negate this requirement.", requirement.negated, writable, listener); + pane.revalidate(); + pane.repaint(); + } + + public void updateReplacementsEditPane(JPanel pane, ReplaceArea area, ReplaceArea.Replacement replacement, final FieldUpdateListener listener) { + boolean writable = ((TMXMap) target).writable; + pane.removeAll(); + + sourceLayer = new JComboBox(new ReplacementsLayersComboModel(area, true, replacement.sourceLayer)); + targetLayer = new JComboBox(new ReplacementsLayersComboModel(area, false, replacement.targetLayer)); + + sourceLayer.setEnabled(writable); + targetLayer.setEnabled(writable); + + sourceLayer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(sourceLayer, sourceLayer.getModel().getSelectedItem()); + } + }); + targetLayer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(targetLayer, targetLayer.getModel().getSelectedItem()); + } + }); + + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.LINE_AXIS)); + pane.add(new JLabel("Replace "), JideBoxLayout.FIX); + pane.add(sourceLayer, JideBoxLayout.FIX); + pane.add(new JLabel(" by "), JideBoxLayout.FIX); + pane.add(targetLayer, JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + } + + public JPanel getXmlEditorPane() { + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + editorPane = new RSyntaxTextArea(); + editorPane.setText(((TMXMap) target).toXml()); + editorPane.setEditable(false); + editorPane.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML); + editorPane.setFont(editorPane.getFont().deriveFont(ATContentStudio.SCALING * editorPane.getFont().getSize())); + pane.add(editorPane, JideBoxLayout.VARY); + + return pane; + } + + public void updateXmlViewText(String text) { + editorPane.setText(text); + } + + + public JPanel getReplacementSimulatorPane() { + JPanel replacementSimulator = new JPanel(); + replacementSimulator.setLayout(new JideBoxLayout(replacementSimulator, JideBoxLayout.PAGE_AXIS)); + JPanel toolsPane = new JPanel(); + toolsPane.setLayout(new JideBoxLayout(toolsPane, JideBoxLayout.LINE_AXIS)); + final JCheckBox walkableVisibleBox = new JCheckBox("Show \"" + TMXMap.WALKABLE_LAYER_NAME + "\" layer."); + final JCheckBox showHeroBox = new JCheckBox("Show hero on walkable tiles under the mouse pointer."); + final JCheckBox showTooltipBox = new JCheckBox("Show tooltip with stack of tiles."); + JPanel areasActivationPane = new JPanel(); + areasActivationPane.setLayout(new JideBoxLayout(areasActivationPane, JideBoxLayout.PAGE_AXIS)); + TreeModel areasTreeModel = new ReplaceAreasActivationTreeModel(); + final JTree areasTree = new JTree(areasTreeModel); + areasTree.setEditable(false); + areasTree.setRootVisible(false); + areasTree.setCellRenderer(new ReplaceAreasActivationTreeCellRenderer()); + areasActivationPane.add(new JScrollPane(areasTree), JideBoxLayout.FIX); + final JToggleButton activate = new JToggleButton("Activate ReplaceArea(s)"); + areasActivationPane.add(activate, JideBoxLayout.VARY); + final TMXReplacementViewer viewer = new TMXReplacementViewer((TMXMap) target); + JPanel activateAndViewPane = new JPanel(); + activateAndViewPane.setLayout(new JideBoxLayout(activateAndViewPane, JideBoxLayout.LINE_AXIS)); + + activateAndViewPane.add(areasActivationPane, JideBoxLayout.FIX); + activateAndViewPane.add(new JScrollPane(viewer), JideBoxLayout.VARY); + + toolsPane.add(walkableVisibleBox, JideBoxLayout.FIX); + toolsPane.add(showTooltipBox, JideBoxLayout.FIX); + toolsPane.add(showHeroBox, JideBoxLayout.FIX); + toolsPane.add(new JPanel(), JideBoxLayout.VARY); + + replacementSimulator.add(toolsPane, JideBoxLayout.FIX); + replacementSimulator.add(activateAndViewPane, JideBoxLayout.VARY); + + walkableVisibleBox.setSelected(viewer.showWalkable); + walkableVisibleBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + viewer.showWalkable = walkableVisibleBox.isSelected(); + viewer.revalidate(); + viewer.repaint(); + } + }); + + showHeroBox.setSelected(viewer.showHeroWithMouse); + showHeroBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + viewer.showHeroWithMouse = showHeroBox.isSelected(); + } + }); + showTooltipBox.setSelected(viewer.showTooltip); + showTooltipBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + viewer.showTooltip = showTooltipBox.isSelected(); + } + }); + activate.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (areasTree.getSelectionPaths() == null) return; + for (TreePath paths : areasTree.getSelectionPaths()) { + Object target = paths.getLastPathComponent(); + if (target instanceof ReplaceArea) { + viewer.activeReplacements.put((ReplaceArea) target, activate.isSelected()); + viewer.updateLayers(); + viewer.revalidate(); + viewer.repaint(); + } else if (target instanceof MapObjectGroup) { + for (MapObject obj : ((MapObjectGroup) target).mapObjects) { + if (obj instanceof ReplaceArea) { + viewer.activeReplacements.put((ReplaceArea) obj, activate.isSelected()); + } + viewer.updateLayers(); + viewer.revalidate(); + viewer.repaint(); + } + } + + } + } + }); + areasTree.addTreeSelectionListener(new TreeSelectionListener() { + @Override + public void valueChanged(TreeSelectionEvent e) { + ReplaceArea oldHighlight = viewer.highlighted; + viewer.highlighted = null; + if (areasTree.getSelectionPaths() == null) return; + for (TreePath paths : areasTree.getSelectionPaths()) { + Object target = paths.getLastPathComponent(); + if (target instanceof ReplaceArea) { + activate.setSelected(viewer.activeReplacements.get((ReplaceArea) target)); + viewer.highlighted = (ReplaceArea) target; + } else if (target instanceof MapObjectGroup) { + for (MapObject obj : ((MapObjectGroup) target).mapObjects) { + activate.setSelected(true); + if (obj instanceof ReplaceArea) { + if (!viewer.activeReplacements.get((ReplaceArea) obj)) { + activate.setSelected(false); + } + } + } + } + } + if (oldHighlight != viewer.highlighted) { + viewer.revalidate(); + viewer.repaint(); + } + } + }); + + return replacementSimulator; + } + + public class ReplaceAreasActivationTreeModel implements TreeModel { + + @Override + public Object getRoot() { + return target; + } + + @Override + public Object getChild(Object parent, int index) { + int i = index; + if (parent instanceof TMXMap) { + for (MapObjectGroup group : ((TMXMap) parent).groups) { + for (MapObject obj : group.mapObjects) { + if (obj instanceof ReplaceArea) { + if (i == 0) return group; + i--; + break; + } + } + } + } else if (parent instanceof MapObjectGroup) { + for (MapObject obj : ((MapObjectGroup) parent).mapObjects) { + if (obj instanceof ReplaceArea) { + if (i == 0) return obj; + i--; + } + } + } + return null; + } + + @Override + public int getChildCount(Object parent) { + int count = 0; + if (parent instanceof TMXMap) { + for (MapObjectGroup group : ((TMXMap) parent).groups) { + for (MapObject obj : group.mapObjects) { + if (obj instanceof ReplaceArea) { + count++; + break; + } + } + } + } else if (parent instanceof MapObjectGroup) { + for (MapObject obj : ((MapObjectGroup) parent).mapObjects) { + if (obj instanceof ReplaceArea) { + count++; + } + } + } + return count; + } + + @Override + public boolean isLeaf(Object node) { + return node instanceof ReplaceArea; + } + + @Override + public void valueForPathChanged(TreePath path, Object newValue) { + // TODO Auto-generated method stub + + } + + @Override + public int getIndexOfChild(Object parent, Object child) { + int index = 0; + if (parent instanceof TMXMap) { + for (MapObjectGroup group : ((TMXMap) parent).groups) { + if (group == child) return index; + for (MapObject obj : group.mapObjects) { + if (obj instanceof ReplaceArea) { + index++; + break; + } + } + } + } else if (parent instanceof MapObjectGroup) { + for (MapObject obj : ((MapObjectGroup) parent).mapObjects) { + if (obj == child) return index; + if (obj instanceof ReplaceArea) { + index++; + } + } + } + return index; + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addTreeModelListener(TreeModelListener l) { + listeners.add(l); + } + + @Override + public void removeTreeModelListener(TreeModelListener l) { + listeners.remove(l); + } + + } + + public class ReplaceAreasActivationTreeCellRenderer extends DefaultTreeCellRenderer { + + private static final long serialVersionUID = 3988638353699460533L; + + @Override + public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { + Component c = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); + + if (c instanceof JLabel) { + JLabel label = (JLabel) c; + + if (value instanceof MapObjectGroup) { + label.setText(((MapObjectGroup) value).name); + label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); + } else if (value instanceof ReplaceArea) { + label.setText(((ReplaceArea) value).name); + label.setIcon(new ImageIcon(DefaultIcons.getReplaceIcon())); + } + } + + return c; + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public static JList addTMXMapSpritesheetsList(JPanel pane, TMXMap tmxMap) { + final JList list = new JList(new TMXMapSpritesheetsListModel(tmxMap)); + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + ATContentStudio.frame.openEditor((Spritesheet) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((Spritesheet) list.getSelectedValue()); + } + } + }); + list.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + ATContentStudio.frame.openEditor((Spritesheet) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((Spritesheet) list.getSelectedValue()); + } + } + }); + list.setCellRenderer(new SpritesheetCellRenderer(true)); + JScrollPane scroller = new JScrollPane(list); + scroller.setBorder(BorderFactory.createTitledBorder("Spritesheets used in this map.")); + pane.add(scroller, JideBoxLayout.FIX); + return list; + } + + @SuppressWarnings("rawtypes") + public class LayerListModel implements ListenerListModel { + + public TMXMap map; + + public LayerListModel(TMXMap map) { + this.map = map; + } + + @Override + public int getSize() { + return map.tmxMap.getLayerCount(); + } + + @Override + public Object getElementAt(int index) { + return map.tmxMap.getLayer(index); + } + + + public void objectChanged(tiled.core.MapLayer layer) { + int index = map.tmxMap.getLayerIndex(layer); + notifyListeners(ListDataEvent.CONTENTS_CHANGED, index, index); + + } + + public void addObject(tiled.core.MapLayer layer) { + map.addLayer(layer); + int index = map.tmxMap.getLayerIndex(layer); + notifyListeners(ListDataEvent.INTERVAL_ADDED, index, index); + } + + public void removeObject(tiled.core.MapLayer layer) { + int index = map.tmxMap.getLayerIndex(layer); + map.removeLayer(layer); + notifyListeners(ListDataEvent.INTERVAL_REMOVED, index, index); + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public List getListeners() { + return listeners; + } + } + + public class LayerListRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = -6182599528961565957L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = (JLabel) c; + tiled.core.MapLayer layer = (tiled.core.MapLayer) value; + label.setText(layer.getName()); + if (layer instanceof tiled.core.TileLayer) { + label.setIcon(new ImageIcon(DefaultIcons.getTileLayerIcon())); + } else if (layer instanceof tiled.core.ObjectGroup) { + label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); + } + } + return c; + } + } + + public class ReplacementsListModel extends OrderedListenerListModel { + public ReplacementsListModel(ReplaceArea area) { + super(area); + } + + @Override + protected List getItems() { + return source.replacements; + } + + @Override + protected void setItems(List items) { + source.replacements = items; + } + + public void addObject(String source, String target) { + ReplaceArea.Replacement repl = this.source.createReplacement(source, target); + addObject(repl); + } + } + + public class ReplacementsListRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = -6182599528961565957L; + public ReplaceArea area; + + public ReplacementsListRenderer(ReplaceArea area) { + super(); + this.area = area; + } + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = (JLabel) c; + ReplaceArea.Replacement repl = (ReplaceArea.Replacement) value; + label.setText(repl.sourceLayer + " -> " + repl.targetLayer); + } + return c; + } + } + + public class ReplacementsLayersComboModel implements ComboBoxModel { + ReplaceArea area; + boolean modelForSource; + + public List availableLayers = new ArrayList(); + + public String selected; + + public ReplacementsLayersComboModel(ReplaceArea area, boolean modelForSource, String selected) { + this.area = area; + this.modelForSource = modelForSource; + this.selected = selected; + + availableLayers.add(null); + for (tiled.core.MapLayer layer : ((TMXMap) target).tmxMap.getLayers()) { + if (layer instanceof tiled.core.TileLayer) { + if (modelForSource && !TMXMap.isPaintedLayerName(layer.getName())) { + continue; + } + if (modelForSource && area.hasReplacementFor(layer.getName()) && !layer.getName().equals(selected)) { + continue; + } + availableLayers.add(layer.getName()); + } + } + + } + + @Override + public String getElementAt(int index) { + return availableLayers.get(index); + } + + @Override + public Object getSelectedItem() { + return selected; + } + + @Override + public int getSize() { + return availableLayers.size(); + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addListDataListener(ListDataListener l) { + listeners.add(l); + } + + @Override + public void removeListDataListener(ListDataListener l) { + listeners.remove(l); + } + + @Override + public void setSelectedItem(Object anItem) { + selected = (String) anItem; + } + } + + public class MapObjectsListModel extends OrderedListenerListModel { + public MapObjectsListModel(MapObjectGroup group) { + super(group); + } + + @Override + protected List getItems() { + return source.mapObjects; + } + + @Override + protected void setItems(List items) { + source.mapObjects = items; + } + } + + public class GroupObjectsRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = -6182599528961565957L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + ((JLabel) c).setText(((MapObject) value).name); + ((JLabel) c).setIcon(new ImageIcon(((MapObject) value).getIcon())); + } + return c; + } + } + + + public class SpawnGroupNpcListModel extends OrderedListenerListModel { + public SpawnGroupNpcListModel(SpawnArea area) { + super(area); + } + + @Override + protected List getItems() { + return source.spawnGroup; + } + + @Override + protected void setItems(List items) { + source.spawnGroup = items; + } + } + + + public class TMXViewer extends JPanel implements Scrollable { + + private static final long serialVersionUID = 2845032142029325865L; + + + public tiled.core.MapObject highlighted = null; + private MapRenderer renderer; + private FieldUpdateListener listener; + private TMXMap map; + + public boolean resizing = false; + public boolean moving = false; + + public Rectangle getResizeHitArea() { + //16x16 px square in the lower right corner of area + return new Rectangle(selectedMapObject.x + selectedMapObject.w - 16, selectedMapObject.y + selectedMapObject.h - 16, 16, 16); + } + + + public Rectangle getMoveHitArea() { + //16x16 px square in the upper left corner of area + return new Rectangle(selectedMapObject.x, selectedMapObject.y, 16, 16); + } + + public Rectangle getSelectHitArea(MapObject obj) { + //16x16 px square in the upper left corner of area + return new Rectangle(obj.x, obj.y, 16, 16); + } + + public TMXViewer(final TMXMap map, FieldUpdateListener listener) { + this.listener = listener; + renderer = createRenderer(map.tmxMap); + this.map = map; + + setPreferredSize(renderer.getMapSize()); + setOpaque(true); + + addMouseListener(new MouseAdapter() { + + @Override + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + if (!moving && !resizing) { + select: + for (MapObjectGroup group : map.groups) { + if (group.visible) { + for (MapObject obj : group.mapObjects) { + if (getSelectHitArea(obj).contains(e.getPoint())) { + TMXMapEditor.this.selectMapObject(obj); + break select; + } + } + } + } + } + } + } + }); + + if (((TMXMap) target).writable) { + addMouseListener(new MouseAdapter() { + + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + resizing = false; + moving = false; + } + } + + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + if (selectedMapObject != null && selectedLayer.isVisible()) { + if (getResizeHitArea().contains(e.getPoint())) { + resizing = true; + } else if (getMoveHitArea().contains(e.getPoint())) { + moving = true; + } + } + } + } + + }); + + addMouseMotionListener(new MouseMotionListener() { + @Override + public void mouseMoved(MouseEvent e) { + if (selectedMapObject == null) return; + if (!resizing && !moving) { + if (getResizeHitArea().contains(e.getPoint())) { + setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR)); + } else if (getMoveHitArea().contains(e.getPoint())) { + setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); + } else { + setCursor(Cursor.getDefaultCursor()); + } + } + } + + @Override + public void mouseDragged(MouseEvent e) { + if (selectedMapObject == null) return; + boolean valueChanged = false; + if (resizing) { + Point p = getClosestTileCorner(e.getPoint()); + if (p.x > selectedMapObject.x) { + int oldW = selectedMapObject.w; + selectedMapObject.w = Math.min(p.x - selectedMapObject.x, map.tmxMap.getWidth() * map.tmxMap.getTileWidth()); + if (selectedMapObject.w != oldW) valueChanged = true; + } + if (p.y > selectedMapObject.y) { + int oldH = selectedMapObject.h; + selectedMapObject.h = Math.min(p.y - selectedMapObject.y, map.tmxMap.getHeight() * map.tmxMap.getTileHeight()); + if (selectedMapObject.h != oldH) valueChanged = true; + } + } else if (moving) { + Point p = getClosestTileCorner(e.getPoint()); + if (p.x + selectedMapObject.w <= map.tmxMap.getWidth() * map.tmxMap.getTileWidth()) { + int oldX = selectedMapObject.x; + selectedMapObject.x = Math.max(p.x, 0); + if (selectedMapObject.x != oldX) valueChanged = true; + } + if (p.y + selectedMapObject.h <= map.tmxMap.getHeight() * map.tmxMap.getTileHeight()) { + int oldY = selectedMapObject.y; + selectedMapObject.y = Math.max(p.y, 0); + if (selectedMapObject.y != oldY) valueChanged = true; + } + } + if (valueChanged) { + TMXViewer.this.listener.valueChanged(TMXViewer.this, null); + TMXViewer.this.revalidate(); + TMXViewer.this.repaint(); + } + } + }); + } + } + + public void setHighlight(tiled.core.MapObject selected) { + highlighted = selected; + invalidate(); + } + + public void paintComponent(Graphics g) { + final Graphics2D g2d = (Graphics2D) g.create(); + final Rectangle clip = g2d.getClipBounds(); + + + // Draw a gray background + g2d.setPaint(new Color(100, 100, 100)); + g2d.fill(clip); + + // Draw each tile map layer + for (tiled.core.MapLayer layer : ((TMXMap) target).tmxMap) { + if (layer instanceof tiled.core.TileLayer && layer.isVisible()) { + renderer.paintTileLayer(g2d, (tiled.core.TileLayer) layer); + } + } + + if (map.colorFilter != null) { + MapColorFilters.applyColorfilter(map.colorFilter, g2d); + } + + + // Draw each map object layer + boolean paintSelected = false; + for (tiled.core.MapLayer layer : ((TMXMap) target).tmxMap) { + if (layer instanceof tiled.core.ObjectGroup && layer.isVisible()) { + paintSelected |= paintObjectGroup(g2d, (tiled.core.ObjectGroup) layer); + } + } + + + if (paintSelected) { + //TODO make this less ugly..... visually speaking. + g2d.setColor(new Color(190, 20, 20)); + g2d.drawRect(selectedMapObject.x + selectedMapObject.w - 16, selectedMapObject.y + selectedMapObject.h - 16, 15, 15); + g2d.drawRect(selectedMapObject.x + selectedMapObject.w - 12, selectedMapObject.y + selectedMapObject.h - 12, 11, 11); + drawObject(selectedMapObject, g2d, new Color(190, 20, 20)); + } + + g2d.dispose(); + } + + private boolean paintObjectGroup(Graphics2D g2d, tiled.core.ObjectGroup layer) { + boolean paintSelected = false; + for (MapObjectGroup group : ((TMXMap) target).groups) { + if (group.tmxGroup == layer) { + for (MapObject object : group.mapObjects) { + if (object == selectedMapObject) { + paintSelected = true; + continue; + } else { + drawObject(object, g2d, new Color(20, 20, 190)); + } + } + break; + } + } + return paintSelected; + } + + private MapRenderer createRenderer(tiled.core.Map map) { + switch (map.getOrientation()) { + case tiled.core.Map.ORIENTATION_ORTHOGONAL: + return new OrthogonalRenderer(map); + default: + return null; + } + } + + public Dimension getPreferredScrollableViewportSize() { + return getPreferredSize(); + } + + public int getScrollableUnitIncrement(Rectangle visibleRect, + int orientation, int direction) { + if (orientation == SwingConstants.HORIZONTAL) + return ((TMXMap) target).tmxMap.getTileWidth(); + else + return ((TMXMap) target).tmxMap.getTileHeight(); + } + + public int getScrollableBlockIncrement(Rectangle visibleRect, + int orientation, int direction) { + if (orientation == SwingConstants.HORIZONTAL) { + final int tileWidth = ((TMXMap) target).tmxMap.getTileWidth(); + return (visibleRect.width / tileWidth - 1) * tileWidth; + } else { + final int tileHeight = ((TMXMap) target).tmxMap.getTileHeight(); + return (visibleRect.height / tileHeight - 1) * tileHeight; + } + } + + public boolean getScrollableTracksViewportWidth() { + return false; + } + + public boolean getScrollableTracksViewportHeight() { + return false; + } + + } + + public static class TMXMapSpritesheetsListModel implements ListenerCollectionModel { + TMXMap map; + + public TMXMapSpritesheetsListModel(TMXMap map) { + this.map = map; + } + + @Override + public Collection getElements() { + return map.usedSpritesheets; + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public List getListeners() { + return listeners; + } + } + + public static class SpritesheetCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 6819681566800482793L; + + private boolean includeType; + + public SpritesheetCellRenderer(boolean includeType) { + super(); + this.includeType = includeType; + + } + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value == null) { + label.setText("none"); + } else { + if (includeType && ((Spritesheet) value).getDataType() != null) { + label.setText(((Spritesheet) value).getDataType().toString() + "/" + ((Spritesheet) value).getDesc()); + } else { + label.setText(((Spritesheet) value).getDesc()); + } + if (((Spritesheet) value).getIcon() == null) { + Notification.addError("Unable to find icon for " + ((Spritesheet) value).getDesc()); + } else { + label.setIcon(new ImageIcon(((Spritesheet) value).getIcon())); + } + } + return label; + } + } + + @Override + public void targetUpdated() { + this.name = ((TMXMap) target).getDesc(); + updateMessage(); + updateXmlViewText(((TMXMap) target).toXml()); + tmxViewer.repaint(); + tmxViewer.revalidate(); + } + + + protected void selectMapObject(MapObject obj) { + for (MapObjectGroup group : ((TMXMap) target).groups) { + if (group.mapObjects.contains(obj)) { + layerList.setSelectedValue(group.tmxGroup, true); + groupObjectsList.setSelectedValue(obj, true); + } + } + } + + public JButton createButtonPane(JPanel pane, final Project proj, final TMXMap map, final FieldUpdateListener listener) { + JPanel savePane = new JPanel(); + savePane.setLayout(new JideBoxLayout(savePane, JideBoxLayout.LINE_AXIS, 6)); + final JButton gdeIcon = new JButton(new ImageIcon(DefaultIcons.getTiledIconImage())); + savePane.add(gdeIcon, JideBoxLayout.FIX); + if (map.writable) { + gdeIcon.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (map.needsSaving()) { + int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You have unsaved changes in ATCS.\nYou'd better save your changes in ATCS before opening this map with the external editor.\nDo you want to save before opening the file?", "Save before opening?", JOptionPane.YES_NO_CANCEL_OPTION); + if (confirm == JOptionPane.CANCEL_OPTION) return; + if (confirm == JOptionPane.YES_OPTION) { + map.save(); + ATContentStudio.frame.nodeChanged(map); + } + } + DesktopIntegration.openTmxMap(map.tmxFile); + } + }); + reload = new JButton("Reload"); + reload.setEnabled(map.changedOnDisk); + savePane.add(reload, JideBoxLayout.FIX); + reload.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + if (map.needsSaving()) { + int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You modified this map in ATCS. All ATCS-made changes will be lost if you confirm.\n On the other hand, if you save using ATCS, all external changes will be lost.\n Do you want to reload?", "Confirm reload?", JOptionPane.OK_CANCEL_OPTION); + if (confirm == JOptionPane.CANCEL_OPTION) return; + } + reload.setEnabled(false); + (new Thread() { + public void run() { + map.reload(); + } + }).start(); + } + }); + if (map.getDataType() == GameSource.Type.altered) { + savePane.add(message = new JLabel(ALTERED_MESSAGE), JideBoxLayout.FIX); + } else if (map.getDataType() == GameSource.Type.created) { + savePane.add(message = new JLabel(CREATED_MESSAGE), JideBoxLayout.FIX); + } + JButton save = new JButton(SAVE); + save.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (map.state != TMXMap.State.saved) { + if (map.changedOnDisk) { + int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You modified this map in an external tool. All external changes will be lost if you confirm.\n On the other hand, if you reload in ATCS, all ATCS-made changes will be lost.\n Do you want to save?", "Confirm save?", JOptionPane.OK_CANCEL_OPTION); + if (confirm == JOptionPane.CANCEL_OPTION) return; + File backup = FileUtils.backupFile(map.tmxFile); + if (backup != null) { + JOptionPane.showMessageDialog(TMXMapEditor.this, "The externally-modified file was backed up as " + backup.getAbsolutePath(), "File backed up", JOptionPane.INFORMATION_MESSAGE); + } else { + JOptionPane.showMessageDialog(TMXMapEditor.this, "The externally-modified file could not be backed up.", "File backup failed", JOptionPane.ERROR_MESSAGE); + } + } + map.save(); + ATContentStudio.frame.nodeChanged(map); + } + } + }); + savePane.add(save, JideBoxLayout.FIX); + JButton delete = new JButton(DELETE); + if (map.getDataType() == GameSource.Type.altered) { + delete.setText(REVERT); + } + delete.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ATContentStudio.frame.closeEditor(map); + map.childrenRemoved(new ArrayList()); + map.delete(); + GameDataElement newOne = map.getProject().getMap(map.id); + for (GameDataElement backlink : map.getBacklinks()) { + backlink.elementChanged(map, newOne); + } + } + }); + savePane.add(delete, JideBoxLayout.FIX); + final JButton bookmark = new JButton(new ImageIcon(map.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); + savePane.add(bookmark, JideBoxLayout.FIX); + bookmark.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + if (map.bookmark == null) { + map.getProject().bookmark(map); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); + } else { + map.bookmark.delete(); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); + } + } + }); + } else { + if (proj.getMap(map.id) != map) { + savePane.add(message = new JLabel(ALTERED_EXISTS_MESSAGE), JideBoxLayout.FIX); + JButton makeWritable = new JButton(GO_TO_ALTERED); + makeWritable.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (map.getProject().getMap(map.id) != map) { + ATContentStudio.frame.openEditor(map.getProject().getMap(map.id)); + ATContentStudio.frame.closeEditor(map); + ATContentStudio.frame.selectInTree(map.getProject().getMap(map.id)); + } + } + }); + savePane.add(makeWritable, JideBoxLayout.FIX); + + } else { + savePane.add(message = new JLabel(READ_ONLY_MESSAGE), JideBoxLayout.FIX); + JButton makeWritable = new JButton(ALTER); + makeWritable.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (map.getProject().getMap(map.id) == map) { + map.getProject().makeWritable(map); + } + if (map.getProject().getMap(map.id) != map) { + ATContentStudio.frame.openEditor(map.getProject().getMap(map.id)); + ATContentStudio.frame.closeEditor(map); + ATContentStudio.frame.selectInTree(map.getProject().getMap(map.id)); + } + } + }); + savePane.add(makeWritable, JideBoxLayout.FIX); + } + } + JButton prev = new JButton(new ImageIcon(DefaultIcons.getArrowLeftIcon())); + JButton next = new JButton(new ImageIcon(DefaultIcons.getArrowRightIcon())); + savePane.add(prev, JideBoxLayout.FIX); + savePane.add(next, JideBoxLayout.FIX); + if (map.getParent().getIndex(map) == 0) { + prev.setEnabled(false); + } + if (map.getParent().getIndex(map) == map.getParent().getChildCount() - 1) { + next.setEnabled(false); + } + prev.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ProjectTreeNode prevNode = (ProjectTreeNode) map.getParent().getChildAt(map.getParent().getIndex(map) - 1); + if (prevNode != null && prevNode instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) prevNode); + } + } + }); + next.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ProjectTreeNode nextNode = (ProjectTreeNode) map.getParent().getChildAt(map.getParent().getIndex(map) + 1); + if (nextNode != null && nextNode instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) nextNode); + } + } + }); + final JButton bookmark = new JButton(new ImageIcon(map.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); + savePane.add(bookmark, JideBoxLayout.FIX); + bookmark.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + if (map.bookmark == null) { + map.getProject().bookmark(map); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); + } else { + map.bookmark.delete(); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); + } + } + }); + //Placeholder. Fills the eventual remaining space. + savePane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(savePane, JideBoxLayout.FIX); + return gdeIcon; + } + + + private int skipAreaFieldEvents = 0; + + public class MapFieldUpdater implements FieldUpdateListener { + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public void valueChanged(JComponent source, Object value) { + TMXMap map = (TMXMap) target; + boolean modified = true; + if (source == layerNameField) { + selectedLayer.setName((String) value); + if (selectedLayer instanceof tiled.core.ObjectGroup) { + map.getGroup((tiled.core.ObjectGroup) selectedLayer).name = (String) value; + } + layerListModel.objectChanged(selectedLayer); + } else if (source == layerVisibleBox) { + selectedLayer.setVisible(layerVisibleBox.isSelected()); + if (selectedLayer instanceof tiled.core.ObjectGroup) { + map.getGroup((tiled.core.ObjectGroup) selectedLayer).visible = layerVisibleBox.isSelected(); + } + modified = false; + tmxViewer.revalidate(); + tmxViewer.repaint(); + } else if (source == groupActiveForNewGame) { + if (selectedLayer instanceof tiled.core.ObjectGroup) { + map.getGroup((tiled.core.ObjectGroup) selectedLayer).active = groupActiveForNewGame.isSelected(); + } + modified = true; + } else if (source == layerList) { + modified = false; + tmxViewer.revalidate(); + tmxViewer.repaint(); + } else if (source == groupObjectsList) { + modified = false; + tmxViewer.revalidate(); + tmxViewer.repaint(); + } else if (source == areaField) { + if (skipAreaFieldEvents > 0) skipAreaFieldEvents--; + else { + selectedMapObject.name = (String) value; + if (selectedMapObject instanceof KeyArea) { + KeyArea area = (KeyArea) selectedMapObject; + if (area.oldSchoolRequirement) { + area.oldSchoolRequirement = false; + } + } else if (selectedMapObject instanceof ReplaceArea) { + ReplaceArea area = (ReplaceArea) selectedMapObject; + if (area.oldSchoolRequirement) { + area.oldSchoolRequirement = false; + } + } + groupObjectsListModel.objectChanged(selectedMapObject); + } + } else if (source == spawngroupField) { + if (selectedMapObject instanceof SpawnArea) { + SpawnArea area = (SpawnArea) selectedMapObject; + if (area.spawnGroup != null && !area.spawnGroup.isEmpty()) { + for (NPC npc : area.spawnGroup) { + npc.removeBacklink(map); + } + } + area.spawngroup_id = (String) value; + selectedMapObject.link(); + npcList.setModel(new SpawnGroupNpcListModel(area)); + groupObjectsListModel.objectChanged(area); + npcList.revalidate(); + npcList.repaint(); + tmxViewer.revalidate(); + tmxViewer.repaint(); + } + } else if (source == targetAreaCombo) { + if (selectedMapObject instanceof MapChange) { + MapChange area = (MapChange) selectedMapObject; + area.place_id = (String) value; + } + } else if (source == outsideBox) { + map.outside = (Integer) value; + } else if (source == colorFilterBox) { + map.colorFilter = (TMXMap.ColorFilter) value; + tmxViewer.revalidate(); + tmxViewer.repaint(); + } else if (source == droplistBox) { + if (selectedMapObject instanceof ContainerArea) { + ContainerArea area = (ContainerArea) selectedMapObject; + if (area.droplist != null) { + area.droplist.removeBacklink(map); + } + area.droplist = (Droplist) value; + if (area.droplist != null) { + area.name = area.droplist.id; + } else { + area.name = null; + } + groupObjectsListModel.objectChanged(area); + tmxViewer.revalidate(); + tmxViewer.repaint(); + } + } else if (source == dialogueBox) { + if (selectedMapObject instanceof KeyArea) { + KeyArea area = (KeyArea) selectedMapObject; + if (area.dialogue != null) { + area.dialogue.removeBacklink(map); + } + area.dialogue = (Dialogue) value; + if (area.dialogue != null) { + area.dialogue_id = area.dialogue.id; + } else { + area.dialogue_id = null; + } + tmxViewer.revalidate(); + tmxViewer.repaint(); + } else if (selectedMapObject instanceof ScriptArea) { + ScriptArea area = (ScriptArea) selectedMapObject; + if (area.dialogue != null) { + area.dialogue.removeBacklink(map); + } + area.dialogue = (Dialogue) value; + if (area.dialogue != null) { + area.name = area.dialogue.id; + } else { + area.name = null; + } + groupObjectsListModel.objectChanged(area); + tmxViewer.revalidate(); + tmxViewer.repaint(); + } else if (selectedMapObject instanceof SignArea) { + SignArea area = (SignArea) selectedMapObject; + if (area.dialogue != null) { + area.dialogue.removeBacklink(map); + } + area.dialogue = (Dialogue) value; + if (area.dialogue != null) { + area.name = area.dialogue.id; + } else { + area.name = null; + } + groupObjectsListModel.objectChanged(area); + tmxViewer.revalidate(); + tmxViewer.repaint(); + } + } else if (source == mapBox) { + if (selectedMapObject instanceof MapChange) { + MapChange area = (MapChange) selectedMapObject; + if (area.map != null) { + area.map.removeBacklink(map); + } + area.map = (TMXMap) value; + if (area.map != null) { + area.map_id = area.map.id; + targetAreaCombo.setModel(new DefaultComboBoxModel((area.map.getMapchangesNames().toArray()))); + } else { + area.map_id = null; + } + tmxViewer.revalidate(); + tmxViewer.repaint(); + } + } else if (source == evaluateTriggerBox) { + if (selectedMapObject instanceof ScriptArea) { + ScriptArea area = (ScriptArea) selectedMapObject; + area.trigger_type = (ScriptArea.EvaluationTrigger) value; + } + } else if (source == quantityField) { + if (selectedMapObject instanceof SpawnArea) { + SpawnArea area = (SpawnArea) selectedMapObject; + area.quantity = (Integer) value; + } + } else if (source == respawnSpeedField) { + if (selectedMapObject instanceof SpawnArea) { + SpawnArea area = (SpawnArea) selectedMapObject; + area.respawnSpeed = (Integer) value; + } + } else if (source == spawnActiveForNewGame) { + if (selectedMapObject instanceof SpawnArea) { + SpawnArea area = (SpawnArea) selectedMapObject; + area.active = (Boolean) value; + } + } else if (source == spawnIgnoreAreas) { + if (selectedMapObject instanceof SpawnArea) { + SpawnArea area = (SpawnArea) selectedMapObject; + area.ignoreAreas = (Boolean) value; + } + } else if (source == requirementTypeCombo) { + if (selectedMapObject instanceof KeyArea) { + KeyArea area = (KeyArea) selectedMapObject; + area.requirement.changeType((Requirement.RequirementType) requirementTypeCombo.getSelectedItem()); + updateRequirementParamsPane(requirementParamsPane, area.requirement, this); + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } else if (selectedMapObject instanceof ReplaceArea) { + ReplaceArea area = (ReplaceArea) selectedMapObject; + area.requirement.changeType((Requirement.RequirementType) requirementTypeCombo.getSelectedItem()); + updateRequirementParamsPane(requirementParamsPane, area.requirement, this); + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } + } else if (source == requirementObj) { + if (selectedMapObject instanceof KeyArea) { + KeyArea area = (KeyArea) selectedMapObject; + if (area.requirement.type == Requirement.RequirementType.skillLevel) { + area.requirement.required_obj_id = value == null ? null : value.toString(); + } else { + area.requirement.required_obj = (GameDataElement) value; + if (area.requirement.required_obj != null) { + area.requirement.required_obj_id = area.requirement.required_obj.id; + } else { + area.requirement.required_obj_id = null; + } + } + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } else if (selectedMapObject instanceof ReplaceArea) { + ReplaceArea area = (ReplaceArea) selectedMapObject; + if (area.requirement.type == Requirement.RequirementType.skillLevel) { + area.requirement.required_obj_id = value == null ? null : value.toString(); + } else { + area.requirement.required_obj = (GameDataElement) value; + if (area.requirement.required_obj != null) { + area.requirement.required_obj_id = area.requirement.required_obj.id; + } else { + area.requirement.required_obj_id = null; + } + } + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } + } else if (source == requirementObjId) { + if (selectedMapObject instanceof KeyArea) { + KeyArea area = (KeyArea) selectedMapObject; + area.requirement.required_obj_id = (String) value; + area.requirement.required_obj = null; + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } else if (selectedMapObject instanceof ReplaceArea) { + ReplaceArea area = (ReplaceArea) selectedMapObject; + area.requirement.required_obj_id = (String) value; + area.requirement.required_obj = null; + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } + } else if (source == requirementValue) { + if (selectedMapObject instanceof KeyArea) { + KeyArea area = (KeyArea) selectedMapObject; + Quest quest = null; + QuestStage stage; + if (requirementValue instanceof JComboBox) { + quest = ((Quest) area.requirement.required_obj); + if (quest != null && area.requirement.required_value != null) { + stage = quest.getStage(area.requirement.required_value); + if (stage != null) stage.removeBacklink(map); + } + } + area.requirement.required_value = (Integer) value; + if (quest != null) { + stage = quest.getStage(area.requirement.required_value); + if (stage != null) stage.addBacklink(map); + } + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } else if (selectedMapObject instanceof ReplaceArea) { + ReplaceArea area = (ReplaceArea) selectedMapObject; + Quest quest = null; + QuestStage stage; + if (requirementValue instanceof JComboBox) { + quest = ((Quest) area.requirement.required_obj); + if (quest != null && area.requirement.required_value != null) { + stage = quest.getStage(area.requirement.required_value); + if (stage != null) stage.removeBacklink(map); + } + } + area.requirement.required_value = (Integer) value; + if (quest != null) { + stage = quest.getStage(area.requirement.required_value); + if (stage != null) stage.addBacklink(map); + } + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } + } else if (source == requirementNegated) { + if (selectedMapObject instanceof KeyArea) { + KeyArea area = (KeyArea) selectedMapObject; + area.requirement.negated = (Boolean) value; + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } else if (selectedMapObject instanceof ReplaceArea) { + ReplaceArea area = (ReplaceArea) selectedMapObject; + area.requirement.negated = (Boolean) value; + if (area.oldSchoolRequirement) { + area.updateNameFromRequirementChange(); + skipAreaFieldEvents += 2; + areaField.setText(area.name); + } + } + } else if (source == sourceLayer) { + selectedReplacement.sourceLayer = (String) value; + replacementsListModel.objectChanged(selectedReplacement); + groupObjectsListModel.objectChanged(selectedMapObject); + } else if (source == targetLayer) { + selectedReplacement.targetLayer = (String) value; + replacementsListModel.objectChanged(selectedReplacement); + groupObjectsListModel.objectChanged(selectedMapObject); + } + if (modified) { + if (map.state != GameDataElement.State.modified) { + map.state = GameDataElement.State.modified; + ATContentStudio.frame.editorChanged(TMXMapEditor.this); + } + map.childrenChanged(new ArrayList()); + } + } + } + + + public void updateMessage() { + + //TODO make this a full update of the button panel. + TMXMap node = (TMXMap) target; + if (node.writable) { + if (node.getDataType() == GameSource.Type.altered) { + message.setText(ALTERED_MESSAGE); + } else if (node.getDataType() == GameSource.Type.created) { + message.setText(CREATED_MESSAGE); + } + } else if (node.getProject().getMap(node.id) != node) { + message.setText(ALTERED_EXISTS_MESSAGE); + } else { + message.setText(READ_ONLY_MESSAGE); + } + message.revalidate(); + message.repaint(); + } + + public class TMXReplacementViewer extends JPanel implements Scrollable { + + private static final long serialVersionUID = 2845032142029325865L; + private TMXMap map; + public ReplaceArea highlighted = null; + public boolean showWalkable = true; + public boolean showHeroWithMouse = true; + public boolean showTooltip = true; + private OrthogonalRenderer renderer; + + private String groundName, objectsName, aboveName, topName, walkableName; + private Map layersByName = new LinkedHashMap(); + private tiled.core.TileLayer ground, objects, above, top, walkable; + + private Map> replacementsForLayer = new LinkedHashMap>(); + public Map activeReplacements = new LinkedHashMap(); + + private boolean tooltipActivated = true; + + public TMXReplacementViewer(final TMXMap map) { + this.map = map; + renderer = createRenderer(map.tmxMap); + + init(); + + setPreferredSize(renderer.getMapSize()); + setOpaque(true); + + addMouseMotionListener(new MouseMotionAdapter() { + @Override + public void mouseMoved(MouseEvent e) { + Point oldTooltippedTile = new Point(tooltippedTile); + tooltippedTile.setLocation(e.getX() / 32, e.getY() / 32); + if (!showTooltip || !((TMXMap) target).tmxMap.contains(tooltippedTile.x, tooltippedTile.y)) { + if (tooltipActivated) { + //Hides the tooltip... + ToolTipManager.sharedInstance().setEnabled(false); + ToolTipManager.sharedInstance().unregisterComponent(TMXReplacementViewer.this); + tooltipActivated = false; + } + } else { + if (showTooltip && !tooltipActivated) { + ToolTipManager.sharedInstance().registerComponent(TMXReplacementViewer.this); + ToolTipManager.sharedInstance().setEnabled(true); + tooltipActivated = true; + } + } + if (showHeroWithMouse && (oldTooltippedTile.x != tooltippedTile.x || oldTooltippedTile.y != tooltippedTile.y)) { + TMXReplacementViewer.this.revalidate(); + TMXReplacementViewer.this.repaint(); + } + } + }); + + ToolTipManager.sharedInstance().registerComponent(this); + setToolTipText(""); + + } + + public void init() { + groundName = objectsName = aboveName = walkableName = topName = null; + layersByName.clear(); + ground = objects = above = walkable = top = null; + replacementsForLayer.clear(); + + for (tiled.core.MapLayer layer : map.tmxMap.getLayers()) { + if (layer instanceof tiled.core.TileLayer) { + layersByName.put(layer.getName(), (tiled.core.TileLayer) layer); + if (TMXMap.GROUND_LAYER_NAME.equalsIgnoreCase(layer.getName())) { + groundName = layer.getName(); + } else if (TMXMap.OBJECTS_LAYER_NAME.equalsIgnoreCase(layer.getName())) { + objectsName = layer.getName(); + } else if (TMXMap.ABOVE_LAYER_NAME.equalsIgnoreCase(layer.getName())) { + aboveName = layer.getName(); + } else if (TMXMap.TOP_LAYER_NAME.equalsIgnoreCase(layer.getName())) { + topName = layer.getName(); + } else if (TMXMap.WALKABLE_LAYER_NAME.equalsIgnoreCase(layer.getName())) { + walkableName = layer.getName(); + } + } + } + + for (MapObjectGroup group : map.groups) { + for (MapObject object : group.mapObjects) { + if (object instanceof ReplaceArea) { + ReplaceArea area = (ReplaceArea) object; + if (!activeReplacements.containsKey(area)) { + activeReplacements.put(area, true); + } + + if (area.replacements != null) { + for (ReplaceArea.Replacement repl : area.replacements) { + if (replacementsForLayer.get(repl.sourceLayer) == null) { + replacementsForLayer.put(repl.sourceLayer, new ArrayList()); + } + replacementsForLayer.get(repl.sourceLayer).add(area); + } + } + } + } + } + updateLayers(); + } + + public void updateLayers() { + ground = mergeReplacements(groundName); + objects = mergeReplacements(objectsName); + above = mergeReplacements(aboveName); + top = mergeReplacements(topName); + walkable = mergeReplacements(walkableName); + } + + private tiled.core.TileLayer mergeReplacements(String layerName) { + tiled.core.TileLayer merged = null; + if (layerName != null && layersByName.get(layerName) != null) { + tiled.core.TileLayer original = layersByName.get(layerName); + merged = new tiled.core.TileLayer(original.getBounds()); + merged.copyFrom(original); + if (replacementsForLayer.containsKey(layerName)) { + for (ReplaceArea area : replacementsForLayer.get(layerName)) { + if (activeReplacements.get(area)) { + String targetName = null; + for (ReplaceArea.Replacement repl : area.replacements) { + if (layerName.equals(repl.sourceLayer)) { + targetName = repl.targetLayer; + } + } + if (targetName != null) { + for (int x = area.x / 32; x < (area.x + area.w) / 32; x++) { + for (int y = area.y / 32; y < (area.y + area.h) / 32; y++) { + merged.setTileAt(x, y, layersByName.get(targetName).getTileAt(x, y)); + } + } + } + } + } + } + } + return merged; + } + + public void setHighlight(ReplaceArea selected) { + highlighted = selected; + invalidate(); + } + + public void paintComponent(Graphics g) { + final Graphics2D g2d = (Graphics2D) g.create(); + final Rectangle clip = g2d.getClipBounds(); + + // Draw a gray background + g2d.setPaint(new Color(100, 100, 100)); + g2d.fill(clip); + + // Draw each tile map layer + + if (ground != null) { + renderer.paintTileLayer(g2d, ground); + } + + if (objects != null) { + renderer.paintTileLayer(g2d, objects); + } + + if (showHeroWithMouse && tooltippedTile != null && ((TMXMap) target).tmxMap.contains(tooltippedTile.x, tooltippedTile.y) && + walkable != null && walkable.getTileAt(tooltippedTile.x, tooltippedTile.y) == null) { + g2d.drawImage(DefaultIcons.getHeroImage(), tooltippedTile.x * 32, tooltippedTile.y * 32, 32, 32, null); + } + + if (above != null) { + renderer.paintTileLayer(g2d, above); + } + + if (top != null) { + renderer.paintTileLayer(g2d, top); + } + if (walkable != null && showWalkable) { + renderer.paintTileLayer(g2d, walkable); + } + + if (map.colorFilter != null) { + MapColorFilters.applyColorfilter(map.colorFilter, g2d); + } + + + if (highlighted != null) { + drawObject(highlighted, g2d, new Color(190, 20, 20)); + } + + g2d.dispose(); + } + + + private OrthogonalRenderer createRenderer(tiled.core.Map map) { + return new OrthogonalRenderer(map); + } + + public Dimension getPreferredScrollableViewportSize() { + return getPreferredSize(); + } + + public int getScrollableUnitIncrement(Rectangle visibleRect, + int orientation, int direction) { + if (orientation == SwingConstants.HORIZONTAL) + return ((TMXMap) target).tmxMap.getTileWidth(); + else + return ((TMXMap) target).tmxMap.getTileHeight(); + } + + public int getScrollableBlockIncrement(Rectangle visibleRect, + int orientation, int direction) { + if (orientation == SwingConstants.HORIZONTAL) { + final int tileWidth = ((TMXMap) target).tmxMap.getTileWidth(); + return (visibleRect.width / tileWidth - 1) * tileWidth; + } else { + final int tileHeight = ((TMXMap) target).tmxMap.getTileHeight(); + return (visibleRect.height / tileHeight - 1) * tileHeight; + } + } + + public boolean getScrollableTracksViewportWidth() { + return false; + } + + public boolean getScrollableTracksViewportHeight() { + return false; + } + + JLabel noTileGround = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); + JLabel noTileObjects = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); + JLabel noTileAbove = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); + JLabel noTileTop = new JLabel("None", new ImageIcon(DefaultIcons.getNullifyImage().getScaledInstance(32, 32, Image.SCALE_DEFAULT)), SwingConstants.LEFT); + + { + noTileGround.setPreferredSize(new Dimension(32, 32)); + noTileObjects.setPreferredSize(new Dimension(32, 32)); + noTileAbove.setPreferredSize(new Dimension(32, 32)); + noTileTop.setPreferredSize(new Dimension(32, 32)); + } + + Point tooltippedTile = new Point(); + JToolTip tt = null; + Point lastTTTile = null; + + @Override + public JToolTip createToolTip() { + if (tooltippedTile.equals(lastTTTile)) { + return tt; + } + if (!((TMXMap) target).tmxMap.contains(tooltippedTile.x, tooltippedTile.y)) { + return super.createToolTip(); + } + tt = super.createToolTip(); + lastTTTile = new Point(tooltippedTile); + tt.setLayout(new BorderLayout()); + JPanel content = new JPanel(); + content.setLayout(new JideBoxLayout(content, JideBoxLayout.PAGE_AXIS)); + if (tooltippedTile != null) { + tiled.core.Tile tile; + Image tileImage; + JLabel label; + + if (top != null && top.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { + tile = top.getTileAt(tooltippedTile.x, tooltippedTile.y); + tileImage = tile.getImage(); + } else { + tile = null; + tileImage = null; + } + if (tileImage != null) { + label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); + label.setPreferredSize(new Dimension(32, 32)); + content.add(label, JideBoxLayout.FIX); + //Fix when (if?) Top is advertised publicly. // } else { // content.add(noTileTop, JideBoxLayout.FIX); - } - - if (above != null && above.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { - tile = above.getTileAt(tooltippedTile.x, tooltippedTile.y); - tileImage = tile.getImage(); - } else { - tile = null; - tileImage = null; - } - if (tileImage != null) { - label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); - label.setPreferredSize(new Dimension(32,32)); - content.add(label, JideBoxLayout.FIX); - } else { - content.add(noTileAbove, JideBoxLayout.FIX); - } - - if (objects != null && objects.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { - tile = objects.getTileAt(tooltippedTile.x, tooltippedTile.y); - tileImage = tile.getImage(); - } else { - tile = null; - tileImage = null; - } - if (tileImage != null) { - label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); - label.setPreferredSize(new Dimension(32,32)); - content.add(label, JideBoxLayout.FIX); - } else { - content.add(noTileObjects, JideBoxLayout.FIX); - } - - if (ground != null && ground.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { - tile = ground.getTileAt(tooltippedTile.x, tooltippedTile.y); - tileImage = tile.getImage(); - } else { - tile = null; - tileImage = null; - } - if (tileImage != null) { - label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); - label.setPreferredSize(new Dimension(32,32)); - content.add(label, JideBoxLayout.FIX); - } else { - content.add(noTileGround, JideBoxLayout.FIX); - } - - content.add(new JLabel(tooltippedTile.x+", "+tooltippedTile.y), JideBoxLayout.FIX); - - } - - tt.add(content, BorderLayout.CENTER); - tt.setPreferredSize(tt.getLayout().preferredLayoutSize(tt)); - return tt; - } - - @Override - public Point getToolTipLocation(MouseEvent event) { - return event.getPoint();//new Point(event.getX() - (event.getX() % 32), event.getY() - (event.getY() % 32)); - } - - } - - - public Point getClosestTileCorner(Point p) { - return new Point(getClosestMultiple(p.x, 32), getClosestMultiple(p.y, 32)); + } + + if (above != null && above.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { + tile = above.getTileAt(tooltippedTile.x, tooltippedTile.y); + tileImage = tile.getImage(); + } else { + tile = null; + tileImage = null; + } + if (tileImage != null) { + label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); + label.setPreferredSize(new Dimension(32, 32)); + content.add(label, JideBoxLayout.FIX); + } else { + content.add(noTileAbove, JideBoxLayout.FIX); + } + + if (objects != null && objects.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { + tile = objects.getTileAt(tooltippedTile.x, tooltippedTile.y); + tileImage = tile.getImage(); + } else { + tile = null; + tileImage = null; + } + if (tileImage != null) { + label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); + label.setPreferredSize(new Dimension(32, 32)); + content.add(label, JideBoxLayout.FIX); + } else { + content.add(noTileObjects, JideBoxLayout.FIX); + } + + if (ground != null && ground.getTileAt(tooltippedTile.x, tooltippedTile.y) != null) { + tile = ground.getTileAt(tooltippedTile.x, tooltippedTile.y); + tileImage = tile.getImage(); + } else { + tile = null; + tileImage = null; + } + if (tileImage != null) { + label = new JLabel(tile.getTileSet().getName(), new ImageIcon(tileImage), SwingConstants.LEFT); + label.setPreferredSize(new Dimension(32, 32)); + content.add(label, JideBoxLayout.FIX); + } else { + content.add(noTileGround, JideBoxLayout.FIX); + } + + content.add(new JLabel(tooltippedTile.x + ", " + tooltippedTile.y), JideBoxLayout.FIX); + + } + + tt.add(content, BorderLayout.CENTER); + tt.setPreferredSize(tt.getLayout().preferredLayoutSize(tt)); + return tt; + } + + @Override + public Point getToolTipLocation(MouseEvent event) { + return event.getPoint();//new Point(event.getX() - (event.getX() % 32), event.getY() - (event.getY() % 32)); + } + } - + + + public Point getClosestTileCorner(Point p) { + return new Point(getClosestMultiple(p.x, 32), getClosestMultiple(p.y, 32)); + } + public int getClosestMultiple(int num, int ref) { - int rest = num % ref; - int result = num - rest; - if (rest >= ref / 2) { - result += ref; - } - return result; + int rest = num % ref; + int result = num - rest; + if (rest >= ref / 2) { + result += ref; + } + return result; } - - + + private void drawObject(MapObject object, Graphics2D g2d, Color color) { - g2d.setPaint(color); - g2d.drawRect(object.x+1, object.y+1, object.w-3, object.h-3); - g2d.drawRect(object.x+2, object.y+2, object.w-5, object.h-5); - g2d.setPaint(color.darker().darker()); - g2d.drawLine(object.x, object.y + object.h - 1, object.x + object.w - 1, object.y + object.h - 1); - g2d.drawLine(object.x + object.w - 1, object.y, object.x + object.w - 1, object.y + object.h - 1); - g2d.drawLine(object.x + 3, object.y + 3, object.x + object.w - 4, object.y + 3); - g2d.drawLine(object.x + 3, object.y + 3, object.x + 3, object.y + object.h - 4); - g2d.setPaint(color.brighter().brighter().brighter()); - g2d.drawLine(object.x, object.y, object.x + object.w - 1, object.y); - g2d.drawLine(object.x, object.y, object.x, object.y + object.h - 1); - g2d.drawLine(object.x + 3, object.y + object.h - 4, object.x + object.w - 4, object.y + object.h - 4); - g2d.drawLine(object.x + object.w - 4, object.y + 3, object.x + object.w - 4, object.y + object.h - 4); - Image img = object.getIcon(); - g2d.setColor(new Color(255, 255, 255, 120)); - g2d.fillRect(object.x + 2, object.y + 2, img.getWidth(null), img.getHeight(null)); - g2d.drawImage(object.getIcon(), object.x + 2, object.y + 2, null); + g2d.setPaint(color); + g2d.drawRect(object.x + 1, object.y + 1, object.w - 3, object.h - 3); + g2d.drawRect(object.x + 2, object.y + 2, object.w - 5, object.h - 5); + g2d.setPaint(color.darker().darker()); + g2d.drawLine(object.x, object.y + object.h - 1, object.x + object.w - 1, object.y + object.h - 1); + g2d.drawLine(object.x + object.w - 1, object.y, object.x + object.w - 1, object.y + object.h - 1); + g2d.drawLine(object.x + 3, object.y + 3, object.x + object.w - 4, object.y + 3); + g2d.drawLine(object.x + 3, object.y + 3, object.x + 3, object.y + object.h - 4); + g2d.setPaint(color.brighter().brighter().brighter()); + g2d.drawLine(object.x, object.y, object.x + object.w - 1, object.y); + g2d.drawLine(object.x, object.y, object.x, object.y + object.h - 1); + g2d.drawLine(object.x + 3, object.y + object.h - 4, object.x + object.w - 4, object.y + object.h - 4); + g2d.drawLine(object.x + object.w - 4, object.y + 3, object.x + object.w - 4, object.y + object.h - 4); + Image img = object.getIcon(); + g2d.setColor(new Color(255, 255, 255, 120)); + g2d.fillRect(object.x + 2, object.y + 2, img.getWidth(null), img.getHeight(null)); + g2d.drawImage(object.getIcon(), object.x + 2, object.y + 2, null); } - - @Override - public void mapChanged() { - if (reload != null) reload.setEnabled(true); - } + @Override + public void mapChanged() { + if (reload != null) reload.setEnabled(true); + } + @Override + public void mapReloaded() { + ATContentStudio.frame.nodeChanged(target); + ((TMXMap) target).removeMapChangedOnDiskListener(this); + ATContentStudio.frame.closeEditor(target); + ATContentStudio.frame.openEditor(target); + + } - @Override - public void mapReloaded() { - ATContentStudio.frame.nodeChanged(target); - ((TMXMap)target).removeMapChangedOnDiskListener(this); - ATContentStudio.frame.closeEditor(target); - ATContentStudio.frame.openEditor(target); - - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java index 0424bcc..0f0d4f7 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java @@ -1,46 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui.map; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JScrollPane; -import javax.swing.JSlider; -import javax.swing.JSplitPane; -import javax.swing.JTextField; -import javax.swing.JViewport; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.event.ChangeEvent; -import javax.swing.event.ChangeListener; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; - -import com.gpl.rpg.atcontentstudio.ui.*; -import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; -import org.fife.ui.rsyntaxtextarea.SyntaxConstants; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; @@ -50,1056 +9,1071 @@ import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; import com.gpl.rpg.atcontentstudio.model.maps.Worldmap; import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; +import com.gpl.rpg.atcontentstudio.ui.*; import com.jidesoft.swing.ComboBoxSearchable; import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideTabbedPane; import com.jidesoft.swing.ListSearchable; +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; + +import javax.swing.*; +import javax.swing.event.*; +import java.awt.*; +import java.awt.event.*; +import java.util.ArrayList; +import java.util.List; public class WorldMapEditor extends Editor implements FieldUpdateListener { - private static final long serialVersionUID = -8358238912588729094L; - + private static final long serialVersionUID = -8358238912588729094L; - private RSyntaxTextArea editorPane; - - public EditMode editMode = EditMode.moveViewSelect; - - public enum EditMode { - moveViewSelect, - moveMaps, - addMap - } - - public String mapBeingAddedID = null; - WorldMapView mapView = null; - WorldmapSegment.NamedArea selectedLabel = null; - MapSegmentMapsListModel msmListModel = null; - ListSelectionModel msmListSelectionModel = null; + private RSyntaxTextArea editorPane; - MapSegmentLabelsListModel mslListModel = null; - - MapSegmentLabelMapsListModel mslmListModel = null; - ListSelectionModel mslmListSelectionModel = null; - - ListModel currentSelectionListModel = null; - ListSelectionModel currentSelectionSelectionModel = null; - ListModel currentHighlightListModel = null; - - JList mapsShown; - JList labelList; - - JTextField labelIdField; - JTextField labelNameField; - JTextField labelTypeField; - - public WorldMapEditor(WorldmapSegment worldmap) { - target = worldmap; - this.name = worldmap.getDesc(); - this.icon = new ImageIcon(worldmap.getIcon()); - setLayout(new BorderLayout()); - - JideTabbedPane editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); - editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); - editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); - editorTabsHolder.setShowCloseButtonOnTab(false); - add(editorTabsHolder, BorderLayout.CENTER); + public EditMode editMode = EditMode.moveViewSelect; - editorTabsHolder.add("Map", buildSegmentTab(worldmap)); - - JScrollPane xmlScroller = new JScrollPane(getXmlEditorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - xmlScroller.getVerticalScrollBar().setUnitIncrement(16); - editorTabsHolder.add("XML", xmlScroller); - } - - @Override - public void targetUpdated() { - this.name = ((GameDataElement)target).getDesc(); - updateMessage(); - updateXmlViewText(((WorldmapSegment)target).toXml()); - mapView.updateFromModel(); - } + public enum EditMode { + moveViewSelect, + moveMaps, + addMap + } - public JPanel getXmlEditorPane() { - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - editorPane = new RSyntaxTextArea(); - editorPane.setText(((WorldmapSegment)target).toXml()); - editorPane.setEditable(false); - editorPane.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML); - editorPane.setFont(editorPane.getFont().deriveFont(ATContentStudio.SCALING * editorPane.getFont().getSize())); - pane.add(editorPane, JideBoxLayout.VARY); + public String mapBeingAddedID = null; + WorldMapView mapView = null; + WorldmapSegment.NamedArea selectedLabel = null; - return pane; - } - - public void updateXmlViewText(String text) { - editorPane.setText(text); - } - - - @SuppressWarnings("unchecked") - private JPanel buildSegmentTab(final WorldmapSegment worldmap) { - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); + MapSegmentMapsListModel msmListModel = null; + ListSelectionModel msmListSelectionModel = null; - addLabelField(pane, "Worldmap File: ", ((Worldmap)worldmap.getParent()).worldmapFile.getAbsolutePath()); - pane.add(createButtonPane(worldmap), JideBoxLayout.FIX); - - mapView = new WorldMapView(worldmap); - JScrollPane mapScroller = new JScrollPane(mapView); - final JViewport vPort = mapScroller.getViewport(); - - final JSlider zoomSlider = new JSlider(WorldMapView.MIN_ZOOM, WorldMapView.MAX_ZOOM, (int)(mapView.zoomLevel / WorldMapView.ZOOM_RATIO)); - zoomSlider.setSnapToTicks(true); - zoomSlider.setMinorTickSpacing(WorldMapView.INC_ZOOM); - zoomSlider.setOrientation(JSlider.VERTICAL); - JPanel zoomSliderPane = new JPanel(); - zoomSliderPane.setLayout(new JideBoxLayout(zoomSliderPane, JideBoxLayout.PAGE_AXIS)); - zoomSliderPane.add(zoomSlider, JideBoxLayout.VARY); - zoomSliderPane.add(new JLabel(new ImageIcon(DefaultIcons.getZoomIcon())), JideBoxLayout.FIX); - - - if (target.writable) { - JPanel mapToolsPane = new JPanel(); - mapToolsPane.setLayout(new JideBoxLayout(mapToolsPane, JideBoxLayout.LINE_AXIS)); - ButtonGroup mapToolsGroup = new ButtonGroup(); - JRadioButton moveView = new JRadioButton("Select maps"); - mapToolsGroup.add(moveView); - mapToolsPane.add(moveView, JideBoxLayout.FIX); - JRadioButton moveMaps = new JRadioButton("Move selected map(s)"); - mapToolsGroup.add(moveMaps); - mapToolsPane.add(moveMaps, JideBoxLayout.FIX); - JRadioButton addMap = new JRadioButton("Add map"); - mapToolsGroup.add(addMap); - mapToolsPane.add(addMap, JideBoxLayout.FIX); - final GDEComboModel mapComboModel = new GDEComboModel(worldmap.getProject(), null){ - private static final long serialVersionUID = 2638082961277241764L; - @Override - public TMXMap getTypedElementAt(int index) { - return project.getMap(index); - } - @Override - public int getSize() { - return project.getMapCount()+1; - } - }; - final MyComboBox mapBox = new MyComboBox(TMXMap.class, mapComboModel); - mapBox.setRenderer(new GDERenderer(false, false)); - new ComboBoxSearchable(mapBox){ - @Override - protected String convertElementToString(Object object) { - if (object == null) return "none"; - else return ((GameDataElement)object).getDesc(); - } - }; - mapBox.setEnabled(false); - mapToolsPane.add(mapBox, JideBoxLayout.FIX); - - mapToolsPane.add(new JPanel(), JideBoxLayout.VARY); - moveView.setSelected(true); - pane.add(mapToolsPane, JideBoxLayout.FIX); - - moveView.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - editMode = EditMode.moveViewSelect; - mapBox.setEnabled(false); - if (mapBeingAddedID != null) { - mapView.mapLocations.remove(mapBeingAddedID); - mapBeingAddedID = null; - mapView.revalidate(); - mapView.repaint(); - } - } - }); + MapSegmentLabelsListModel mslListModel = null; - moveMaps.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - editMode = EditMode.moveMaps; - mapBox.setEnabled(false); - if (mapBeingAddedID != null) { - mapView.mapLocations.remove(mapBeingAddedID); - mapBeingAddedID = null; - mapView.revalidate(); - mapView.repaint(); - } - } - }); + MapSegmentLabelMapsListModel mslmListModel = null; + ListSelectionModel mslmListSelectionModel = null; - addMap.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - editMode = EditMode.addMap; - mapBox.setEnabled(true); - if (mapBox.getSelectedItem() != null) { - mapBeingAddedID = ((TMXMap)mapBox.getSelectedItem()).id; - } - } - }); - - mapBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (mapBox.getSelectedItem() == null) { - mapBeingAddedID = null; - } else { - if (mapBeingAddedID != null) { - mapView.updateFromModel(); - } - mapBeingAddedID = ((TMXMap)mapBox.getSelectedItem()).id; - if (mapView.mapLocations.isEmpty()) { - TMXMap map = target.getProject().getMap(mapBeingAddedID); - int w = map.tmxMap.getWidth() * WorldMapView.TILE_SIZE; - int h = map.tmxMap.getHeight() * WorldMapView.TILE_SIZE; - mapView.mapLocations.put(mapBeingAddedID, new Rectangle(0, 0, w, h)); - mapView.recomputeSize(); - mapView.revalidate(); - mapView.repaint(); - } - } - } - }); - - } - - JPanel mapZoomPane = new JPanel(); - mapZoomPane.setLayout(new BorderLayout()); - mapZoomPane.add(zoomSliderPane, BorderLayout.WEST); - mapZoomPane.add(mapScroller, BorderLayout.CENTER); - - JPanel mapPropsPane = new JPanel(); - buildMapPropsPane(mapPropsPane, worldmap); - - setCurrentSelectionModel(msmListModel, msmListSelectionModel); - - - final JSplitPane mapAndPropsSplitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mapZoomPane, mapPropsPane); - SwingUtilities.invokeLater(new Runnable(){ - @Override - public void run() { - mapAndPropsSplitter.setDividerLocation(0.8d); - } - }); - pane.add(mapAndPropsSplitter, JideBoxLayout.VARY); - - zoomSlider.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - - Rectangle view = vPort.getViewRect(); - - float oldZoomLevel = mapView.zoomLevel; - mapView.zoomLevel = zoomSlider.getValue() * WorldMapView.ZOOM_RATIO; - - int newCenterX = (int) (view.getCenterX() / oldZoomLevel * mapView.zoomLevel); - int newCenterY = (int) (view.getCenterY() / oldZoomLevel * mapView.zoomLevel); + ListModel currentSelectionListModel = null; + ListSelectionModel currentSelectionSelectionModel = null; + ListModel currentHighlightListModel = null; - view.x = newCenterX - (view.width / 2); - view.y = newCenterY - (view.height / 2); - - mapView.scrollRectToVisible(view); - mapView.revalidate(); - mapView.repaint(); - } - }); - - MouseAdapter mouseListener = new MouseAdapter() { - final int skipRecomputeDefault = 5; - Point dragStart = null; - int skipRecompute = 0; - - @Override - public void mouseClicked(MouseEvent e) { - String selectedMap = null; + JList mapsShown; + JList labelList; + + JTextField labelIdField; + JTextField labelNameField; + JTextField labelTypeField; + + public WorldMapEditor(WorldmapSegment worldmap) { + target = worldmap; + this.name = worldmap.getDesc(); + this.icon = new ImageIcon(worldmap.getIcon()); + setLayout(new BorderLayout()); + + JideTabbedPane editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); + editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); + editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); + editorTabsHolder.setShowCloseButtonOnTab(false); + add(editorTabsHolder, BorderLayout.CENTER); + + editorTabsHolder.add("Map", buildSegmentTab(worldmap)); + + JScrollPane xmlScroller = new JScrollPane(getXmlEditorPane(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + xmlScroller.getVerticalScrollBar().setUnitIncrement(16); + editorTabsHolder.add("XML", xmlScroller); + } + + @Override + public void targetUpdated() { + this.name = ((GameDataElement) target).getDesc(); + updateMessage(); + updateXmlViewText(((WorldmapSegment) target).toXml()); + mapView.updateFromModel(); + } + + public JPanel getXmlEditorPane() { + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + editorPane = new RSyntaxTextArea(); + editorPane.setText(((WorldmapSegment) target).toXml()); + editorPane.setEditable(false); + editorPane.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_XML); + editorPane.setFont(editorPane.getFont().deriveFont(ATContentStudio.SCALING * editorPane.getFont().getSize())); + pane.add(editorPane, JideBoxLayout.VARY); + + return pane; + } + + public void updateXmlViewText(String text) { + editorPane.setText(text); + } + + + @SuppressWarnings("unchecked") + private JPanel buildSegmentTab(final WorldmapSegment worldmap) { + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS)); + + addLabelField(pane, "Worldmap File: ", ((Worldmap) worldmap.getParent()).worldmapFile.getAbsolutePath()); + pane.add(createButtonPane(worldmap), JideBoxLayout.FIX); + + mapView = new WorldMapView(worldmap); + JScrollPane mapScroller = new JScrollPane(mapView); + final JViewport vPort = mapScroller.getViewport(); + + final JSlider zoomSlider = new JSlider(WorldMapView.MIN_ZOOM, WorldMapView.MAX_ZOOM, (int) (mapView.zoomLevel / WorldMapView.ZOOM_RATIO)); + zoomSlider.setSnapToTicks(true); + zoomSlider.setMinorTickSpacing(WorldMapView.INC_ZOOM); + zoomSlider.setOrientation(JSlider.VERTICAL); + JPanel zoomSliderPane = new JPanel(); + zoomSliderPane.setLayout(new JideBoxLayout(zoomSliderPane, JideBoxLayout.PAGE_AXIS)); + zoomSliderPane.add(zoomSlider, JideBoxLayout.VARY); + zoomSliderPane.add(new JLabel(new ImageIcon(DefaultIcons.getZoomIcon())), JideBoxLayout.FIX); + + + if (target.writable) { + JPanel mapToolsPane = new JPanel(); + mapToolsPane.setLayout(new JideBoxLayout(mapToolsPane, JideBoxLayout.LINE_AXIS)); + ButtonGroup mapToolsGroup = new ButtonGroup(); + JRadioButton moveView = new JRadioButton("Select maps"); + mapToolsGroup.add(moveView); + mapToolsPane.add(moveView, JideBoxLayout.FIX); + JRadioButton moveMaps = new JRadioButton("Move selected map(s)"); + mapToolsGroup.add(moveMaps); + mapToolsPane.add(moveMaps, JideBoxLayout.FIX); + JRadioButton addMap = new JRadioButton("Add map"); + mapToolsGroup.add(addMap); + mapToolsPane.add(addMap, JideBoxLayout.FIX); + final GDEComboModel mapComboModel = new GDEComboModel(worldmap.getProject(), null) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public TMXMap getTypedElementAt(int index) { + return project.getMap(index); + } + + @Override + public int getSize() { + return project.getMapCount() + 1; + } + }; + final MyComboBox mapBox = new MyComboBox(TMXMap.class, mapComboModel); + mapBox.setRenderer(new GDERenderer(false, false)); + new ComboBoxSearchable(mapBox) { + @Override + protected String convertElementToString(Object object) { + if (object == null) return "none"; + else return ((GameDataElement) object).getDesc(); + } + }; + mapBox.setEnabled(false); + mapToolsPane.add(mapBox, JideBoxLayout.FIX); + + mapToolsPane.add(new JPanel(), JideBoxLayout.VARY); + moveView.setSelected(true); + pane.add(mapToolsPane, JideBoxLayout.FIX); + + moveView.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + editMode = EditMode.moveViewSelect; + mapBox.setEnabled(false); + if (mapBeingAddedID != null) { + mapView.mapLocations.remove(mapBeingAddedID); + mapBeingAddedID = null; + mapView.revalidate(); + mapView.repaint(); + } + } + }); + + moveMaps.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + editMode = EditMode.moveMaps; + mapBox.setEnabled(false); + if (mapBeingAddedID != null) { + mapView.mapLocations.remove(mapBeingAddedID); + mapBeingAddedID = null; + mapView.revalidate(); + mapView.repaint(); + } + } + }); + + addMap.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + editMode = EditMode.addMap; + mapBox.setEnabled(true); + if (mapBox.getSelectedItem() != null) { + mapBeingAddedID = ((TMXMap) mapBox.getSelectedItem()).id; + } + } + }); + + mapBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (mapBox.getSelectedItem() == null) { + mapBeingAddedID = null; + } else { + if (mapBeingAddedID != null) { + mapView.updateFromModel(); + } + mapBeingAddedID = ((TMXMap) mapBox.getSelectedItem()).id; + if (mapView.mapLocations.isEmpty()) { + TMXMap map = target.getProject().getMap(mapBeingAddedID); + int w = map.tmxMap.getWidth() * WorldMapView.TILE_SIZE; + int h = map.tmxMap.getHeight() * WorldMapView.TILE_SIZE; + mapView.mapLocations.put(mapBeingAddedID, new Rectangle(0, 0, w, h)); + mapView.recomputeSize(); + mapView.revalidate(); + mapView.repaint(); + } + } + } + }); + + } + + JPanel mapZoomPane = new JPanel(); + mapZoomPane.setLayout(new BorderLayout()); + mapZoomPane.add(zoomSliderPane, BorderLayout.WEST); + mapZoomPane.add(mapScroller, BorderLayout.CENTER); + + JPanel mapPropsPane = new JPanel(); + buildMapPropsPane(mapPropsPane, worldmap); + + setCurrentSelectionModel(msmListModel, msmListSelectionModel); + + + final JSplitPane mapAndPropsSplitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mapZoomPane, mapPropsPane); + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + mapAndPropsSplitter.setDividerLocation(0.8d); + } + }); + pane.add(mapAndPropsSplitter, JideBoxLayout.VARY); + + zoomSlider.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + + Rectangle view = vPort.getViewRect(); + + float oldZoomLevel = mapView.zoomLevel; + mapView.zoomLevel = zoomSlider.getValue() * WorldMapView.ZOOM_RATIO; + + int newCenterX = (int) (view.getCenterX() / oldZoomLevel * mapView.zoomLevel); + int newCenterY = (int) (view.getCenterY() / oldZoomLevel * mapView.zoomLevel); + + view.x = newCenterX - (view.width / 2); + view.y = newCenterY - (view.height / 2); + + mapView.scrollRectToVisible(view); + mapView.revalidate(); + mapView.repaint(); + } + }); + + MouseAdapter mouseListener = new MouseAdapter() { + final int skipRecomputeDefault = 5; + Point dragStart = null; + int skipRecompute = 0; + + @Override + public void mouseClicked(MouseEvent e) { + String selectedMap = null; // boolean update = false; - int x = (int) (e.getX() / mapView.zoomLevel); - int y = (int) (e.getY() / mapView.zoomLevel); - for (String s : mapView.mapLocations.keySet()) { - if (mapView.mapLocations.get(s).contains(x, y)) { - selectedMap = s; - break; - } - } - if (editMode == EditMode.moveViewSelect) { - if (selectedMap == null) return; - if (e.getButton() == MouseEvent.BUTTON1) { - if (e.isControlDown() || e.isShiftDown()) { - if (mapView.getSelectedMapsIDs().contains(selectedMap)) { - if (mapView.getSelectedMapsIDs().size() > 1) { - removeFromSelection(selectedMap); + int x = (int) (e.getX() / mapView.zoomLevel); + int y = (int) (e.getY() / mapView.zoomLevel); + for (String s : mapView.mapLocations.keySet()) { + if (mapView.mapLocations.get(s).contains(x, y)) { + selectedMap = s; + break; + } + } + if (editMode == EditMode.moveViewSelect) { + if (selectedMap == null) return; + if (e.getButton() == MouseEvent.BUTTON1) { + if (e.isControlDown() || e.isShiftDown()) { + if (mapView.getSelectedMapsIDs().contains(selectedMap)) { + if (mapView.getSelectedMapsIDs().size() > 1) { + removeFromSelection(selectedMap); // mapView.selected.remove(selectedMap); // update = true; - } - } else { - addToSelection(selectedMap); + } + } else { + addToSelection(selectedMap); // mapView.selected.add(selectedMap); // update = true; - } - } else { - clearSelection(); + } + } else { + clearSelection(); // mapView.selected.clear(); - addToSelection(selectedMap); + addToSelection(selectedMap); // mapView.selected.add(selectedMap); // update = true; - } - } - } else if (editMode == EditMode.addMap && mapBeingAddedID != null) { - if (e.getButton() == MouseEvent.BUTTON1) { - mapView.recomputeSize(); - pushToModel(); - } - mapView.updateFromModel(); + } + } + } else if (editMode == EditMode.addMap && mapBeingAddedID != null) { + if (e.getButton() == MouseEvent.BUTTON1) { + mapView.recomputeSize(); + pushToModel(); + } + mapView.updateFromModel(); // update = true; - mapBeingAddedID = null; - } + mapBeingAddedID = null; + } // if (update) { // validateSelection(); // } - } - - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - dragStart = e.getLocationOnScreen(); - } - } - - @Override - public void mouseReleased(MouseEvent e) { - dragStart = null; - if (editMode == EditMode.moveMaps) { - pushToModel(); - } - } - - @Override - public void mouseMoved(MouseEvent e) { - if (editMode == EditMode.addMap && mapBeingAddedID != null) { - int x = (int) (e.getX() / mapView.zoomLevel); - int y = (int) (e.getY() / mapView.zoomLevel); - TMXMap map = target.getProject().getMap(mapBeingAddedID); - int w = map.tmxMap.getWidth() * WorldMapView.TILE_SIZE; - int h = map.tmxMap.getHeight() * WorldMapView.TILE_SIZE; - x -= w / 2; - x -= x % WorldMapView.TILE_SIZE; - y -= h / 2; - y -= y % WorldMapView.TILE_SIZE; - mapView.mapLocations.put(mapBeingAddedID, new Rectangle(x, y, w, h)); - if (--skipRecompute <= 0) { - if (mapView.recomputeSize()) { - skipRecompute = skipRecomputeDefault; - } - } - mapView.revalidate(); - mapView.repaint(); - } - } - - @Override - public void mouseDragged(MouseEvent e) { - if (dragStart == null) return; - int deltaX = e.getXOnScreen() - dragStart.x; - int deltaY = e.getYOnScreen() - dragStart.y; + } - if (editMode != EditMode.moveMaps) { - Rectangle view = vPort.getViewRect(); - view.setLocation(view.x - deltaX, view.y - deltaY); - mapView.scrollRectToVisible(view); + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + dragStart = e.getLocationOnScreen(); + } + } - dragStart = e.getLocationOnScreen(); - } else { - int mapDeltaX = (int) ((deltaX / mapView.zoomLevel)); - int mapDeltaY = (int) ((deltaY / mapView.zoomLevel)); - - mapDeltaX -= mapDeltaX % WorldMapView.TILE_SIZE; - mapDeltaY -= mapDeltaY % WorldMapView.TILE_SIZE; - - for (String s : mapView.getSelectedMapsIDs()) { - mapView.mapLocations.get(s).x = (worldmap.mapLocations.get(s).x * WorldMapView.TILE_SIZE) + mapDeltaX; - mapView.mapLocations.get(s).y = (worldmap.mapLocations.get(s).y * WorldMapView.TILE_SIZE) + mapDeltaY; - } + @Override + public void mouseReleased(MouseEvent e) { + dragStart = null; + if (editMode == EditMode.moveMaps) { + pushToModel(); + } + } - if (--skipRecompute <= 0) { - if (mapView.recomputeSize()) { - skipRecompute = skipRecomputeDefault; - } - } + @Override + public void mouseMoved(MouseEvent e) { + if (editMode == EditMode.addMap && mapBeingAddedID != null) { + int x = (int) (e.getX() / mapView.zoomLevel); + int y = (int) (e.getY() / mapView.zoomLevel); + TMXMap map = target.getProject().getMap(mapBeingAddedID); + int w = map.tmxMap.getWidth() * WorldMapView.TILE_SIZE; + int h = map.tmxMap.getHeight() * WorldMapView.TILE_SIZE; + x -= w / 2; + x -= x % WorldMapView.TILE_SIZE; + y -= h / 2; + y -= y % WorldMapView.TILE_SIZE; + mapView.mapLocations.put(mapBeingAddedID, new Rectangle(x, y, w, h)); + if (--skipRecompute <= 0) { + if (mapView.recomputeSize()) { + skipRecompute = skipRecomputeDefault; + } + } + mapView.revalidate(); + mapView.repaint(); + } + } - mapView.revalidate(); - mapView.repaint(); - } - } - - - }; + @Override + public void mouseDragged(MouseEvent e) { + if (dragStart == null) return; + int deltaX = e.getXOnScreen() - dragStart.x; + int deltaY = e.getYOnScreen() - dragStart.y; - mapView.addMouseListener(mouseListener); - mapView.addMouseMotionListener(mouseListener); - - mapView.addMapClickListener(new WorldMapView.MapClickListener() { - @Override - public void mapClicked(MouseEvent e, TMXMap m) { - if (e.getClickCount() == 2) { - ATContentStudio.frame.openEditor(m); - } - } - - @Override - public void mapChangeClicked(MouseEvent e, TMXMap m, TMXMap changeTarget) { - if (e.getClickCount() == 2) { - ATContentStudio.frame.openEditor(changeTarget); - } - } - - @Override - public void backgroundClicked(MouseEvent e) { - } - }); - - return pane; - } - - + if (editMode != EditMode.moveMaps) { + Rectangle view = vPort.getViewRect(); + view.setLocation(view.x - deltaX, view.y - deltaY); + mapView.scrollRectToVisible(view); - private void buildMapPropsPane(JPanel mapPropsPane, final WorldmapSegment worldmap) { - JideTabbedPane tabPane = new JideTabbedPane(JideTabbedPane.TOP); - - JPanel mapListPane = new JPanel(); - mapListPane.setLayout(new JideBoxLayout(mapListPane, JideBoxLayout.PAGE_AXIS)); - mapListPane.add(new JLabel("Maps shown here"), JideBoxLayout.FIX); - msmListModel = new MapSegmentMapsListModel(worldmap); - mapsShown = new JList(msmListModel); - mapsShown.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - msmListSelectionModel = mapsShown.getSelectionModel(); - mapsShown.setCellRenderer(new MapCellRenderer()); - new ListSearchable(mapsShown) { - @Override - protected String convertElementToString(Object object) { - return ((TMXMap)object).id; - } - }; - mapListPane.add(new JScrollPane(mapsShown), JideBoxLayout.VARY); - mapsShown.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { - ATContentStudio.frame.openEditor(mapsShown.getSelectedValue()); - ATContentStudio.frame.selectInTree(mapsShown.getSelectedValue()); - } - } - }); - mapsShown.addKeyListener(new KeyAdapter() { - @Override - public void keyReleased(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - ATContentStudio.frame.openEditor(mapsShown.getSelectedValue()); - ATContentStudio.frame.selectInTree(mapsShown.getSelectedValue()); - } - } - }); - mapsShown.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - setCurrentSelectionModel(msmListModel, msmListSelectionModel); - } - }); - - - tabPane.addTab("Map list", mapListPane); - - final JPanel labelEditPane = new JPanel(); - labelEditPane.setLayout(new JideBoxLayout(labelEditPane, JideBoxLayout.PAGE_AXIS)); - labelEditPane.add(new JLabel("Labels on the worldmap"), JideBoxLayout.FIX); - - mslListModel = new MapSegmentLabelsListModel(worldmap); - labelList = new JList(mslListModel); - labelList.setCellRenderer(new MapLabelCellRenderer()); - labelList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - labelEditPane.add(new JScrollPane(labelList), JideBoxLayout.FLEXIBLE); - - JPanel labelListButtonsPane = new JPanel(); - labelListButtonsPane.setLayout(new JideBoxLayout(labelListButtonsPane, JideBoxLayout.LINE_AXIS)); - final JButton createLabel = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - labelListButtonsPane.add(createLabel, JideBoxLayout.FIX); - final JButton deleteLabel = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - labelListButtonsPane.add(deleteLabel, JideBoxLayout.FIX); - labelListButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - labelEditPane.add(labelListButtonsPane, JideBoxLayout.FIX); - - final JPanel labelParametersPane = new JPanel(); - labelEditPane.add(labelParametersPane, JideBoxLayout.FLEXIBLE); - - labelList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedLabel = labelList.getSelectedValue(); - updateLabelParamsPane(labelParametersPane, worldmap); - labelEditPane.revalidate(); - labelEditPane.repaint(); - } - }); - - createLabel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - WorldmapSegment.NamedArea creation = new WorldmapSegment.NamedArea(null, null, null); - worldmap.labels.put(WorldmapSegment.TEMP_LABEL_KEY, creation); - worldmap.labelledMaps.put(WorldmapSegment.TEMP_LABEL_KEY, new ArrayList()); - mslListModel.listChanged(); - labelList.setSelectedValue(creation, true); - } - }); - - deleteLabel.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedLabel.id != null) { - worldmap.labelledMaps.remove(selectedLabel.id); - worldmap.labels.remove(selectedLabel.id); - } else { - worldmap.labelledMaps.remove(WorldmapSegment.TEMP_LABEL_KEY); - worldmap.labels.remove(WorldmapSegment.TEMP_LABEL_KEY); - } - labelList.clearSelection(); - mslListModel.listChanged(); - notifyModelModified(); - } - }); + dragStart = e.getLocationOnScreen(); + } else { + int mapDeltaX = (int) ((deltaX / mapView.zoomLevel)); + int mapDeltaY = (int) ((deltaY / mapView.zoomLevel)); - - tabPane.addTab("Labels", labelEditPane); - - mapPropsPane.setLayout(new BorderLayout()); - mapPropsPane.add(tabPane, BorderLayout.CENTER); - } - - private void updateLabelParamsPane(JPanel labelParametersPane, final WorldmapSegment worldmap) { - labelParametersPane.removeAll(); - if (selectedLabel == null) { - setCurrentHighlightModel(null); - return; - } - labelParametersPane.setLayout(new JideBoxLayout(labelParametersPane, JideBoxLayout.PAGE_AXIS)); - - labelIdField = addTextField(labelParametersPane, "Internal ID: ", selectedLabel.id, worldmap.writable, this); - labelNameField = addTranslatableTextField(labelParametersPane, "Name: ", selectedLabel.name, worldmap.writable, this); - labelTypeField = addTextField(labelParametersPane, "Type: ", selectedLabel.type, worldmap.writable, this); - - - labelParametersPane.add(new JLabel("Label covers the following maps"), JideBoxLayout.FIX); - - mslmListModel = new MapSegmentLabelMapsListModel(worldmap, selectedLabel); - final JList labelCoverageList = new JList(mslmListModel); - labelCoverageList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - mslmListSelectionModel = labelCoverageList.getSelectionModel(); - labelCoverageList.setCellRenderer(new MapCellRenderer()); - labelParametersPane.add(new JScrollPane(labelCoverageList), JideBoxLayout.VARY); - labelCoverageList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - setCurrentHighlightModel(mslmListModel); - } - }); - - JPanel labelCoverageButtonsPane = new JPanel(); - labelCoverageButtonsPane.setLayout(new JideBoxLayout(labelCoverageButtonsPane, JideBoxLayout.LINE_AXIS)); - JButton addCoverage = new JButton("Add on-map selection"); - labelCoverageButtonsPane.add(addCoverage, JideBoxLayout.FIX); - JButton replaceCoverage = new JButton("Replace by on-map selection"); - labelCoverageButtonsPane.add(replaceCoverage, JideBoxLayout.FIX); - JButton removeFromCoverage = new JButton("Remove selected in list"); - labelCoverageButtonsPane.add(removeFromCoverage, JideBoxLayout.FIX); - labelCoverageButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - - addCoverage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedLabel == null) return; - String labelId = selectedLabel.id; - if (labelId == null) labelId = WorldmapSegment.TEMP_LABEL_KEY; - - List currentCoverage = worldmap.labelledMaps.get(labelId); - if (currentCoverage == null) { - worldmap.labelledMaps.put(labelId, new ArrayList()); - currentCoverage = worldmap.labelledMaps.get(labelId); - } - for (int i = 0; i < msmListModel.getSize(); i++) { - if (msmListSelectionModel.isSelectedIndex(i)) { - if (!currentCoverage.contains(msmListModel.getElementAt(i).id)) { - currentCoverage.add(msmListModel.getElementAt(i).id); - } - } - } - mslmListModel.listChanged(); - repaintMap(); - } - }); - - replaceCoverage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedLabel == null) return; - String labelId = selectedLabel.id; - if (labelId == null) labelId = WorldmapSegment.TEMP_LABEL_KEY; - - List currentCoverage = worldmap.labelledMaps.get(labelId); - if (currentCoverage == null) { - worldmap.labelledMaps.put(labelId, new ArrayList()); - currentCoverage = worldmap.labelledMaps.get(labelId); - } else { - currentCoverage.clear(); - } - for (int i = 0; i < msmListModel.getSize(); i++) { - if (msmListSelectionModel.isSelectedIndex(i)) { - if (!currentCoverage.contains(msmListModel.getElementAt(i).id)) { - currentCoverage.add(msmListModel.getElementAt(i).id); - } - } - } - mslmListModel.listChanged(); - repaintMap(); - } - }); - - removeFromCoverage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedLabel == null) return; - String labelId = selectedLabel.id; - if (labelId == null) labelId = WorldmapSegment.TEMP_LABEL_KEY; - - List currentCoverage = worldmap.labelledMaps.get(labelId); - if (currentCoverage == null) return; - List toRemove = new ArrayList(); - for (int i = 0; i < mslmListModel.getSize(); i++) { - if (mslmListSelectionModel.isSelectedIndex(i)) { - if (currentCoverage.contains(mslmListModel.getElementAt(i).id)) { - toRemove.add(mslmListModel.getElementAt(i).id); - } - } - } - currentCoverage.removeAll(toRemove); - mslmListModel.listChanged(); - repaintMap(); - } - }); - - labelParametersPane.add(labelCoverageButtonsPane, JideBoxLayout.FIX); - setCurrentHighlightModel(mslmListModel); - - } - - public class MapSegmentMapsListModel implements ListenerListModel { + mapDeltaX -= mapDeltaX % WorldMapView.TILE_SIZE; + mapDeltaY -= mapDeltaY % WorldMapView.TILE_SIZE; - WorldmapSegment segment; - - public MapSegmentMapsListModel(WorldmapSegment segment) { - this.segment = segment; - } - - @Override - public int getSize() { - return segment.mapLocations.size(); - } + for (String s : mapView.getSelectedMapsIDs()) { + mapView.mapLocations.get(s).x = (worldmap.mapLocations.get(s).x * WorldMapView.TILE_SIZE) + mapDeltaX; + mapView.mapLocations.get(s).y = (worldmap.mapLocations.get(s).y * WorldMapView.TILE_SIZE) + mapDeltaY; + } - @Override - public TMXMap getElementAt(int index) { - return segment.getProject().getMap(((String)segment.mapLocations.keySet().toArray()[index])); - } + if (--skipRecompute <= 0) { + if (mapView.recomputeSize()) { + skipRecompute = skipRecomputeDefault; + } + } - public void listChanged() { - fireListChanged(); - } - - List listeners = new ArrayList(); - @Override - public List getListeners() { - return listeners; - } - } - - public class MapSegmentLabelMapsListModel implements ListenerListModel { - WorldmapSegment segment; - WorldmapSegment.NamedArea area; - - public MapSegmentLabelMapsListModel(WorldmapSegment segment, WorldmapSegment.NamedArea area) { - this.segment = segment; - this.area = area; - } - - @Override - public int getSize() { - if (area.id == null) return segment.labelledMaps.get(WorldmapSegment.TEMP_LABEL_KEY).size(); - return segment.labelledMaps.get(area.id).size(); - } + mapView.revalidate(); + mapView.repaint(); + } + } - @Override - public TMXMap getElementAt(int index) { - if (area.id == null) return segment.getProject().getMap(segment.labelledMaps.get(WorldmapSegment.TEMP_LABEL_KEY).get(index)); - return segment.getProject().getMap(segment.labelledMaps.get(area.id).get(index)); - } - public void listChanged() { - fireListChanged(); - } - - List listeners = new ArrayList(); + }; - @Override - public List getListeners() { - return listeners; - } - } - - public class MapSegmentLabelsListModel implements ListenerListModel { + mapView.addMouseListener(mouseListener); + mapView.addMouseMotionListener(mouseListener); - WorldmapSegment segment; - - public MapSegmentLabelsListModel(WorldmapSegment segment) { - this.segment = segment; - } - - @Override - public int getSize() { - return segment.labels.values().size(); - } + mapView.addMapClickListener(new WorldMapView.MapClickListener() { + @Override + public void mapClicked(MouseEvent e, TMXMap m) { + if (e.getClickCount() == 2) { + ATContentStudio.frame.openEditor(m); + } + } - @Override - public WorldmapSegment.NamedArea getElementAt(int index) { - return new ArrayList(segment.labels.values()).get(index); - } + @Override + public void mapChangeClicked(MouseEvent e, TMXMap m, TMXMap changeTarget) { + if (e.getClickCount() == 2) { + ATContentStudio.frame.openEditor(changeTarget); + } + } - public void listChanged() { - fireListChanged(); - } - - List listeners = new ArrayList(); + @Override + public void backgroundClicked(MouseEvent e) { + } + }); - @Override - public List getListeners() { - return listeners; - } - - } - - public static class MapCellRenderer extends DefaultListCellRenderer { + return pane; + } - private static final long serialVersionUID = 6819681566800482793L; - - public MapCellRenderer() { - super(); - } - - @SuppressWarnings("rawtypes") - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value == null) { - label.setText("None"); - } else { - label.setText(((GameDataElement)value).getDesc()); - if (((GameDataElement)value).getIcon() == null) { - Notification.addError("Unable to find icon for "+((GameDataElement)value).getDesc()); - } else { - label.setIcon(new ImageIcon(((GameDataElement)value).getIcon())); - } - } - return label; - } - - } - - public static class MapLabelCellRenderer extends DefaultListCellRenderer { + private void buildMapPropsPane(JPanel mapPropsPane, final WorldmapSegment worldmap) { + JideTabbedPane tabPane = new JideTabbedPane(JideTabbedPane.TOP); - private static final long serialVersionUID = 6819681566800482793L; + JPanel mapListPane = new JPanel(); + mapListPane.setLayout(new JideBoxLayout(mapListPane, JideBoxLayout.PAGE_AXIS)); + mapListPane.add(new JLabel("Maps shown here"), JideBoxLayout.FIX); + msmListModel = new MapSegmentMapsListModel(worldmap); + mapsShown = new JList(msmListModel); + mapsShown.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + msmListSelectionModel = mapsShown.getSelectionModel(); + mapsShown.setCellRenderer(new MapCellRenderer()); + new ListSearchable(mapsShown) { + @Override + protected String convertElementToString(Object object) { + return ((TMXMap) object).id; + } + }; + mapListPane.add(new JScrollPane(mapsShown), JideBoxLayout.VARY); + mapsShown.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { + ATContentStudio.frame.openEditor(mapsShown.getSelectedValue()); + ATContentStudio.frame.selectInTree(mapsShown.getSelectedValue()); + } + } + }); + mapsShown.addKeyListener(new KeyAdapter() { + @Override + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + ATContentStudio.frame.openEditor(mapsShown.getSelectedValue()); + ATContentStudio.frame.selectInTree(mapsShown.getSelectedValue()); + } + } + }); + mapsShown.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + setCurrentSelectionModel(msmListModel, msmListSelectionModel); + } + }); - - public MapLabelCellRenderer() { - super(); - } - - @SuppressWarnings("rawtypes") - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value == null) { - label.setText("None"); - } else { - WorldmapSegment.NamedArea area = (WorldmapSegment.NamedArea) value; - if (area.id != null) { - label.setText(area.name+" ("+area.id+")"); - label.setIcon(new ImageIcon(DefaultIcons.getLabelIcon())); - } else { - label.setText("Incomplete Label. Enter an ID."); - label.setIcon(new ImageIcon(DefaultIcons.getNullifyIcon())); - } - } - return label; - } - - } - public JPanel createButtonPane(final WorldmapSegment node) { - final JButton gdeIcon = new JButton(new ImageIcon(DefaultIcons.getUIMapImage())); - JPanel savePane = new JPanel(); - savePane.add(gdeIcon, JideBoxLayout.FIX); - savePane.setLayout(new JideBoxLayout(savePane, JideBoxLayout.LINE_AXIS, 6)); - if (node.writable) { - if (node.getDataType() == GameSource.Type.altered) { - savePane.add(message = new JLabel(ALTERED_MESSAGE), JideBoxLayout.FIX); - } else if (node.getDataType() == GameSource.Type.created) { - savePane.add(message = new JLabel(CREATED_MESSAGE), JideBoxLayout.FIX); - } - JButton save = new JButton(SAVE); - save.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (node.getParent() instanceof Worldmap) { - if (node.state != GameDataElement.State.saved) { - final List events = node.attemptSave(); - if (events == null) { - ATContentStudio.frame.nodeChanged(node); - } else { - new Thread() { - @Override - public void run() { - new SaveItemsWizard(events, node).setVisible(true); - } - }.start(); - } - } - } - } - }); - savePane.add(save, JideBoxLayout.FIX); - JButton delete = new JButton(DELETE); - if (node.getDataType() == GameSource.Type.altered) { - delete.setText(REVERT); - } - delete.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ATContentStudio.frame.closeEditor(node); - node.childrenRemoved(new ArrayList()); - if (node.getParent() instanceof Worldmap) { - ((Worldmap)node.getParent()).remove(node); - node.save(); - for (GameDataElement backlink : node.getBacklinks()) { - backlink.elementChanged(node, node.getProject().getWorldmapSegment(node.id)); - } - } - } - }); - savePane.add(delete, JideBoxLayout.FIX); - } else { - if (node.getProject().alteredContent.getWorldmapSegment(node.id) != null) { - savePane.add(message = new JLabel(ALTERED_EXISTS_MESSAGE), JideBoxLayout.FIX); - JButton makeWritable = new JButton("Go to altered"); - makeWritable.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (node.getProject().getWorldmapSegment(node.id) != node) { - ATContentStudio.frame.openEditor(node.getProject().getWorldmapSegment(node.id)); - ATContentStudio.frame.closeEditor(node); - ATContentStudio.frame.selectInTree(node.getProject().getWorldmapSegment(node.id)); - } - } - }); - savePane.add(makeWritable, JideBoxLayout.FIX); + tabPane.addTab("Map list", mapListPane); + + final JPanel labelEditPane = new JPanel(); + labelEditPane.setLayout(new JideBoxLayout(labelEditPane, JideBoxLayout.PAGE_AXIS)); + labelEditPane.add(new JLabel("Labels on the worldmap"), JideBoxLayout.FIX); + + mslListModel = new MapSegmentLabelsListModel(worldmap); + labelList = new JList(mslListModel); + labelList.setCellRenderer(new MapLabelCellRenderer()); + labelList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + labelEditPane.add(new JScrollPane(labelList), JideBoxLayout.FLEXIBLE); + + JPanel labelListButtonsPane = new JPanel(); + labelListButtonsPane.setLayout(new JideBoxLayout(labelListButtonsPane, JideBoxLayout.LINE_AXIS)); + final JButton createLabel = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); + labelListButtonsPane.add(createLabel, JideBoxLayout.FIX); + final JButton deleteLabel = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + labelListButtonsPane.add(deleteLabel, JideBoxLayout.FIX); + labelListButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + labelEditPane.add(labelListButtonsPane, JideBoxLayout.FIX); + + final JPanel labelParametersPane = new JPanel(); + labelEditPane.add(labelParametersPane, JideBoxLayout.FLEXIBLE); + + labelList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + selectedLabel = labelList.getSelectedValue(); + updateLabelParamsPane(labelParametersPane, worldmap); + labelEditPane.revalidate(); + labelEditPane.repaint(); + } + }); + + createLabel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + WorldmapSegment.NamedArea creation = new WorldmapSegment.NamedArea(null, null, null); + worldmap.labels.put(WorldmapSegment.TEMP_LABEL_KEY, creation); + worldmap.labelledMaps.put(WorldmapSegment.TEMP_LABEL_KEY, new ArrayList()); + mslListModel.listChanged(); + labelList.setSelectedValue(creation, true); + } + }); + + deleteLabel.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedLabel.id != null) { + worldmap.labelledMaps.remove(selectedLabel.id); + worldmap.labels.remove(selectedLabel.id); + } else { + worldmap.labelledMaps.remove(WorldmapSegment.TEMP_LABEL_KEY); + worldmap.labels.remove(WorldmapSegment.TEMP_LABEL_KEY); + } + labelList.clearSelection(); + mslListModel.listChanged(); + notifyModelModified(); + } + }); + + + tabPane.addTab("Labels", labelEditPane); + + mapPropsPane.setLayout(new BorderLayout()); + mapPropsPane.add(tabPane, BorderLayout.CENTER); + } + + private void updateLabelParamsPane(JPanel labelParametersPane, final WorldmapSegment worldmap) { + labelParametersPane.removeAll(); + if (selectedLabel == null) { + setCurrentHighlightModel(null); + return; + } + labelParametersPane.setLayout(new JideBoxLayout(labelParametersPane, JideBoxLayout.PAGE_AXIS)); + + labelIdField = addTextField(labelParametersPane, "Internal ID: ", selectedLabel.id, worldmap.writable, this); + labelNameField = addTranslatableTextField(labelParametersPane, "Name: ", selectedLabel.name, worldmap.writable, this); + labelTypeField = addTextField(labelParametersPane, "Type: ", selectedLabel.type, worldmap.writable, this); + + + labelParametersPane.add(new JLabel("Label covers the following maps"), JideBoxLayout.FIX); + + mslmListModel = new MapSegmentLabelMapsListModel(worldmap, selectedLabel); + final JList labelCoverageList = new JList(mslmListModel); + labelCoverageList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + mslmListSelectionModel = labelCoverageList.getSelectionModel(); + labelCoverageList.setCellRenderer(new MapCellRenderer()); + labelParametersPane.add(new JScrollPane(labelCoverageList), JideBoxLayout.VARY); + labelCoverageList.addListSelectionListener(new ListSelectionListener() { + @Override + public void valueChanged(ListSelectionEvent e) { + setCurrentHighlightModel(mslmListModel); + } + }); + + JPanel labelCoverageButtonsPane = new JPanel(); + labelCoverageButtonsPane.setLayout(new JideBoxLayout(labelCoverageButtonsPane, JideBoxLayout.LINE_AXIS)); + JButton addCoverage = new JButton("Add on-map selection"); + labelCoverageButtonsPane.add(addCoverage, JideBoxLayout.FIX); + JButton replaceCoverage = new JButton("Replace by on-map selection"); + labelCoverageButtonsPane.add(replaceCoverage, JideBoxLayout.FIX); + JButton removeFromCoverage = new JButton("Remove selected in list"); + labelCoverageButtonsPane.add(removeFromCoverage, JideBoxLayout.FIX); + labelCoverageButtonsPane.add(new JPanel(), JideBoxLayout.VARY); + + addCoverage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedLabel == null) return; + String labelId = selectedLabel.id; + if (labelId == null) labelId = WorldmapSegment.TEMP_LABEL_KEY; + + List currentCoverage = worldmap.labelledMaps.get(labelId); + if (currentCoverage == null) { + worldmap.labelledMaps.put(labelId, new ArrayList()); + currentCoverage = worldmap.labelledMaps.get(labelId); + } + for (int i = 0; i < msmListModel.getSize(); i++) { + if (msmListSelectionModel.isSelectedIndex(i)) { + if (!currentCoverage.contains(msmListModel.getElementAt(i).id)) { + currentCoverage.add(msmListModel.getElementAt(i).id); + } + } + } + mslmListModel.listChanged(); + repaintMap(); + } + }); + + replaceCoverage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedLabel == null) return; + String labelId = selectedLabel.id; + if (labelId == null) labelId = WorldmapSegment.TEMP_LABEL_KEY; + + List currentCoverage = worldmap.labelledMaps.get(labelId); + if (currentCoverage == null) { + worldmap.labelledMaps.put(labelId, new ArrayList()); + currentCoverage = worldmap.labelledMaps.get(labelId); + } else { + currentCoverage.clear(); + } + for (int i = 0; i < msmListModel.getSize(); i++) { + if (msmListSelectionModel.isSelectedIndex(i)) { + if (!currentCoverage.contains(msmListModel.getElementAt(i).id)) { + currentCoverage.add(msmListModel.getElementAt(i).id); + } + } + } + mslmListModel.listChanged(); + repaintMap(); + } + }); + + removeFromCoverage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (selectedLabel == null) return; + String labelId = selectedLabel.id; + if (labelId == null) labelId = WorldmapSegment.TEMP_LABEL_KEY; + + List currentCoverage = worldmap.labelledMaps.get(labelId); + if (currentCoverage == null) return; + List toRemove = new ArrayList(); + for (int i = 0; i < mslmListModel.getSize(); i++) { + if (mslmListSelectionModel.isSelectedIndex(i)) { + if (currentCoverage.contains(mslmListModel.getElementAt(i).id)) { + toRemove.add(mslmListModel.getElementAt(i).id); + } + } + } + currentCoverage.removeAll(toRemove); + mslmListModel.listChanged(); + repaintMap(); + } + }); + + labelParametersPane.add(labelCoverageButtonsPane, JideBoxLayout.FIX); + setCurrentHighlightModel(mslmListModel); + + } + + public class MapSegmentMapsListModel implements ListenerListModel { + + WorldmapSegment segment; + + public MapSegmentMapsListModel(WorldmapSegment segment) { + this.segment = segment; + } + + @Override + public int getSize() { + return segment.mapLocations.size(); + } + + @Override + public TMXMap getElementAt(int index) { + return segment.getProject().getMap(((String) segment.mapLocations.keySet().toArray()[index])); + } + + public void listChanged() { + fireListChanged(); + } + + List listeners = new ArrayList(); + + @Override + public List getListeners() { + return listeners; + } + } + + public class MapSegmentLabelMapsListModel implements ListenerListModel { + WorldmapSegment segment; + WorldmapSegment.NamedArea area; + + public MapSegmentLabelMapsListModel(WorldmapSegment segment, WorldmapSegment.NamedArea area) { + this.segment = segment; + this.area = area; + } + + @Override + public int getSize() { + if (area.id == null) return segment.labelledMaps.get(WorldmapSegment.TEMP_LABEL_KEY).size(); + return segment.labelledMaps.get(area.id).size(); + } + + @Override + public TMXMap getElementAt(int index) { + if (area.id == null) + return segment.getProject().getMap(segment.labelledMaps.get(WorldmapSegment.TEMP_LABEL_KEY).get(index)); + return segment.getProject().getMap(segment.labelledMaps.get(area.id).get(index)); + } + + public void listChanged() { + fireListChanged(); + } + + List listeners = new ArrayList(); + + @Override + public List getListeners() { + return listeners; + } + } + + public class MapSegmentLabelsListModel implements ListenerListModel { + + WorldmapSegment segment; + + public MapSegmentLabelsListModel(WorldmapSegment segment) { + this.segment = segment; + } + + @Override + public int getSize() { + return segment.labels.values().size(); + } + + @Override + public WorldmapSegment.NamedArea getElementAt(int index) { + return new ArrayList(segment.labels.values()).get(index); + } + + public void listChanged() { + fireListChanged(); + } + + List listeners = new ArrayList(); + + @Override + public List getListeners() { + return listeners; + } + + } + + public static class MapCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 6819681566800482793L; + + + public MapCellRenderer() { + super(); + } + + @SuppressWarnings("rawtypes") + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value == null) { + label.setText("None"); + } else { + label.setText(((GameDataElement) value).getDesc()); + if (((GameDataElement) value).getIcon() == null) { + Notification.addError("Unable to find icon for " + ((GameDataElement) value).getDesc()); + } else { + label.setIcon(new ImageIcon(((GameDataElement) value).getIcon())); + } + } + return label; + } + + } + + public static class MapLabelCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 6819681566800482793L; + + + public MapLabelCellRenderer() { + super(); + } + + @SuppressWarnings("rawtypes") + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value == null) { + label.setText("None"); + } else { + WorldmapSegment.NamedArea area = (WorldmapSegment.NamedArea) value; + if (area.id != null) { + label.setText(area.name + " (" + area.id + ")"); + label.setIcon(new ImageIcon(DefaultIcons.getLabelIcon())); + } else { + label.setText("Incomplete Label. Enter an ID."); + label.setIcon(new ImageIcon(DefaultIcons.getNullifyIcon())); + } + } + return label; + } + + } + + public JPanel createButtonPane(final WorldmapSegment node) { + final JButton gdeIcon = new JButton(new ImageIcon(DefaultIcons.getUIMapImage())); + JPanel savePane = new JPanel(); + savePane.add(gdeIcon, JideBoxLayout.FIX); + savePane.setLayout(new JideBoxLayout(savePane, JideBoxLayout.LINE_AXIS, 6)); + if (node.writable) { + if (node.getDataType() == GameSource.Type.altered) { + savePane.add(message = new JLabel(ALTERED_MESSAGE), JideBoxLayout.FIX); + } else if (node.getDataType() == GameSource.Type.created) { + savePane.add(message = new JLabel(CREATED_MESSAGE), JideBoxLayout.FIX); + } + JButton save = new JButton(SAVE); + save.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (node.getParent() instanceof Worldmap) { + if (node.state != GameDataElement.State.saved) { + final List events = node.attemptSave(); + if (events == null) { + ATContentStudio.frame.nodeChanged(node); + } else { + new Thread() { + @Override + public void run() { + new SaveItemsWizard(events, node).setVisible(true); + } + }.start(); + } + } + } + } + }); + savePane.add(save, JideBoxLayout.FIX); + JButton delete = new JButton(DELETE); + if (node.getDataType() == GameSource.Type.altered) { + delete.setText(REVERT); + } + delete.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ATContentStudio.frame.closeEditor(node); + node.childrenRemoved(new ArrayList()); + if (node.getParent() instanceof Worldmap) { + ((Worldmap) node.getParent()).remove(node); + node.save(); + for (GameDataElement backlink : node.getBacklinks()) { + backlink.elementChanged(node, node.getProject().getWorldmapSegment(node.id)); + } + } + } + }); + savePane.add(delete, JideBoxLayout.FIX); + } else { + if (node.getProject().alteredContent.getWorldmapSegment(node.id) != null) { + savePane.add(message = new JLabel(ALTERED_EXISTS_MESSAGE), JideBoxLayout.FIX); + JButton makeWritable = new JButton("Go to altered"); + makeWritable.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (node.getProject().getWorldmapSegment(node.id) != node) { + ATContentStudio.frame.openEditor(node.getProject().getWorldmapSegment(node.id)); + ATContentStudio.frame.closeEditor(node); + ATContentStudio.frame.selectInTree(node.getProject().getWorldmapSegment(node.id)); + } + } + }); + savePane.add(makeWritable, JideBoxLayout.FIX); + + } else { + savePane.add(message = new JLabel(READ_ONLY_MESSAGE), JideBoxLayout.FIX); + JButton makeWritable = new JButton("Alter"); + makeWritable.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (node.getProject().getWorldmapSegment(node.id) == node) { + node.getProject().makeWritable(node); + } + if (node.getProject().getWorldmapSegment(node.id) != node) { + ATContentStudio.frame.openEditor(node.getProject().getWorldmapSegment(node.id)); + ATContentStudio.frame.closeEditor(node); + ATContentStudio.frame.selectInTree(node.getProject().getWorldmapSegment(node.id)); + } + updateMessage(); + } + }); + savePane.add(makeWritable, JideBoxLayout.FIX); + } + } + JButton prev = new JButton(new ImageIcon(DefaultIcons.getArrowLeftIcon())); + JButton next = new JButton(new ImageIcon(DefaultIcons.getArrowRightIcon())); + savePane.add(prev, JideBoxLayout.FIX); + savePane.add(next, JideBoxLayout.FIX); + if (node.getParent().getIndex(node) == 0) { + prev.setEnabled(false); + } + if (node.getParent().getIndex(node) == node.getParent().getChildCount() - 1) { + next.setEnabled(false); + } + prev.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ProjectTreeNode prevNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) - 1); + if (prevNode != null && prevNode instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) prevNode); + } + } + }); + next.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + ProjectTreeNode nextNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) + 1); + if (nextNode != null && nextNode instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) nextNode); + } + } + }); + final JButton bookmark = new JButton(new ImageIcon(node.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); + savePane.add(bookmark, JideBoxLayout.FIX); + bookmark.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + if (node.bookmark == null) { + node.getProject().bookmark(node); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); + } else { + node.bookmark.delete(); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); + } + } + }); + //Placeholder. Fills the eventual remaining space. + savePane.add(new JPanel(), JideBoxLayout.VARY); + return savePane; + } + + public void updateMessage() { + + //TODO make this a full update of the button panel. + WorldmapSegment node = (WorldmapSegment) target; + if (node.writable) { + if (node.getDataType() == GameSource.Type.altered) { + message.setText(ALTERED_MESSAGE); + } else if (node.getDataType() == GameSource.Type.created) { + message.setText(CREATED_MESSAGE); + } + } else if (node.getProject().alteredContent.getWorldmapSegment(node.id) != null) { + message.setText(ALTERED_EXISTS_MESSAGE); + } else { + message.setText(READ_ONLY_MESSAGE); + } + message.revalidate(); + message.repaint(); + } + + public void pushToModel() { + mapView.pushToModel(); + msmListModel.listChanged(); + notifyModelModified(); + updateXmlViewText(((WorldmapSegment) target).toXml()); + } + + public void notifyModelModified() { + target.state = GameDataElement.State.modified; + target.childrenChanged(new ArrayList()); + } + + ListSelectionListener activeSelectionListSelectionListener = new ListSelectionListener() { + public void valueChanged(ListSelectionEvent e) { + repaintMap(); + } + + ; + }; + + private void setCurrentSelectionModel(ListModel listModel, ListSelectionModel listSelectionModel) { + if (currentSelectionSelectionModel != null) { + currentSelectionSelectionModel.removeListSelectionListener(activeSelectionListSelectionListener); + } + currentSelectionListModel = listModel; + currentSelectionSelectionModel = listSelectionModel; + mapView.selectedListModel = listModel; + mapView.selectedSelectionModel = listSelectionModel; + currentSelectionSelectionModel.addListSelectionListener(activeSelectionListSelectionListener); + repaintMap(); + } + + private void setCurrentHighlightModel(ListModel listModel) { + mapView.highlightedListModel = listModel; + repaintMap(); + } + + + public void clearSelection() { + currentSelectionSelectionModel.clearSelection(); + } + + public void addToSelection(String mapId) { + if (mapId == null) return; + int index = -1; + for (int i = 0; i < currentSelectionListModel.getSize(); i++) { + if (currentSelectionListModel.getElementAt(i).id.equals(mapId)) { + index = i; + break; + } + } + currentSelectionSelectionModel.addSelectionInterval(index, index); + } + + public void removeFromSelection(String mapId) { + if (mapId == null) return; + int index = -1; + for (int i = 0; i < currentSelectionListModel.getSize(); i++) { + if (currentSelectionListModel.getElementAt(i).id.equals(mapId)) { + index = i; + break; + } + } + currentSelectionSelectionModel.removeSelectionInterval(index, index); + } + + public void repaintMap() { + mapView.revalidate(); + mapView.repaint(); + } + + @Override + public void valueChanged(JComponent source, Object value) { + WorldmapSegment worldmap = (WorldmapSegment) target; + boolean changed = false; + if (source == labelIdField) { + List coverage; + if (selectedLabel.id != null) { + coverage = worldmap.labelledMaps.get(selectedLabel.id); + worldmap.labelledMaps.remove(selectedLabel.id); + worldmap.labels.remove(selectedLabel.id); + } else { + coverage = worldmap.labelledMaps.get(WorldmapSegment.TEMP_LABEL_KEY); + worldmap.labels.remove(WorldmapSegment.TEMP_LABEL_KEY); + } + selectedLabel.id = (String) value; + if (value != null) { + worldmap.labelledMaps.put(selectedLabel.id, coverage); + worldmap.labels.put(selectedLabel.id, selectedLabel); + } + mslListModel.listChanged(); + changed = true; + } else if (source == labelNameField) { + selectedLabel.name = (String) value; + mslListModel.listChanged(); + changed = true; + repaintMap(); + } else if (source == labelTypeField) { + selectedLabel.type = (String) value; + changed = true; + } + + if (changed) { + notifyModelModified(); + updateXmlViewText(worldmap.toXml()); + } + } - } else { - savePane.add(message = new JLabel(READ_ONLY_MESSAGE), JideBoxLayout.FIX); - JButton makeWritable = new JButton("Alter"); - makeWritable.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (node.getProject().getWorldmapSegment(node.id) == node) { - node.getProject().makeWritable(node); - } - if (node.getProject().getWorldmapSegment(node.id) != node) { - ATContentStudio.frame.openEditor(node.getProject().getWorldmapSegment(node.id)); - ATContentStudio.frame.closeEditor(node); - ATContentStudio.frame.selectInTree(node.getProject().getWorldmapSegment(node.id)); - } - updateMessage(); - } - }); - savePane.add(makeWritable, JideBoxLayout.FIX); - } - } - JButton prev = new JButton(new ImageIcon(DefaultIcons.getArrowLeftIcon())); - JButton next = new JButton(new ImageIcon(DefaultIcons.getArrowRightIcon())); - savePane.add(prev, JideBoxLayout.FIX); - savePane.add(next, JideBoxLayout.FIX); - if (node.getParent().getIndex(node) == 0) { - prev.setEnabled(false); - } - if (node.getParent().getIndex(node) == node.getParent().getChildCount() - 1) { - next.setEnabled(false); - } - prev.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ProjectTreeNode prevNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) - 1); - if (prevNode != null && prevNode instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement) prevNode); - } - } - }); - next.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - ProjectTreeNode nextNode = (ProjectTreeNode) node.getParent().getChildAt(node.getParent().getIndex(node) + 1); - if (nextNode != null && nextNode instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement) nextNode); - } - } - }); - final JButton bookmark = new JButton(new ImageIcon(node.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); - savePane.add(bookmark, JideBoxLayout.FIX); - bookmark.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - if (node.bookmark == null) { - node.getProject().bookmark(node); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); - } else { - node.bookmark.delete(); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); - } - } - }); - //Placeholder. Fills the eventual remaining space. - savePane.add(new JPanel(), JideBoxLayout.VARY); - return savePane; - } - - public void updateMessage() { - - //TODO make this a full update of the button panel. - WorldmapSegment node = (WorldmapSegment) target; - if (node.writable) { - if (node.getDataType() == GameSource.Type.altered) { - message.setText(ALTERED_MESSAGE); - } else if (node.getDataType() == GameSource.Type.created) { - message.setText(CREATED_MESSAGE); - } - } else if (node.getProject().alteredContent.getWorldmapSegment(node.id) != null) { - message.setText(ALTERED_EXISTS_MESSAGE); - } else { - message.setText(READ_ONLY_MESSAGE); - } - message.revalidate(); - message.repaint(); - } - - public void pushToModel() { - mapView.pushToModel(); - msmListModel.listChanged(); - notifyModelModified(); - updateXmlViewText(((WorldmapSegment)target).toXml()); - } - - public void notifyModelModified() { - target.state = GameDataElement.State.modified; - target.childrenChanged(new ArrayList()); - } - - ListSelectionListener activeSelectionListSelectionListener = new ListSelectionListener() { - public void valueChanged(ListSelectionEvent e) { - repaintMap(); - }; - }; - - private void setCurrentSelectionModel(ListModel listModel, ListSelectionModel listSelectionModel) { - if (currentSelectionSelectionModel != null) { - currentSelectionSelectionModel.removeListSelectionListener(activeSelectionListSelectionListener); - } - currentSelectionListModel = listModel; - currentSelectionSelectionModel = listSelectionModel; - mapView.selectedListModel = listModel; - mapView.selectedSelectionModel = listSelectionModel; - currentSelectionSelectionModel.addListSelectionListener(activeSelectionListSelectionListener); - repaintMap(); - } - - private void setCurrentHighlightModel(ListModel listModel) { - mapView.highlightedListModel = listModel; - repaintMap(); - } - - - public void clearSelection() { - currentSelectionSelectionModel.clearSelection(); - } - - public void addToSelection(String mapId) { - if (mapId == null) return; - int index = -1; - for (int i = 0; i < currentSelectionListModel.getSize(); i++) { - if (currentSelectionListModel.getElementAt(i).id.equals(mapId)) { - index = i; - break; - } - } - currentSelectionSelectionModel.addSelectionInterval(index, index); - } - - public void removeFromSelection(String mapId) { - if (mapId == null) return; - int index = -1; - for (int i = 0; i < currentSelectionListModel.getSize(); i++) { - if (currentSelectionListModel.getElementAt(i).id.equals(mapId)) { - index = i; - break; - } - } - currentSelectionSelectionModel.removeSelectionInterval(index, index); - } - - public void repaintMap() { - mapView.revalidate(); - mapView.repaint(); - } - - @Override - public void valueChanged(JComponent source, Object value) { - WorldmapSegment worldmap = (WorldmapSegment)target; - boolean changed = false; - if (source == labelIdField) { - List coverage; - if (selectedLabel.id != null) { - coverage = worldmap.labelledMaps.get(selectedLabel.id); - worldmap.labelledMaps.remove(selectedLabel.id); - worldmap.labels.remove(selectedLabel.id); - } else { - coverage = worldmap.labelledMaps.get(WorldmapSegment.TEMP_LABEL_KEY); - worldmap.labels.remove(WorldmapSegment.TEMP_LABEL_KEY); - } - selectedLabel.id = (String) value; - if (value != null) { - worldmap.labelledMaps.put(selectedLabel.id, coverage); - worldmap.labels.put(selectedLabel.id, selectedLabel); - } - mslListModel.listChanged(); - changed = true; - } else if (source == labelNameField) { - selectedLabel.name = (String) value; - mslListModel.listChanged(); - changed = true; - repaintMap(); - } else if (source == labelTypeField) { - selectedLabel.type = (String) value; - changed = true; - } - - if (changed) { - notifyModelModified(); - updateXmlViewText(worldmap.toXml()); - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapView.java b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapView.java index 796710a..ff5fc8c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapView.java @@ -1,73 +1,47 @@ package com.gpl.rpg.atcontentstudio.ui.map; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.Stroke; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.maps.*; +import tiled.view.MapRenderer; +import tiled.view.OrthogonalRenderer; + +import javax.swing.*; +import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.font.FontRenderContext; import java.awt.font.GlyphVector; import java.awt.geom.Rectangle2D; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; +import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; -import javax.swing.JComponent; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.Scrollable; -import javax.swing.ToolTipManager; - -import tiled.view.MapRenderer; -import tiled.view.OrthogonalRenderer; - -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.maps.MapChange; -import com.gpl.rpg.atcontentstudio.model.maps.MapObject; -import com.gpl.rpg.atcontentstudio.model.maps.MapObjectGroup; -import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; -import com.gpl.rpg.atcontentstudio.model.maps.WorldmapSegment; - public class WorldMapView extends JComponent implements Scrollable { - private static final long serialVersionUID = -4111374378777093799L; - - public static final int TILE_SIZE = 32; - public static final int MIN_ZOOM = 5; - public static final int MAX_ZOOM = 250; - public static final int INC_ZOOM = 5; - public static final float ZOOM_RATIO = 0.01f; - - WorldmapSegment worldmap; - Project proj; - - - public Map mapLocations = new LinkedHashMap(); + private static final long serialVersionUID = -4111374378777093799L; + + public static final int TILE_SIZE = 32; + public static final int MIN_ZOOM = 5; + public static final int MAX_ZOOM = 250; + public static final int INC_ZOOM = 5; + public static final float ZOOM_RATIO = 0.01f; + + WorldmapSegment worldmap; + Project proj; + + + public Map mapLocations = new LinkedHashMap(); + + public ListSelectionModel selectedSelectionModel = null; + public ListModel selectedListModel = null; + + public ListModel highlightedListModel = null; + + public float zoomLevel = 0.1f; + int sizeX = 0, sizeY = 0; + int offsetX = 0, offsetY = 0; - public ListSelectionModel selectedSelectionModel = null; - public ListModel selectedListModel = null; - - public ListModel highlightedListModel = null; - - public float zoomLevel = 0.1f; - int sizeX = 0, sizeY = 0; - int offsetX = 0, offsetY = 0; - - static final Color selectOutlineColor = new Color(255, 0, 0); static final Stroke selectOutlineStroke = new BasicStroke(4f); static final Color highlightOutlineColor = Color.CYAN; @@ -75,304 +49,306 @@ public class WorldMapView extends JComponent implements Scrollable { static final Color mapIdLabelOutlineColor = Color.BLACK; static final Stroke thinLabelOutlineStroke = new BasicStroke(1.5f); static final Stroke labelOutlineStroke = new BasicStroke(3f); - - public WorldMapView(WorldmapSegment worldmap) { - this.worldmap = worldmap; - this.proj = worldmap.getProject(); - updateFromModel(); - - addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - String selectedMap = null; + + public WorldMapView(WorldmapSegment worldmap) { + this.worldmap = worldmap; + this.proj = worldmap.getProject(); + updateFromModel(); + + addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + String selectedMap = null; // boolean update = false; - int x = (int) (e.getX() / zoomLevel); - int y = (int) (e.getY() / zoomLevel); - for (String s : mapLocations.keySet()) { - if (mapLocations.get(s).contains(x, y)) { - selectedMap = s; - break; - } - } - if (selectedMap != null) { - x = x - mapLocations.get(selectedMap).x; - y = y - mapLocations.get(selectedMap).y; - //Look for a mapchange there - TMXMap map = proj.getMap(selectedMap); - - boolean mapchangeFound = false; - for (MapObjectGroup group : map.groups) { - for (MapObject obj : group.mapObjects) { - if (obj instanceof MapChange) { - if (x >= obj.x && x < obj.x + obj.w && y >= obj.y && y < obj.y + obj.h) { - String mapId = ((MapChange)obj).map != null ? ((MapChange)obj).map.id : ((MapChange)obj).map_id; - mapChangeClicked(e, proj.getMap(selectedMap), proj.getMap(mapId)); - mapchangeFound = true; - } - } - } - } - - if (!mapchangeFound) { - mapClicked(e, WorldMapView.this.worldmap.getProject().getMap(selectedMap)); - } - } else { - backgroundClicked(e); - } - } - }); - - addMouseMotionListener(new MouseAdapter() { - @Override - public void mouseMoved(MouseEvent e) { - String selectedMap = null; - int x = (int) (e.getX() / zoomLevel); - int y = (int) (e.getY() / zoomLevel); - for (String s : mapLocations.keySet()) { - if (mapLocations.get(s).contains(x, y)) { - selectedMap = s; - break; - } - } - if (selectedMap != null) { - //Reuse x,y to indicate to tile-within-the-map coordinates. - x = x - mapLocations.get(selectedMap).x; - y = y - mapLocations.get(selectedMap).y; - //Look for a mapchange there - TMXMap map = proj.getMap(selectedMap); - - boolean mapchangeFound = false; - for (MapObjectGroup group : map.groups) { - for (MapObject obj : group.mapObjects) { - if (obj instanceof MapChange) { - if (x >= obj.x && x < obj.x + obj.w && y >= obj.y && y < obj.y + obj.h) { - String mapId = ((MapChange)obj).map != null ? ((MapChange)obj).map.id : ((MapChange)obj).map_id; - setToolTipText(selectedMap+"->"+mapId); - mapchangeFound = true; - } - } - } - } - - if (!mapchangeFound) { - setToolTipText(selectedMap); - } - ToolTipManager.sharedInstance().registerComponent(WorldMapView.this); - ToolTipManager.sharedInstance().setEnabled(true); - } else { - ToolTipManager.sharedInstance().setEnabled(false); - ToolTipManager.sharedInstance().unregisterComponent(WorldMapView.this); - setToolTipText(null); - } - } - }); - } - - @Override - public Point getToolTipLocation(MouseEvent event) { - return event.getPoint(); - } - - private void paintOnGraphics(Graphics2D g2) { - g2.setPaint(new Color(100, 100, 100)); + int x = (int) (e.getX() / zoomLevel); + int y = (int) (e.getY() / zoomLevel); + for (String s : mapLocations.keySet()) { + if (mapLocations.get(s).contains(x, y)) { + selectedMap = s; + break; + } + } + if (selectedMap != null) { + x = x - mapLocations.get(selectedMap).x; + y = y - mapLocations.get(selectedMap).y; + //Look for a mapchange there + TMXMap map = proj.getMap(selectedMap); + + boolean mapchangeFound = false; + for (MapObjectGroup group : map.groups) { + for (MapObject obj : group.mapObjects) { + if (obj instanceof MapChange) { + if (x >= obj.x && x < obj.x + obj.w && y >= obj.y && y < obj.y + obj.h) { + String mapId = ((MapChange) obj).map != null ? ((MapChange) obj).map.id : ((MapChange) obj).map_id; + mapChangeClicked(e, proj.getMap(selectedMap), proj.getMap(mapId)); + mapchangeFound = true; + } + } + } + } + + if (!mapchangeFound) { + mapClicked(e, WorldMapView.this.worldmap.getProject().getMap(selectedMap)); + } + } else { + backgroundClicked(e); + } + } + }); + + addMouseMotionListener(new MouseAdapter() { + @Override + public void mouseMoved(MouseEvent e) { + String selectedMap = null; + int x = (int) (e.getX() / zoomLevel); + int y = (int) (e.getY() / zoomLevel); + for (String s : mapLocations.keySet()) { + if (mapLocations.get(s).contains(x, y)) { + selectedMap = s; + break; + } + } + if (selectedMap != null) { + //Reuse x,y to indicate to tile-within-the-map coordinates. + x = x - mapLocations.get(selectedMap).x; + y = y - mapLocations.get(selectedMap).y; + //Look for a mapchange there + TMXMap map = proj.getMap(selectedMap); + + boolean mapchangeFound = false; + for (MapObjectGroup group : map.groups) { + for (MapObject obj : group.mapObjects) { + if (obj instanceof MapChange) { + if (x >= obj.x && x < obj.x + obj.w && y >= obj.y && y < obj.y + obj.h) { + String mapId = ((MapChange) obj).map != null ? ((MapChange) obj).map.id : ((MapChange) obj).map_id; + setToolTipText(selectedMap + "->" + mapId); + mapchangeFound = true; + } + } + } + } + + if (!mapchangeFound) { + setToolTipText(selectedMap); + } + ToolTipManager.sharedInstance().registerComponent(WorldMapView.this); + ToolTipManager.sharedInstance().setEnabled(true); + } else { + ToolTipManager.sharedInstance().setEnabled(false); + ToolTipManager.sharedInstance().unregisterComponent(WorldMapView.this); + setToolTipText(null); + } + } + }); + } + + @Override + public Point getToolTipLocation(MouseEvent event) { + return event.getPoint(); + } + + private void paintOnGraphics(Graphics2D g2) { + g2.setPaint(new Color(100, 100, 100)); g2.fillRect(0, 0, sizeX, sizeY); - + g2.setPaint(selectOutlineColor); g2.setStroke(selectOutlineStroke); - + Font areaNameFont = g2.getFont(); areaNameFont = areaNameFont.deriveFont(70f).deriveFont(Font.BOLD); - + Font mapIdFont = g2.getFont(); mapIdFont = mapIdFont.deriveFont(50f).deriveFont(Font.BOLD); g2.setFont(mapIdFont); FontMetrics mifm = g2.getFontMetrics(); int mapIdLabelHeight = mifm.getHeight(); - + for (String s : new HashSet(mapLocations.keySet())) { - int x = mapLocations.get(s).x; - int y = mapLocations.get(s).y; - - g2.translate(x, y); - - - TMXMap map = proj.getMap(s); - if (map == null) continue; - MapRenderer renderer = new OrthogonalRenderer(map.tmxMap); - - // Draw each tile map layer - for (tiled.core.MapLayer layer : ((TMXMap)map).tmxMap) { - if (layer instanceof tiled.core.TileLayer && layer.isVisible()) { - if (layer.getName().equalsIgnoreCase("walkable")) continue; - renderer.paintTileLayer(g2, (tiled.core.TileLayer) layer); - } else if (layer instanceof tiled.core.ObjectGroup) { - paintObjectGroup(g2, map, (tiled.core.ObjectGroup) layer); - } - } - if (map.colorFilter != null) { - Shape oldClip = g2.getClip(); - g2.setClip(0, 0, map.tmxMap.getWidth() * TILE_SIZE, map.tmxMap.getHeight() * TILE_SIZE); - MapColorFilters.applyColorfilter(map.colorFilter, g2); - g2.setClip(oldClip); - } - - g2.translate(-x, -y); - + int x = mapLocations.get(s).x; + int y = mapLocations.get(s).y; + + g2.translate(x, y); + + + TMXMap map = proj.getMap(s); + if (map == null) continue; + MapRenderer renderer = new OrthogonalRenderer(map.tmxMap); + + // Draw each tile map layer + for (tiled.core.MapLayer layer : ((TMXMap) map).tmxMap) { + if (layer instanceof tiled.core.TileLayer && layer.isVisible()) { + if (layer.getName().equalsIgnoreCase("walkable")) continue; + renderer.paintTileLayer(g2, (tiled.core.TileLayer) layer); + } else if (layer instanceof tiled.core.ObjectGroup) { + paintObjectGroup(g2, map, (tiled.core.ObjectGroup) layer); + } + } + if (map.colorFilter != null) { + Shape oldClip = g2.getClip(); + g2.setClip(0, 0, map.tmxMap.getWidth() * TILE_SIZE, map.tmxMap.getHeight() * TILE_SIZE); + MapColorFilters.applyColorfilter(map.colorFilter, g2); + g2.setClip(oldClip); + } + + g2.translate(-x, -y); + } - + if (highlightedListModel != null) { - outlineFromListModel(g2, highlightedListModel, null, highlightOutlineColor, highlightOutlineStroke, mapIdFont, mapIdLabelHeight); + outlineFromListModel(g2, highlightedListModel, null, highlightOutlineColor, highlightOutlineStroke, mapIdFont, mapIdLabelHeight); } - + if (selectedListModel != null && selectedSelectionModel != null) { - outlineFromListModel(g2, selectedListModel, selectedSelectionModel, selectOutlineColor, selectOutlineStroke, mapIdFont, mapIdLabelHeight); + outlineFromListModel(g2, selectedListModel, selectedSelectionModel, selectOutlineColor, selectOutlineStroke, mapIdFont, mapIdLabelHeight); } - - + + g2.setStroke(labelOutlineStroke); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setFont(areaNameFont); FontMetrics fm = g2.getFontMetrics(); FontRenderContext frc = g2.getFontRenderContext(); - + for (String s : worldmap.labels.keySet()) { - String label = worldmap.labels.get(s).name; - if (label != null) { - Rectangle areaCovered = new Rectangle(0, 0, -1, -1); - for (String map : worldmap.labelledMaps.get(s)) { - areaCovered.add(mapLocations.get(map)); - } + String label = worldmap.labels.get(s).name; + if (label != null) { + Rectangle areaCovered = new Rectangle(0, 0, -1, -1); + for (String map : worldmap.labelledMaps.get(s)) { + areaCovered.add(mapLocations.get(map)); + } - Rectangle2D stringBounds = fm.getStringBounds(label, g2); - GlyphVector gv = areaNameFont.createGlyphVector(frc, label); - g2.setColor(Color.WHITE); - g2.fill(gv.getOutline((int)(areaCovered.getCenterX() - stringBounds.getCenterX()), (int)(areaCovered.getCenterY() - stringBounds.getCenterY()))); - g2.setColor(Color.BLACK); - g2.draw(gv.getOutline((int)(areaCovered.getCenterX() - stringBounds.getCenterX()), (int)(areaCovered.getCenterY() - stringBounds.getCenterY()))); - } + Rectangle2D stringBounds = fm.getStringBounds(label, g2); + GlyphVector gv = areaNameFont.createGlyphVector(frc, label); + g2.setColor(Color.WHITE); + g2.fill(gv.getOutline((int) (areaCovered.getCenterX() - stringBounds.getCenterX()), (int) (areaCovered.getCenterY() - stringBounds.getCenterY()))); + g2.setColor(Color.BLACK); + g2.draw(gv.getOutline((int) (areaCovered.getCenterX() - stringBounds.getCenterX()), (int) (areaCovered.getCenterY() - stringBounds.getCenterY()))); + } } - } - - private void paintObjectGroup(Graphics2D g2d, TMXMap map, tiled.core.ObjectGroup layer) { - for (MapObjectGroup group : map.groups) { - if (group.tmxGroup == layer) { - for (MapObject object : group.mapObjects) { - if (object instanceof MapChange) { -// Only show mapchange areas pointing to maps not shown in this worldmap - if (((MapChange)object).map != null && !mapLocations.containsKey(((MapChange)object).map.id)) { - drawObject(object, g2d, new Color(20, 20, 190)); - } - } - } - break; - } - } - } - - private void drawObject(MapObject object, Graphics2D g2d, Color color) { - g2d.setPaint(color); - g2d.drawRect(object.x+1, object.y+1, object.w-3, object.h-3); - g2d.drawRect(object.x+2, object.y+2, object.w-5, object.h-5); - g2d.setPaint(color.darker().darker()); - g2d.drawLine(object.x, object.y + object.h - 1, object.x + object.w - 1, object.y + object.h - 1); - g2d.drawLine(object.x + object.w - 1, object.y, object.x + object.w - 1, object.y + object.h - 1); - g2d.drawLine(object.x + 3, object.y + 3, object.x + object.w - 4, object.y + 3); - g2d.drawLine(object.x + 3, object.y + 3, object.x + 3, object.y + object.h - 4); - g2d.setPaint(color.brighter().brighter().brighter()); - g2d.drawLine(object.x, object.y, object.x + object.w - 1, object.y); - g2d.drawLine(object.x, object.y, object.x, object.y + object.h - 1); - g2d.drawLine(object.x + 3, object.y + object.h - 4, object.x + object.w - 4, object.y + object.h - 4); - g2d.drawLine(object.x + object.w - 4, object.y + 3, object.x + object.w - 4, object.y + object.h - 4); - Image img = object.getIcon(); - g2d.setColor(new Color(255, 255, 255, 120)); - g2d.fillRect(object.x + 2, object.y + 2, img.getWidth(null), img.getHeight(null)); - g2d.drawImage(object.getIcon(), object.x + 2, object.y + 2, null); } - - private void outlineFromListModel(Graphics2D g2, ListModel listModel, ListSelectionModel selectionModel, Color outlineColor, Stroke outlineStroke, Font mapIdFont, int mapIdLabelHeight) { - for (int i =0; i listModel, ListSelectionModel selectionModel, Color outlineColor, Stroke outlineStroke, Font mapIdFont, int mapIdLabelHeight) { + for (int i = 0; i < listModel.getSize(); i++) { + //No selection model ? We want to highlight the whole list. + if (selectionModel == null || selectionModel.isSelectedIndex(i)) { + TMXMap map = listModel.getElementAt(i); + int x = mapLocations.get(map.id).x; + int y = mapLocations.get(map.id).y; + + g2.translate(x, y); + + GlyphVector gv = mapIdFont.createGlyphVector(g2.getFontRenderContext(), map.id); + g2.setStroke(outlineStroke); + g2.setColor(outlineColor); + g2.drawRect(0, 0, map.tmxMap.getWidth() * TILE_SIZE, map.tmxMap.getHeight() * TILE_SIZE); + + g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g2.setStroke(thinLabelOutlineStroke); + g2.fill(gv.getOutline(8, 8 + mapIdLabelHeight)); + g2.setColor(mapIdLabelOutlineColor); + g2.draw(gv.getOutline(8, 8 + mapIdLabelHeight)); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); - + g2.translate(-x, -y); - } + } } - } - - public List getSelectedMapsIDs() { - List result = new ArrayList(); - for (int i =0; i getSelectedMapsIDs() { + List result = new ArrayList(); + for (int i = 0; i < selectedListModel.getSize(); i++) { + if (selectedSelectionModel.isSelectedIndex(i)) { + TMXMap map = selectedListModel.getElementAt(i); + result.add(map.id); + } + } + return result; + } + + @Override + protected void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D) g.create(); + try { + g2.scale(zoomLevel, zoomLevel); // g2.drawImage(img, 0, 0, null); - paintOnGraphics(g2); + paintOnGraphics(g2); - } finally { - g2.dispose(); - } - - } - - - public interface MapClickListener { - public void mapClicked(MouseEvent e, TMXMap m); - public void mapChangeClicked(MouseEvent e, TMXMap m, TMXMap changeTarget); - public void backgroundClicked(MouseEvent e); - } + } finally { + g2.dispose(); + } + + } + + + public interface MapClickListener { + public void mapClicked(MouseEvent e, TMXMap m); + + public void mapChangeClicked(MouseEvent e, TMXMap m, TMXMap changeTarget); + + public void backgroundClicked(MouseEvent e); + } + + private List listeners = new CopyOnWriteArrayList(); + + public void addMapClickListener(MapClickListener l) { + listeners.add(l); + } + + public void removeMapClickListener(MapClickListener l) { + listeners.remove(l); + } + + private void mapClicked(MouseEvent e, TMXMap m) { + for (MapClickListener l : listeners) l.mapClicked(e, m); + } + + private void mapChangeClicked(MouseEvent e, TMXMap m, TMXMap changeTarget) { + for (MapClickListener l : listeners) l.mapChangeClicked(e, m, changeTarget); + } + + private void backgroundClicked(MouseEvent e) { + for (MapClickListener l : listeners) l.backgroundClicked(e); + } - private List listeners = new CopyOnWriteArrayList(); - - public void addMapClickListener(MapClickListener l) { - listeners.add(l); - } - - public void removeMapClickListener(MapClickListener l) { - listeners.remove(l); - } - - private void mapClicked(MouseEvent e, TMXMap m) { - for (MapClickListener l : listeners) l.mapClicked(e, m); - } - - private void mapChangeClicked(MouseEvent e, TMXMap m, TMXMap changeTarget) { - for (MapClickListener l : listeners) l.mapChangeClicked(e, m, changeTarget); - } - - private void backgroundClicked(MouseEvent e) { - for (MapClickListener l : listeners) l.backgroundClicked(e); - } - // private boolean paintObjectGroup(Graphics2D g2d, TMXMap map, tiled.core.ObjectGroup layer) { // boolean paintSelected = false; // for (MapObjectGroup group : map.groups) { @@ -406,121 +382,120 @@ public class WorldMapView extends JComponent implements Scrollable { // g2d.drawImage(object.getIcon(), object.x + 2, object.y + 2, null); // } - @Override - public Dimension getPreferredSize() { - return new Dimension((int)(zoomLevel * sizeX), (int)(zoomLevel * sizeY)); - } - - @Override - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } + @Override + public Dimension getPreferredSize() { + return new Dimension((int) (zoomLevel * sizeX), (int) (zoomLevel * sizeY)); + } - @Override - public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { - return TILE_SIZE; - } + @Override + public Dimension getPreferredScrollableViewportSize() { + return getPreferredSize(); + } - @Override - public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { - return 4 * TILE_SIZE; - } + @Override + public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { + return TILE_SIZE; + } - @Override - public boolean getScrollableTracksViewportWidth() { - return false; - } + @Override + public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { + return 4 * TILE_SIZE; + } - @Override - public boolean getScrollableTracksViewportHeight() { - return false; - } + @Override + public boolean getScrollableTracksViewportWidth() { + return false; + } + + @Override + public boolean getScrollableTracksViewportHeight() { + return false; + } + + public boolean recomputeSize() { + sizeX = sizeY = 0; + boolean originMoved = false; + int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE; + for (String s : mapLocations.keySet()) { + int x = mapLocations.get(s).x; + int w = proj.getMap(s).tmxMap.getWidth() * TILE_SIZE; + int y = mapLocations.get(s).y; + int h = proj.getMap(s).tmxMap.getHeight() * TILE_SIZE; + + sizeX = Math.max(sizeX, x + w); + sizeY = Math.max(sizeY, y + h); + minX = Math.min(minX, x); + minY = Math.min(minY, y); + } + + if (minX != 0) { + for (String s : mapLocations.keySet()) { + mapLocations.get(s).x -= minX; + } + sizeX -= minX; + offsetX += minX; + originMoved = true; + } + + if (minY != 0) { + for (String s : mapLocations.keySet()) { + mapLocations.get(s).y -= minY; + } + sizeY -= minY; + offsetY += minY; + originMoved = true; + } + return originMoved; + } + + + public void updateFromModel() { + mapLocations.clear(); + sizeX = sizeY = 0; + offsetX = worldmap.segmentX * TILE_SIZE; + offsetY = worldmap.segmentY * TILE_SIZE; + for (String s : worldmap.mapLocations.keySet()) { + if (proj.getMap(s) == null) { + System.err.println("Warning. Worldmap " + worldmap.id + " references map " + s + " but it doesn't exist in this project"); + continue; + } + int x = worldmap.mapLocations.get(s).x * TILE_SIZE; + int w = proj.getMap(s).tmxMap.getWidth() * TILE_SIZE; + int y = worldmap.mapLocations.get(s).y * TILE_SIZE; + int h = proj.getMap(s).tmxMap.getHeight() * TILE_SIZE; + + sizeX = Math.max(sizeX, x + w); + sizeY = Math.max(sizeY, y + h); + + mapLocations.put(s, new Rectangle(x, y, w, h)); + } + } + + public void pushToModel() { + worldmap.segmentX = offsetX / TILE_SIZE; + worldmap.segmentY = offsetY / TILE_SIZE; + for (String id : worldmap.mapLocations.keySet()) { + if (worldmap.getProject().getMap(id) == null) { + System.err.println("Warning. Worldmap " + worldmap.id + " references map " + id + " but it doesn't exist in this project"); + continue; + } + worldmap.getProject().getMap(id).removeBacklink(worldmap); + } + worldmap.mapLocations.clear(); + for (String s : mapLocations.keySet()) { + int x = mapLocations.get(s).x / TILE_SIZE; + int y = mapLocations.get(s).y / TILE_SIZE; + + worldmap.mapLocations.put(s, new Point(x, y)); + } + + for (String id : worldmap.mapLocations.keySet()) { + if (worldmap.getProject().getMap(id) == null) { + System.err.println("Warning. Worldmap " + worldmap.id + " references map " + id + " but it doesn't exist in this project"); + continue; + } + worldmap.getProject().getMap(id).addBacklink(worldmap); + } + } - public boolean recomputeSize() { - sizeX = sizeY = 0; - boolean originMoved = false; - int minX = Integer.MAX_VALUE, minY= Integer.MAX_VALUE; - for (String s : mapLocations.keySet()) { - int x = mapLocations.get(s).x; - int w = proj.getMap(s).tmxMap.getWidth() * TILE_SIZE; - int y = mapLocations.get(s).y; - int h = proj.getMap(s).tmxMap.getHeight() * TILE_SIZE; - - sizeX = Math.max(sizeX, x + w); - sizeY = Math.max(sizeY, y + h); - minX = Math.min(minX, x); - minY = Math.min(minY, y); - } - - if (minX != 0) { - for (String s : mapLocations.keySet()) { - mapLocations.get(s).x -= minX; - } - sizeX -= minX; - offsetX += minX; - originMoved = true; - } - - if (minY != 0) { - for (String s : mapLocations.keySet()) { - mapLocations.get(s).y -= minY; - } - sizeY -= minY; - offsetY += minY; - originMoved = true; - } - return originMoved; - } - - - - public void updateFromModel() { - mapLocations.clear(); - sizeX = sizeY = 0; - offsetX = worldmap.segmentX * TILE_SIZE; - offsetY = worldmap.segmentY * TILE_SIZE; - for (String s : worldmap.mapLocations.keySet()) { - if (proj.getMap(s) == null) { - System.err.println("Warning. Worldmap "+worldmap.id+" references map "+s+" but it doesn't exist in this project"); - continue; - } - int x = worldmap.mapLocations.get(s).x * TILE_SIZE; - int w = proj.getMap(s).tmxMap.getWidth() * TILE_SIZE; - int y = worldmap.mapLocations.get(s).y * TILE_SIZE; - int h = proj.getMap(s).tmxMap.getHeight() * TILE_SIZE; - - sizeX = Math.max(sizeX, x + w); - sizeY = Math.max(sizeY, y + h); - - mapLocations.put(s, new Rectangle(x, y, w, h)); - } - } - - public void pushToModel() { - worldmap.segmentX = offsetX / TILE_SIZE; - worldmap.segmentY = offsetY / TILE_SIZE; - for (String id : worldmap.mapLocations.keySet()) { - if (worldmap.getProject().getMap(id) == null) { - System.err.println("Warning. Worldmap "+worldmap.id+" references map "+id+" but it doesn't exist in this project"); - continue; - } - worldmap.getProject().getMap(id).removeBacklink(worldmap); - } - worldmap.mapLocations.clear(); - for (String s : mapLocations.keySet()) { - int x = mapLocations.get(s).x / TILE_SIZE; - int y = mapLocations.get(s).y / TILE_SIZE; - - worldmap.mapLocations.put(s, new Point(x, y)); - } - - for (String id : worldmap.mapLocations.keySet()) { - if (worldmap.getProject().getMap(id) == null) { - System.err.println("Warning. Worldmap "+worldmap.id+" references map "+id+" but it doesn't exist in this project"); - continue; - } - worldmap.getProject().getMap(id).addBacklink(worldmap); - } - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/saves/SavedGameEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/saves/SavedGameEditor.java index 7944465..ff4b6b0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/saves/SavedGameEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/saves/SavedGameEditor.java @@ -1,32 +1,30 @@ package com.gpl.rpg.atcontentstudio.ui.saves; -import java.awt.BorderLayout; - -import javax.swing.ImageIcon; -import javax.swing.JScrollPane; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.saves.SavedGame; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.Editor; +import javax.swing.*; +import java.awt.*; + public class SavedGameEditor extends Editor { - private static final long serialVersionUID = 6055910379650778737L; + private static final long serialVersionUID = 6055910379650778737L; - public SavedGameEditor(SavedGame save) { - this.name = save.loadedSave.displayInfo; - this.icon = new ImageIcon(DefaultIcons.getHeroIcon()); - this.target = save; - setLayout(new BorderLayout()); - add(new JScrollPane(new com.gpl.rpg.andorstrainer.ui.SavedGameEditor(save.loadedSave, ATContentStudio.frame)), BorderLayout.CENTER); - - } - - @Override - public void targetUpdated() { - // TODO Auto-generated method stub + public SavedGameEditor(SavedGame save) { + this.name = save.loadedSave.displayInfo; + this.icon = new ImageIcon(DefaultIcons.getHeroIcon()); + this.target = save; + setLayout(new BorderLayout()); + add(new JScrollPane(new com.gpl.rpg.andorstrainer.ui.SavedGameEditor(save.loadedSave, ATContentStudio.frame)), BorderLayout.CENTER); - } + } + + @Override + public void targetUpdated() { + // TODO Auto-generated method stub + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpriteChooser.java b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpriteChooser.java index ab55e24..36310fe 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpriteChooser.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpriteChooser.java @@ -1,5 +1,12 @@ package com.gpl.rpg.atcontentstudio.ui.sprites; +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; +import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet.Category; +import com.gpl.rpg.atcontentstudio.utils.SpriteUtils; + +import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -8,187 +15,180 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import javax.swing.*; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet.Category; -import com.gpl.rpg.atcontentstudio.utils.SpriteUtils; public class SpriteChooser extends JDialog { - private static final long serialVersionUID = -6018113265015159521L; + private static final long serialVersionUID = -6018113265015159521L; - private static final int STD_WIDTH = 32; - private static final int STD_HEIGHT = 32; - private static final int MAX_PER_ROW = 10; + private static final int STD_WIDTH = 32; + private static final int STD_HEIGHT = 32; + private static final int MAX_PER_ROW = 10; - public static Map> cache = new LinkedHashMap>(); - public static Map>> cacheValidator = new LinkedHashMap>>(); + public static Map> cache = new LinkedHashMap>(); + public static Map>> cacheValidator = new LinkedHashMap>>(); - public static SpriteChooser getChooser(Project proj, Spritesheet.Category category) { - if (cache.get(proj) == null) { - cache.put(proj, new LinkedHashMap()); - } - if (cache.get(proj).get(category) == null) { - cache.get(proj).put(category, new SpriteChooser(proj, category)); - } else { - List spritesheets = new ArrayList(); - for (int i = 0; i < proj.getSpritesheetCount(); i++) { - Spritesheet sheet = proj.getSpritesheet(i); - if (sheet.category == category) { - spritesheets.add(sheet); - } - } - if (!spritesheets.equals(cacheValidator.get(proj).get(category))) { - cache.get(proj).put(category, new SpriteChooser(proj, category)); - } - } - SpriteChooser wanted = cache.get(proj).get(category); - wanted.group.clearSelection(); - wanted.selectedIconId = null; + public static SpriteChooser getChooser(Project proj, Spritesheet.Category category) { + if (cache.get(proj) == null) { + cache.put(proj, new LinkedHashMap()); + } + if (cache.get(proj).get(category) == null) { + cache.get(proj).put(category, new SpriteChooser(proj, category)); + } else { + List spritesheets = new ArrayList(); + for (int i = 0; i < proj.getSpritesheetCount(); i++) { + Spritesheet sheet = proj.getSpritesheet(i); + if (sheet.category == category) { + spritesheets.add(sheet); + } + } + if (!spritesheets.equals(cacheValidator.get(proj).get(category))) { + cache.get(proj).put(category, new SpriteChooser(proj, category)); + } + } + SpriteChooser wanted = cache.get(proj).get(category); + wanted.group.clearSelection(); + wanted.selectedIconId = null; // wanted.selectedOne = null; - wanted.listener = null; + wanted.listener = null; // wanted.ok.setEnabled(false); - wanted.pack(); - return wanted; - } + wanted.pack(); + return wanted; + } - private ButtonGroup group; + private ButtonGroup group; // private IconButton selectedOne = null; // private JButton ok; // private JButton cancel; - public String selectedIconId = null; + public String selectedIconId = null; - public SpriteChooser(Project proj, Category category) { - super(ATContentStudio.frame); - setTitle("Select a sprite"); - setModalityType(ModalityType.APPLICATION_MODAL); - List spritesheets = new ArrayList(); - for (int i = 0; i < proj.getSpritesheetCount(); i++) { - Spritesheet sheet = proj.getSpritesheet(i); - if (sheet.category == category) { - spritesheets.add(sheet); - } - } - if (cacheValidator.get(proj) == null) { - cacheValidator.put(proj, new LinkedHashMap>()); - } - cacheValidator.get(proj).put(category, spritesheets); + public SpriteChooser(Project proj, Category category) { + super(ATContentStudio.frame); + setTitle("Select a sprite"); + setModalityType(ModalityType.APPLICATION_MODAL); + List spritesheets = new ArrayList(); + for (int i = 0; i < proj.getSpritesheetCount(); i++) { + Spritesheet sheet = proj.getSpritesheet(i); + if (sheet.category == category) { + spritesheets.add(sheet); + } + } + if (cacheValidator.get(proj) == null) { + cacheValidator.put(proj, new LinkedHashMap>()); + } + cacheValidator.get(proj).put(category, spritesheets); - JPanel pane = new JPanel(); - pane.setLayout(new GridBagLayout()); - GridBagConstraints c = new GridBagConstraints(); - c.weightx = 1; - c.weighty = 1; - c.gridx = 0; - c.gridy = 0; - c.gridwidth = 1; - c.gridheight = 1; - c.anchor = GridBagConstraints.NORTHWEST; - c.fill = GridBagConstraints.BOTH; + JPanel pane = new JPanel(); + pane.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.weightx = 1; + c.weighty = 1; + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 1; + c.gridheight = 1; + c.anchor = GridBagConstraints.NORTHWEST; + c.fill = GridBagConstraints.BOTH; - List reservedSlots = new ArrayList(); - Point nextFreeSlot = new Point(0, 0); + List reservedSlots = new ArrayList(); + Point nextFreeSlot = new Point(0, 0); - int i; - BufferedImage img; - group = new ButtonGroup(); - //For every sprite find a free space in panel: - for (Spritesheet sheet : spritesheets) { + int i; + BufferedImage img; + group = new ButtonGroup(); + //For every sprite find a free space in panel: + for (Spritesheet sheet : spritesheets) { i = -1; while ((img = sheet.getImage(++i)) != null) { if (SpriteUtils.checkIsImageEmpty(img)) { continue; } - IconButton button = new IconButton(img, sheet.id, i); - group.add(button); - if (sheet.spriteWidth == STD_WIDTH && sheet.spriteHeight == STD_HEIGHT) { - pane.add(button, c); - c.gridx++; - if (c.gridx >= MAX_PER_ROW) { - c.gridx = 0; - c.gridy++; - } - nextFreeSlot.setLocation(c.gridx, c.gridy); - } else { - c.gridwidth = (sheet.spriteWidth / STD_WIDTH) + (sheet.spriteWidth % STD_WIDTH == 0 ? 0 : 1); - c.gridheight = (sheet.spriteHeight / STD_HEIGHT) + (sheet.spriteHeight % STD_HEIGHT == 0 ? 0 : 1); - boolean slotOk = false; - while (!slotOk) { - slotOk = true; - for (int x = c.gridx; x < c.gridx + c.gridwidth; x++) { - for (int y = c.gridy; y < c.gridy + c.gridwidth; y++) { - if (reservedSlots.contains(new Point(x, y))) { - slotOk = false; - break; - } - } - if (!slotOk) { - break; - } - } - if (c.gridx + c.gridwidth > MAX_PER_ROW) { - c.gridx = 0; - c.gridy++; - slotOk = false; - } else if (!slotOk) { - c.gridx++; - } - } - pane.add(button, c); - for (int x = c.gridx; x < c.gridx + c.gridwidth; x++) { - for (int y = c.gridy; y < c.gridy + c.gridwidth; y++) { - reservedSlots.add(new Point(x, y)); - } - } - c.gridwidth = 1; - c.gridheight = 1; - c.gridx = nextFreeSlot.x; - c.gridy = nextFreeSlot.y; - } - while (reservedSlots.contains(nextFreeSlot)) { - c.gridx++; - if (c.gridx >= MAX_PER_ROW) { - c.gridx = 0; - c.gridy++; - } - nextFreeSlot.setLocation(c.gridx, c.gridy); - } - } - } + IconButton button = new IconButton(img, sheet.id, i); + group.add(button); + if (sheet.spriteWidth == STD_WIDTH && sheet.spriteHeight == STD_HEIGHT) { + pane.add(button, c); + c.gridx++; + if (c.gridx >= MAX_PER_ROW) { + c.gridx = 0; + c.gridy++; + } + nextFreeSlot.setLocation(c.gridx, c.gridy); + } else { + c.gridwidth = (sheet.spriteWidth / STD_WIDTH) + (sheet.spriteWidth % STD_WIDTH == 0 ? 0 : 1); + c.gridheight = (sheet.spriteHeight / STD_HEIGHT) + (sheet.spriteHeight % STD_HEIGHT == 0 ? 0 : 1); + boolean slotOk = false; + while (!slotOk) { + slotOk = true; + for (int x = c.gridx; x < c.gridx + c.gridwidth; x++) { + for (int y = c.gridy; y < c.gridy + c.gridwidth; y++) { + if (reservedSlots.contains(new Point(x, y))) { + slotOk = false; + break; + } + } + if (!slotOk) { + break; + } + } + if (c.gridx + c.gridwidth > MAX_PER_ROW) { + c.gridx = 0; + c.gridy++; + slotOk = false; + } else if (!slotOk) { + c.gridx++; + } + } + pane.add(button, c); + for (int x = c.gridx; x < c.gridx + c.gridwidth; x++) { + for (int y = c.gridy; y < c.gridy + c.gridwidth; y++) { + reservedSlots.add(new Point(x, y)); + } + } + c.gridwidth = 1; + c.gridheight = 1; + c.gridx = nextFreeSlot.x; + c.gridy = nextFreeSlot.y; + } + while (reservedSlots.contains(nextFreeSlot)) { + c.gridx++; + if (c.gridx >= MAX_PER_ROW) { + c.gridx = 0; + c.gridy++; + } + nextFreeSlot.setLocation(c.gridx, c.gridy); + } + } + } // ok = new JButton("Ok"); // cancel = new JButton("Cancel"); - c.gridx = 0; - boolean emptyLine = false; - while (!emptyLine) { - c.gridy++; - emptyLine = true; - for (i = MAX_PER_ROW - 1; i >= 0; i--) { - if (reservedSlots.contains(new Point(i, c.gridy))) { - emptyLine = false; - continue; - } - } - } + c.gridx = 0; + boolean emptyLine = false; + while (!emptyLine) { + c.gridy++; + emptyLine = true; + for (i = MAX_PER_ROW - 1; i >= 0; i--) { + if (reservedSlots.contains(new Point(i, c.gridy))) { + emptyLine = false; + continue; + } + } + } // JPanel buttonPane = new JPanel(); // buttonPane.add(cancel, BorderLayout.WEST); // buttonPane.add(ok, BorderLayout.EAST); - JPanel wrapper = new JPanel(); - wrapper.setLayout(new BorderLayout()); - JScrollPane scroller = new JScrollPane(pane); - scroller.getVerticalScrollBar().setUnitIncrement(16); - scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - wrapper.add(scroller, BorderLayout.CENTER); + JPanel wrapper = new JPanel(); + wrapper.setLayout(new BorderLayout()); + JScrollPane scroller = new JScrollPane(pane); + scroller.getVerticalScrollBar().setUnitIncrement(16); + scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); + wrapper.add(scroller, BorderLayout.CENTER); // wrapper.add(buttonPane, BorderLayout.SOUTH); // ok.addActionListener(new ActionListener() { @@ -211,44 +211,44 @@ public class SpriteChooser extends JDialog { // } // }); - setContentPane(wrapper); - } + setContentPane(wrapper); + } - private SpriteChooser.SelectionListener listener = null; + private SpriteChooser.SelectionListener listener = null; - public void setSelectionListener(SpriteChooser.SelectionListener l) { - listener = l; - } + public void setSelectionListener(SpriteChooser.SelectionListener l) { + listener = l; + } - public class IconButton extends JToggleButton { + public class IconButton extends JToggleButton { - private static final long serialVersionUID = 7559407153561178455L; + private static final long serialVersionUID = 7559407153561178455L; - public String sheetId; - public int spriteIndex; + public String sheetId; + public int spriteIndex; - public IconButton(Image img, String sheetId, int spriteIndex) { - super(new ImageIcon(img)); - this.sheetId = sheetId; - this.spriteIndex = spriteIndex; - setToolTipText(sheetId + ":" + spriteIndex); - addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (IconButton.this.isSelected()) { - selectedIconId = IconButton.this.sheetId + ":" + IconButton.this.spriteIndex; - SpriteChooser.this.setVisible(false); - SpriteChooser.this.dispose(); - if (listener != null) listener.iconSelected(selectedIconId); - } - } - }); - } - } + public IconButton(Image img, String sheetId, int spriteIndex) { + super(new ImageIcon(img)); + this.sheetId = sheetId; + this.spriteIndex = spriteIndex; + setToolTipText(sheetId + ":" + spriteIndex); + addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (IconButton.this.isSelected()) { + selectedIconId = IconButton.this.sheetId + ":" + IconButton.this.spriteIndex; + SpriteChooser.this.setVisible(false); + SpriteChooser.this.dispose(); + if (listener != null) listener.iconSelected(selectedIconId); + } + } + }); + } + } - public static interface SelectionListener { - public void iconSelected(String selected); - } + public static interface SelectionListener { + public void iconSelected(String selected); + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java index 2eba1c0..da8acb0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java @@ -1,44 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui.sprites; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Image; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListCellRenderer; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.ListModel; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListDataEvent; -import javax.swing.event.ListDataListener; -import javax.swing.event.TableModelListener; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableColumn; -import javax.swing.table.TableModel; - import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; @@ -53,404 +14,422 @@ import com.gpl.rpg.atcontentstudio.utils.DesktopIntegration; import com.jidesoft.swing.JideBoxLayout; import com.jidesoft.swing.JideTabbedPane; +import javax.swing.*; +import javax.swing.event.ListDataListener; +import javax.swing.event.TableModelListener; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.TableColumn; +import javax.swing.table.TableModel; +import java.awt.*; +import java.awt.event.*; +import java.util.List; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; + public class SpritesheetEditor extends Editor { - private static final long serialVersionUID = 3956109815682889863L; + private static final long serialVersionUID = 3956109815682889863L; - Map editorTabs = new LinkedHashMap(); - JideTabbedPane editorTabsHolder; - - private JSpinner widthField; - private JSpinner heightField; - private JCheckBox animatedBox; - @SuppressWarnings("rawtypes") - private JComboBox categoryBox; - private JPanel spriteViewPane; - - - public static JComponent getWarningLabel() { - JLabel label = new JLabel( - "" + - "The data accompamying the image here is not part of the game.
" + - "What you change here will be changed in your ATCS project only.
" + - "None of this is exported to JSON or TMX, although it must be set correctly in order to choose tiles & icons correctly.
" + - "
"); - return label; - } - - public SpritesheetEditor(Spritesheet sheet) { - super(); - this.icon = new ImageIcon(sheet.getIcon(0)); - this.name = sheet.id; - this.target = sheet; - - JPanel pane = new JPanel(); - - final FieldUpdateListener listener = new SpritesheetFieldUpdater(); - - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); + Map editorTabs = new LinkedHashMap(); + JideTabbedPane editorTabsHolder; - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - JButton openImage = new JButton(new ImageIcon(DefaultIcons.getTileLayerImage())); - openImage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - DesktopIntegration.openImage(((Spritesheet)target).spritesheetFile); - } - }); - buttonPane.add(openImage, JideBoxLayout.FIX); - buttonPane.add(getWarningLabel(), JideBoxLayout.FIX); - final JButton bookmark = new JButton(new ImageIcon(sheet.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); - buttonPane.add(bookmark, JideBoxLayout.FIX); - bookmark.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent arg0) { - if (target.bookmark == null) { - target.getProject().bookmark(target); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); - } else { - target.bookmark.delete(); - bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); - } - } - }); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, JideBoxLayout.FIX); - addLabelField(pane, "Spritesheet ID: ", sheet.id); - addLabelField(pane, "File: ", sheet.spritesheetFile.getAbsolutePath()); - widthField = addIntegerField(pane, "Sprite width (px): ", sheet.spriteWidth, false, true, listener); - heightField = addIntegerField(pane, "Sprite height (px): ", sheet.spriteHeight, false, true, listener); - animatedBox = addBooleanBasedCheckBox(pane, "Is an animation", sheet.animated, true, listener); - categoryBox = addEnumValueBox(pane, "Category: ", Spritesheet.Category.values(), sheet.category, true, listener); - - spriteViewPane = new JPanel(); - updateView(spriteViewPane); - pane.add(spriteViewPane, JideBoxLayout.FIX); + private JSpinner widthField; + private JSpinner heightField; + private JCheckBox animatedBox; + @SuppressWarnings("rawtypes") + private JComboBox categoryBox; + private JPanel spriteViewPane; - addBacklinksList(pane, sheet); - - //Placeholder. Fills the eventual remaining space. - pane.add(new JPanel(), JideBoxLayout.VARY); - - setLayout(new BorderLayout()); - editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); - editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); - editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); - editorTabsHolder.setShowCloseButtonOnTab(false); - add(editorTabsHolder, BorderLayout.CENTER); - JScrollPane sheetScroller = new JScrollPane(pane); - sheetScroller.getVerticalScrollBar().setUnitIncrement(16); - editorTabsHolder.add("Spritesheet",sheetScroller); - JScrollPane rawScroller = new JScrollPane(new JLabel(new ImageIcon(sheet.spritesheet))); - rawScroller.getVerticalScrollBar().setUnitIncrement(16); - editorTabsHolder.add("Raw image", rawScroller); - } - - private Thread animator = new Thread(); - private boolean animate = true; - private JLabel iconLabel; - private List icons = null; - - public void updateView(JPanel pane) { - Spritesheet sheet = (Spritesheet)target; - pane.removeAll(); - pane.setLayout(new BorderLayout()); - if (sheet.animated) { - iconLabel = new JLabel(); - iconLabel.setBackground(Color.WHITE); - if (icons == null) { - icons = new ArrayList(); - } else { - icons.clear(); - } - int i = 0; - Image img; - while ((img = sheet.getImage(i++)) != null) { - icons.add(new ImageIcon(img)); - } - if (i > 0) { - iconLabel.setIcon(icons.get(0)); - } - pane.add(iconLabel, BorderLayout.CENTER); - resetAnimator(); - } else { - JTable spritesTable = new JTable(new SpritesheetTableModel(sheet)); - spritesTable.setDefaultRenderer(Image.class, new SpritesheetCellRenderer(sheet)); - spritesTable.setCellSelectionEnabled(true); - spritesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - spritesTable.getTableHeader().setVisible(false); - Enumeration columns = spritesTable.getColumnModel().getColumns(); - TableColumn col; - while (columns.hasMoreElements()) { - col = columns.nextElement(); - col.setMinWidth(sheet.spriteWidth + 4); - col.setMaxWidth(sheet.spriteWidth + 4); - } - spritesTable.setRowHeight(sheet.spriteHeight + 4); - pane.add(new JScrollPane(spritesTable), BorderLayout.CENTER); - } - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static JList addBacklinksList(JPanel pane, Spritesheet sheet) { - final JList list = new JList(new SpritesheetsBacklinksListModel(sheet)); - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - if (list.getSelectedValue() instanceof TMXMap) { - ATContentStudio.frame.openEditor((TMXMap)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((TMXMap)list.getSelectedValue()); - } else if (list.getSelectedValue() instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((GameDataElement)list.getSelectedValue()); - } - } - } - }); - list.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - if (list.getSelectedValue() instanceof TMXMap) { - ATContentStudio.frame.openEditor((TMXMap)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((TMXMap)list.getSelectedValue()); - } else if (list.getSelectedValue() instanceof GameDataElement) { - ATContentStudio.frame.openEditor((GameDataElement)list.getSelectedValue()); - ATContentStudio.frame.selectInTree((GameDataElement)list.getSelectedValue()); - } - } - } - }); - list.setCellRenderer(new BacklinkCellRenderer(true)); - JScrollPane scroller = new JScrollPane(list); - scroller.setBorder(BorderFactory.createTitledBorder("Elements pointing to this spritesheet.")); - pane.add(scroller, JideBoxLayout.FIX); - return list; - } - - public static class SpritesheetTableModel implements TableModel { + public static JComponent getWarningLabel() { + JLabel label = new JLabel( + "" + + "The data accompamying the image here is not part of the game.
" + + "What you change here will be changed in your ATCS project only.
" + + "None of this is exported to JSON or TMX, although it must be set correctly in order to choose tiles & icons correctly.
" + + "
"); + return label; + } - Spritesheet sheet; - - public SpritesheetTableModel(Spritesheet sheet) { - this.sheet = sheet; - } - - @Override - public int getRowCount() { - return (sheet.spritesheet.getHeight() / sheet.spriteHeight) + ((sheet.spritesheet.getHeight() % sheet.spriteHeight) == 0 ? 0 : 1); - } + public SpritesheetEditor(Spritesheet sheet) { + super(); + this.icon = new ImageIcon(sheet.getIcon(0)); + this.name = sheet.id; + this.target = sheet; - @Override - public int getColumnCount() { - return (sheet.spritesheet.getWidth() / sheet.spriteWidth) + ((sheet.spritesheet.getWidth() % sheet.spriteWidth) == 0 ? 0 : 1); - } + JPanel pane = new JPanel(); - @Override - public String getColumnName(int columnIndex) { - return ""; - } + final FieldUpdateListener listener = new SpritesheetFieldUpdater(); - @Override - public Class getColumnClass(int columnIndex) { - return Image.class; - } + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.PAGE_AXIS, 6)); - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - return false; - } + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); + JButton openImage = new JButton(new ImageIcon(DefaultIcons.getTileLayerImage())); + openImage.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + DesktopIntegration.openImage(((Spritesheet) target).spritesheetFile); + } + }); + buttonPane.add(openImage, JideBoxLayout.FIX); + buttonPane.add(getWarningLabel(), JideBoxLayout.FIX); + final JButton bookmark = new JButton(new ImageIcon(sheet.bookmark != null ? DefaultIcons.getBookmarkActiveIcon() : DefaultIcons.getBookmarkInactiveIcon())); + buttonPane.add(bookmark, JideBoxLayout.FIX); + bookmark.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + if (target.bookmark == null) { + target.getProject().bookmark(target); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkActiveIcon())); + } else { + target.bookmark.delete(); + bookmark.setIcon(new ImageIcon(DefaultIcons.getBookmarkInactiveIcon())); + } + } + }); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + pane.add(buttonPane, JideBoxLayout.FIX); + addLabelField(pane, "Spritesheet ID: ", sheet.id); + addLabelField(pane, "File: ", sheet.spritesheetFile.getAbsolutePath()); + widthField = addIntegerField(pane, "Sprite width (px): ", sheet.spriteWidth, false, true, listener); + heightField = addIntegerField(pane, "Sprite height (px): ", sheet.spriteHeight, false, true, listener); + animatedBox = addBooleanBasedCheckBox(pane, "Is an animation", sheet.animated, true, listener); + categoryBox = addEnumValueBox(pane, "Category: ", Spritesheet.Category.values(), sheet.category, true, listener); - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - return sheet.getImage((rowIndex * getColumnCount()) + columnIndex); - } + spriteViewPane = new JPanel(); + updateView(spriteViewPane); + pane.add(spriteViewPane, JideBoxLayout.FIX); - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - } + addBacklinksList(pane, sheet); - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addTableModelListener(TableModelListener l) { - listeners.add(l); - } + //Placeholder. Fills the eventual remaining space. + pane.add(new JPanel(), JideBoxLayout.VARY); - @Override - public void removeTableModelListener(TableModelListener l) { - listeners.remove(l); - } - - } - - public static class SpritesheetCellRenderer extends DefaultTableCellRenderer { - private static final long serialVersionUID = -4213756343124247612L; - Spritesheet sheet; - public SpritesheetCellRenderer(Spritesheet sheet) { - super(); - this.sheet = sheet; - } - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - if (c instanceof JLabel) { - ((JLabel)c).setText(""); - if (value != null) { - ((JLabel)c).setIcon(new ImageIcon((Image)value)); - ((JLabel)c).setToolTipText(sheet.id+":"+((row * table.getColumnCount())+column)); - } - - } - return c; - } - } - - @Override - public void setVisible(boolean aFlag) { - super.setVisible(aFlag); - animate = aFlag; - if (aFlag && animator != null) { - resetAnimator(); - } - } + setLayout(new BorderLayout()); + editorTabsHolder = new JideTabbedPane(JideTabbedPane.BOTTOM); + editorTabsHolder.setTabShape(JideTabbedPane.SHAPE_FLAT); + editorTabsHolder.setUseDefaultShowCloseButtonOnTab(false); + editorTabsHolder.setShowCloseButtonOnTab(false); + add(editorTabsHolder, BorderLayout.CENTER); - private void resetAnimator() { - new Thread() { - public void run() { - if (animator != null && animator.isAlive()) { - try { - animator.join(); - } catch (InterruptedException e) {} - } - animate = true; - animator = new Thread() { - public void run() { - int i = -1; - while (animate) { - if (icons != null) { - synchronized (icons) { - i = (i + 1) % icons.size(); - iconLabel.setIcon(icons.get(i)); - } - iconLabel.revalidate(); - } - try { - Thread.sleep(100); - } catch (InterruptedException e) {} - } - }; - }; - animator.start(); - } - }.start(); - } - - - public static class SpritesheetsBacklinksListModel implements ListenerListModel { - - Spritesheet sheet; - - public SpritesheetsBacklinksListModel(Spritesheet sheet) { - this.sheet = sheet; - } - - @Override - public int getSize() { - return sheet.getBacklinks().size(); - } + JScrollPane sheetScroller = new JScrollPane(pane); + sheetScroller.getVerticalScrollBar().setUnitIncrement(16); + editorTabsHolder.add("Spritesheet", sheetScroller); + JScrollPane rawScroller = new JScrollPane(new JLabel(new ImageIcon(sheet.spritesheet))); + rawScroller.getVerticalScrollBar().setUnitIncrement(16); + editorTabsHolder.add("Raw image", rawScroller); + } - @Override - public ProjectTreeNode getElementAt(int index) { - for (ProjectTreeNode node : sheet.getBacklinks()) { - if (index == 0) return node; - index --; - } - return null; - } + private Thread animator = new Thread(); + private boolean animate = true; + private JLabel iconLabel; + private List icons = null; - List listeners = new CopyOnWriteArrayList(); + public void updateView(JPanel pane) { + Spritesheet sheet = (Spritesheet) target; + pane.removeAll(); + pane.setLayout(new BorderLayout()); + if (sheet.animated) { + iconLabel = new JLabel(); + iconLabel.setBackground(Color.WHITE); + if (icons == null) { + icons = new ArrayList(); + } else { + icons.clear(); + } + int i = 0; + Image img; + while ((img = sheet.getImage(i++)) != null) { + icons.add(new ImageIcon(img)); + } + if (i > 0) { + iconLabel.setIcon(icons.get(0)); + } + pane.add(iconLabel, BorderLayout.CENTER); + resetAnimator(); + } else { + JTable spritesTable = new JTable(new SpritesheetTableModel(sheet)); + spritesTable.setDefaultRenderer(Image.class, new SpritesheetCellRenderer(sheet)); + spritesTable.setCellSelectionEnabled(true); + spritesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + spritesTable.getTableHeader().setVisible(false); + Enumeration columns = spritesTable.getColumnModel().getColumns(); + TableColumn col; + while (columns.hasMoreElements()) { + col = columns.nextElement(); + col.setMinWidth(sheet.spriteWidth + 4); + col.setMaxWidth(sheet.spriteWidth + 4); + } + spritesTable.setRowHeight(sheet.spriteHeight + 4); + pane.add(new JScrollPane(spritesTable), BorderLayout.CENTER); + } + } - @Override - public List getListeners() { - return listeners; - } - } - - public static class BacklinkCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 6819681566800482793L; + @SuppressWarnings({"rawtypes", "unchecked"}) + public static JList addBacklinksList(JPanel pane, Spritesheet sheet) { + final JList list = new JList(new SpritesheetsBacklinksListModel(sheet)); + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + if (list.getSelectedValue() instanceof TMXMap) { + ATContentStudio.frame.openEditor((TMXMap) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((TMXMap) list.getSelectedValue()); + } else if (list.getSelectedValue() instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); + } + } + } + }); + list.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + if (list.getSelectedValue() instanceof TMXMap) { + ATContentStudio.frame.openEditor((TMXMap) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((TMXMap) list.getSelectedValue()); + } else if (list.getSelectedValue() instanceof GameDataElement) { + ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); + } + } + } + }); + list.setCellRenderer(new BacklinkCellRenderer(true)); + JScrollPane scroller = new JScrollPane(list); + scroller.setBorder(BorderFactory.createTitledBorder("Elements pointing to this spritesheet.")); + pane.add(scroller, JideBoxLayout.FIX); + return list; + } - private boolean includeType; - - public BacklinkCellRenderer(boolean includeType) { - super(); - this.includeType = includeType; - - } - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value == null) { - label.setText("none"); - } else { - if (includeType && ((ProjectTreeNode)value).getDataType() != null) { - label.setText(((ProjectTreeNode)value).getDataType().toString()+"/"+((ProjectTreeNode)value).getDesc()); - } else { - label.setText(((ProjectTreeNode)value).getDesc()); - } - if (((ProjectTreeNode)value).getIcon() == null) { - Notification.addError("Unable to find icon for "+((ProjectTreeNode)value).getDesc()); - } else { - label.setIcon(new ImageIcon(((ProjectTreeNode)value).getIcon())); - } - } - return label; - } - - } + public static class SpritesheetTableModel implements TableModel { - @Override - public void targetUpdated() { - this.icon = new ImageIcon(((Spritesheet)target).getIcon(0)); - this.name = ((Spritesheet)target).id; - } - - public class SpritesheetFieldUpdater implements FieldUpdateListener { - @Override - public void valueChanged(JComponent source, Object value) { - Spritesheet sheet = (Spritesheet) target; - if (source == widthField) { - sheet.spriteWidth = (Integer) value; - sheet.clearCache(); - updateView(spriteViewPane); - spriteViewPane.revalidate(); - spriteViewPane.repaint(); - } else if (source == heightField) { - sheet.spriteHeight = (Integer) value; - sheet.clearCache(); - updateView(spriteViewPane); - spriteViewPane.revalidate(); - spriteViewPane.repaint(); - } else if (source == animatedBox) { - sheet.animated = (Boolean) value; - if (!sheet.animated) { - animate = false; - } - updateView(spriteViewPane); - spriteViewPane.revalidate(); - spriteViewPane.repaint(); - } else if (source == categoryBox) { - sheet.category = (Spritesheet.Category) value; - } - sheet.save(); - } - } + Spritesheet sheet; + + public SpritesheetTableModel(Spritesheet sheet) { + this.sheet = sheet; + } + + @Override + public int getRowCount() { + return (sheet.spritesheet.getHeight() / sheet.spriteHeight) + ((sheet.spritesheet.getHeight() % sheet.spriteHeight) == 0 ? 0 : 1); + } + + @Override + public int getColumnCount() { + return (sheet.spritesheet.getWidth() / sheet.spriteWidth) + ((sheet.spritesheet.getWidth() % sheet.spriteWidth) == 0 ? 0 : 1); + } + + @Override + public String getColumnName(int columnIndex) { + return ""; + } + + @Override + public Class getColumnClass(int columnIndex) { + return Image.class; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + return sheet.getImage((rowIndex * getColumnCount()) + columnIndex); + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addTableModelListener(TableModelListener l) { + listeners.add(l); + } + + @Override + public void removeTableModelListener(TableModelListener l) { + listeners.remove(l); + } + + } + + public static class SpritesheetCellRenderer extends DefaultTableCellRenderer { + private static final long serialVersionUID = -4213756343124247612L; + Spritesheet sheet; + + public SpritesheetCellRenderer(Spritesheet sheet) { + super(); + this.sheet = sheet; + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + if (c instanceof JLabel) { + ((JLabel) c).setText(""); + if (value != null) { + ((JLabel) c).setIcon(new ImageIcon((Image) value)); + ((JLabel) c).setToolTipText(sheet.id + ":" + ((row * table.getColumnCount()) + column)); + } + + } + return c; + } + } + + @Override + public void setVisible(boolean aFlag) { + super.setVisible(aFlag); + animate = aFlag; + if (aFlag && animator != null) { + resetAnimator(); + } + } + + private void resetAnimator() { + new Thread() { + public void run() { + if (animator != null && animator.isAlive()) { + try { + animator.join(); + } catch (InterruptedException e) { + } + } + animate = true; + animator = new Thread() { + public void run() { + int i = -1; + while (animate) { + if (icons != null) { + synchronized (icons) { + i = (i + 1) % icons.size(); + iconLabel.setIcon(icons.get(i)); + } + iconLabel.revalidate(); + } + try { + Thread.sleep(100); + } catch (InterruptedException e) { + } + } + } + + ; + }; + animator.start(); + } + }.start(); + } + + + public static class SpritesheetsBacklinksListModel implements ListenerListModel { + + Spritesheet sheet; + + public SpritesheetsBacklinksListModel(Spritesheet sheet) { + this.sheet = sheet; + } + + @Override + public int getSize() { + return sheet.getBacklinks().size(); + } + + @Override + public ProjectTreeNode getElementAt(int index) { + for (ProjectTreeNode node : sheet.getBacklinks()) { + if (index == 0) return node; + index--; + } + return null; + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public List getListeners() { + return listeners; + } + } + + public static class BacklinkCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 6819681566800482793L; + + private boolean includeType; + + public BacklinkCellRenderer(boolean includeType) { + super(); + this.includeType = includeType; + + } + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value == null) { + label.setText("none"); + } else { + if (includeType && ((ProjectTreeNode) value).getDataType() != null) { + label.setText(((ProjectTreeNode) value).getDataType().toString() + "/" + ((ProjectTreeNode) value).getDesc()); + } else { + label.setText(((ProjectTreeNode) value).getDesc()); + } + if (((ProjectTreeNode) value).getIcon() == null) { + Notification.addError("Unable to find icon for " + ((ProjectTreeNode) value).getDesc()); + } else { + label.setIcon(new ImageIcon(((ProjectTreeNode) value).getIcon())); + } + } + return label; + } + + } + + @Override + public void targetUpdated() { + this.icon = new ImageIcon(((Spritesheet) target).getIcon(0)); + this.name = ((Spritesheet) target).id; + } + + public class SpritesheetFieldUpdater implements FieldUpdateListener { + @Override + public void valueChanged(JComponent source, Object value) { + Spritesheet sheet = (Spritesheet) target; + if (source == widthField) { + sheet.spriteWidth = (Integer) value; + sheet.clearCache(); + updateView(spriteViewPane); + spriteViewPane.revalidate(); + spriteViewPane.repaint(); + } else if (source == heightField) { + sheet.spriteHeight = (Integer) value; + sheet.clearCache(); + updateView(spriteViewPane); + spriteViewPane.revalidate(); + spriteViewPane.repaint(); + } else if (source == animatedBox) { + sheet.animated = (Boolean) value; + if (!sheet.animated) { + animate = false; + } + updateView(spriteViewPane); + spriteViewPane.revalidate(); + spriteViewPane.repaint(); + } else if (source == categoryBox) { + sheet.category = (Spritesheet.Category) value; + } + sheet.save(); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/BeanShellView.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/BeanShellView.java index fbca8b7..2f8d3a1 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/BeanShellView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/BeanShellView.java @@ -1,152 +1,143 @@ package com.gpl.rpg.atcontentstudio.ui.tools; -import java.awt.BorderLayout; +import bsh.EvalError; +import bsh.Interpreter; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import com.gpl.rpg.atcontentstudio.ui.WorkerDialog; +import com.jidesoft.swing.JideBoxLayout; +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; + +import javax.swing.*; +import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTextArea; - -import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; -import org.fife.ui.rsyntaxtextarea.SyntaxConstants; - -import bsh.EvalError; -import bsh.Interpreter; - -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.WorkerDialog; -import com.jidesoft.swing.JideBoxLayout; - public class BeanShellView extends JFrame { - /** - * - */ - private static final long serialVersionUID = 8399265342746690313L; + /** + * + */ + private static final long serialVersionUID = 8399265342746690313L; - public BeanShellView() { - super("ATCS BeanShell script pad"); - setIconImage(DefaultIcons.getMainIconImage()); - JSplitPane splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT); - - JPanel shPane = new JPanel(); - shPane.setLayout(new JideBoxLayout(shPane, JideBoxLayout.PAGE_AXIS)); - final RSyntaxTextArea shArea = new RSyntaxTextArea(30,80); - shArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); - shPane.add(new JScrollPane(shArea), JideBoxLayout.VARY); - - JPanel shButtonPane = new JPanel(); - shButtonPane.setLayout(new JideBoxLayout(shButtonPane, JideBoxLayout.LINE_AXIS)); - shButtonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton run = new JButton("Run"); - shButtonPane.add(run, JideBoxLayout.FIX); - shPane.add(shButtonPane, JideBoxLayout.FIX); - splitter.setTopComponent(shPane); - - final RSyntaxTextArea outArea = new RSyntaxTextArea(20,40); - outArea.setEditable(false); - JPanel outPane = new JPanel(); - outPane.setLayout(new JideBoxLayout(outPane, JideBoxLayout.PAGE_AXIS)); - JPanel outButtonPane = new JPanel(); - outButtonPane.setLayout(new JideBoxLayout(outButtonPane, JideBoxLayout.LINE_AXIS)); - outButtonPane.add(new JLabel("Output"), JideBoxLayout.FIX); - outButtonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton outClear = new JButton("Clear"); - outButtonPane.add(outClear, JideBoxLayout.FIX); - outPane.add(outButtonPane, JideBoxLayout.FIX); - outPane.add(new JScrollPane(outArea), JideBoxLayout.VARY); + public BeanShellView() { + super("ATCS BeanShell script pad"); + setIconImage(DefaultIcons.getMainIconImage()); + JSplitPane splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT); - final RSyntaxTextArea errArea = new RSyntaxTextArea(20,40); - errArea.setEditable(false); - JPanel errPane = new JPanel(); - errPane.setLayout(new JideBoxLayout(errPane, JideBoxLayout.PAGE_AXIS)); - JPanel errButtonPane = new JPanel(); - errButtonPane.setLayout(new JideBoxLayout(errButtonPane, JideBoxLayout.LINE_AXIS)); - errButtonPane.add(new JLabel("Errors"), JideBoxLayout.FIX); - errButtonPane.add(new JPanel(), JideBoxLayout.VARY); - JButton errClear = new JButton("Clear"); - errButtonPane.add(errClear, JideBoxLayout.FIX); - errPane.add(errButtonPane, JideBoxLayout.FIX); - errPane.add(new JScrollPane(errArea), JideBoxLayout.VARY); + JPanel shPane = new JPanel(); + shPane.setLayout(new JideBoxLayout(shPane, JideBoxLayout.PAGE_AXIS)); + final RSyntaxTextArea shArea = new RSyntaxTextArea(30, 80); + shArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA); + shPane.add(new JScrollPane(shArea), JideBoxLayout.VARY); + + JPanel shButtonPane = new JPanel(); + shButtonPane.setLayout(new JideBoxLayout(shButtonPane, JideBoxLayout.LINE_AXIS)); + shButtonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton run = new JButton("Run"); + shButtonPane.add(run, JideBoxLayout.FIX); + shPane.add(shButtonPane, JideBoxLayout.FIX); + splitter.setTopComponent(shPane); + + final RSyntaxTextArea outArea = new RSyntaxTextArea(20, 40); + outArea.setEditable(false); + JPanel outPane = new JPanel(); + outPane.setLayout(new JideBoxLayout(outPane, JideBoxLayout.PAGE_AXIS)); + JPanel outButtonPane = new JPanel(); + outButtonPane.setLayout(new JideBoxLayout(outButtonPane, JideBoxLayout.LINE_AXIS)); + outButtonPane.add(new JLabel("Output"), JideBoxLayout.FIX); + outButtonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton outClear = new JButton("Clear"); + outButtonPane.add(outClear, JideBoxLayout.FIX); + outPane.add(outButtonPane, JideBoxLayout.FIX); + outPane.add(new JScrollPane(outArea), JideBoxLayout.VARY); + + final RSyntaxTextArea errArea = new RSyntaxTextArea(20, 40); + errArea.setEditable(false); + JPanel errPane = new JPanel(); + errPane.setLayout(new JideBoxLayout(errPane, JideBoxLayout.PAGE_AXIS)); + JPanel errButtonPane = new JPanel(); + errButtonPane.setLayout(new JideBoxLayout(errButtonPane, JideBoxLayout.LINE_AXIS)); + errButtonPane.add(new JLabel("Errors"), JideBoxLayout.FIX); + errButtonPane.add(new JPanel(), JideBoxLayout.VARY); + JButton errClear = new JButton("Clear"); + errButtonPane.add(errClear, JideBoxLayout.FIX); + errPane.add(errButtonPane, JideBoxLayout.FIX); + errPane.add(new JScrollPane(errArea), JideBoxLayout.VARY); + + + JSplitPane errOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); + errOut.setLeftComponent(outPane); + errOut.setRightComponent(errPane); + splitter.setBottomComponent(errOut); + + run.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + final Interpreter shInt = new Interpreter(); + final PrintStream printOut = new PrintStream(new AreaOutputStream(outArea)); + shInt.setOut(printOut); + final PrintStream printErr = new PrintStream(new AreaOutputStream(errArea)); + shInt.setErr(printErr); + + WorkerDialog.showTaskMessage("Running your script...", null, new Runnable() { + @Override + public void run() { + + try { + shInt.eval(shArea.getText()); + } catch (EvalError e1) { + e1.printStackTrace(printErr); + } + printOut.flush(); + printErr.flush(); + printOut.close(); + printErr.close(); + + } + }); + + } + }); + + outClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + outArea.setText(""); + } + }); + + errClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + errArea.setText(""); + } + }); + + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(splitter, BorderLayout.CENTER); + pack(); + setVisible(true); + } + + public static class AreaOutputStream extends OutputStream { + + private JTextArea textArea; + + public AreaOutputStream(JTextArea area) { + this.textArea = area; + } + + @Override + public void write(int b) throws IOException { + textArea.append(String.valueOf((char) b)); + textArea.setCaretPosition(textArea.getDocument().getLength()); + } + + } - - JSplitPane errOut = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); - errOut.setLeftComponent(outPane); - errOut.setRightComponent(errPane); - splitter.setBottomComponent(errOut); - - run.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - final Interpreter shInt = new Interpreter(); - final PrintStream printOut = new PrintStream(new AreaOutputStream(outArea)); - shInt.setOut(printOut); - final PrintStream printErr = new PrintStream(new AreaOutputStream(errArea)); - shInt.setErr(printErr); - - WorkerDialog.showTaskMessage("Running your script...", null, new Runnable() { - @Override - public void run() { - - try { - shInt.eval(shArea.getText()); - } catch (EvalError e1) { - e1.printStackTrace(printErr); - } - printOut.flush(); - printErr.flush(); - printOut.close(); - printErr.close(); - - } - }); - - } - }); - - outClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - outArea.setText(""); - } - }); - - errClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - errArea.setText(""); - } - }); - - - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(splitter, BorderLayout.CENTER); - pack(); - setVisible(true); - } - - public static class AreaOutputStream extends OutputStream { - - private JTextArea textArea; - - public AreaOutputStream(JTextArea area) { - this.textArea = area; - } - - @Override - public void write(int b) throws IOException { - textArea.append(String.valueOf((char)b)); - textArea.setCaretPosition(textArea.getDocument().getLength()); - } - - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/ElementTableView.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/ElementTableView.java index 3bdd38a..11b8fed 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/ElementTableView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/ElementTableView.java @@ -1,81 +1,92 @@ package com.gpl.rpg.atcontentstudio.ui.tools; -import java.awt.BorderLayout; -import java.util.List; - -import javax.swing.Icon; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.table.TableModel; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.SaveEvent; import com.gpl.rpg.atcontentstudio.model.gamedata.GameDataSet; import com.gpl.rpg.atcontentstudio.ui.Editor; +import javax.swing.*; +import javax.swing.table.TableModel; +import java.awt.*; +import java.util.List; + public class ElementTableView extends Editor { - private static final long serialVersionUID = 8048693233599125878L; + private static final long serialVersionUID = 8048693233599125878L; - public ElementTableView(TableModel elementTableModel, String title, Icon icon) { - this.target = new DummyGDE(); - this.name = title; - this.icon = icon; - - setLayout(new BorderLayout()); - - JTable table = new JTable(elementTableModel) { - private static final long serialVersionUID = -2738230330859706440L; - public boolean getScrollableTracksViewportWidth() { - return getPreferredSize().width < getParent().getWidth(); - } + public ElementTableView(TableModel elementTableModel, String title, Icon icon) { + this.target = new DummyGDE(); + this.name = title; + this.icon = icon; + + setLayout(new BorderLayout()); + + JTable table = new JTable(elementTableModel) { + private static final long serialVersionUID = -2738230330859706440L; + + public boolean getScrollableTracksViewportWidth() { + return getPreferredSize().width < getParent().getWidth(); + } }; table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - table.setAutoCreateRowSorter(true); - table.setAutoscrolls(true); - table.setCellSelectionEnabled(false); - table.setRowSelectionAllowed(true); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - add(new JScrollPane(table), BorderLayout.CENTER); - } - - @Override - public void targetUpdated() { - - } - - class DummyGDE extends GameDataElement { + table.setAutoCreateRowSorter(true); + table.setAutoscrolls(true); + table.setCellSelectionEnabled(false); + table.setRowSelectionAllowed(true); + table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); + add(new JScrollPane(table), BorderLayout.CENTER); + } - private static final long serialVersionUID = 5889666999423783180L; + @Override + public void targetUpdated() { - @Override - public GameDataSet getDataSet() {return null;} + } - @Override - public String getDesc() {return null;} + class DummyGDE extends GameDataElement { - @Override - public void parse() {} + private static final long serialVersionUID = 5889666999423783180L; - @Override - public void link() {} + @Override + public GameDataSet getDataSet() { + return null; + } - @Override - public GameDataElement clone() {return null;} + @Override + public String getDesc() { + return null; + } - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) {} + @Override + public void parse() { + } - @Override - public String getProjectFilename() {return null;} + @Override + public void link() { + } - @Override - public void save() {} + @Override + public GameDataElement clone() { + return null; + } - @Override - public List attemptSave() {return null;} - - } + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + } + + @Override + public String getProjectFilename() { + return null; + } + + @Override + public void save() { + } + + @Override + public List attemptSave() { + return null; + } + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java index 1df2fc9..e8d7e76 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java @@ -1,216 +1,208 @@ package com.gpl.rpg.atcontentstudio.ui.tools; -import java.util.ArrayList; -import java.util.List; - import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.GameSource; import com.gpl.rpg.atcontentstudio.model.gamedata.*; -import com.gpl.rpg.atcontentstudio.model.maps.ContainerArea; -import com.gpl.rpg.atcontentstudio.model.maps.KeyArea; -import com.gpl.rpg.atcontentstudio.model.maps.MapChange; -import com.gpl.rpg.atcontentstudio.model.maps.MapObject; -import com.gpl.rpg.atcontentstudio.model.maps.MapObjectGroup; -import com.gpl.rpg.atcontentstudio.model.maps.ReplaceArea; -import com.gpl.rpg.atcontentstudio.model.maps.RestArea; -import com.gpl.rpg.atcontentstudio.model.maps.ScriptArea; -import com.gpl.rpg.atcontentstudio.model.maps.SignArea; -import com.gpl.rpg.atcontentstudio.model.maps.SpawnArea; -import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; +import com.gpl.rpg.atcontentstudio.model.maps.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; +import java.util.ArrayList; +import java.util.List; + public class GDEVisitor { - public static List findDependencies(GameDataElement origin, boolean includeSource) { - List visited = new ArrayList(); - visit(origin, visited, includeSource); - return visited; - } - - private static void visit(GameDataElement element, List visited, boolean includeSource) { - if (element == null) return; - if (visited.contains(element)) return; - if (!(includeSource || element.getDataType() != GameSource.Type.source)) return; - - visited.add(element); - element.link(); - if (element instanceof ActorCondition) { - visitActorCondition((ActorCondition)element, visited, includeSource); - } else if (element instanceof Dialogue) { - visitDialogue((Dialogue)element, visited, includeSource); - } else if (element instanceof Droplist) { - visitDroplist((Droplist)element, visited, includeSource); - } else if (element instanceof Item) { - visitItem((Item)element, visited, includeSource); - } else if (element instanceof ItemCategory) { - visitItemCategory((ItemCategory)element, visited, includeSource); - } else if (element instanceof NPC) { - visitNPC((NPC)element, visited, includeSource); - } else if (element instanceof Quest) { - visitQuest((Quest)element, visited, includeSource); - } else if (element instanceof TMXMap) { - visitTMXMap((TMXMap)element, visited, includeSource); - } else if (element instanceof Spritesheet) { - visitSpritesheet((Spritesheet)element, visited, includeSource); - } - - } + public static List findDependencies(GameDataElement origin, boolean includeSource) { + List visited = new ArrayList(); + visit(origin, visited, includeSource); + return visited; + } - private static void visitActorCondition(ActorCondition element, List visited, boolean includeSource) { - if (element.icon_id != null) visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); + private static void visit(GameDataElement element, List visited, boolean includeSource) { + if (element == null) return; + if (visited.contains(element)) return; + if (!(includeSource || element.getDataType() != GameSource.Type.source)) return; - for (GameDataElement backlink : element.getBacklinks()) { - visit(backlink, visited, includeSource); - } - } + visited.add(element); + element.link(); + if (element instanceof ActorCondition) { + visitActorCondition((ActorCondition) element, visited, includeSource); + } else if (element instanceof Dialogue) { + visitDialogue((Dialogue) element, visited, includeSource); + } else if (element instanceof Droplist) { + visitDroplist((Droplist) element, visited, includeSource); + } else if (element instanceof Item) { + visitItem((Item) element, visited, includeSource); + } else if (element instanceof ItemCategory) { + visitItemCategory((ItemCategory) element, visited, includeSource); + } else if (element instanceof NPC) { + visitNPC((NPC) element, visited, includeSource); + } else if (element instanceof Quest) { + visitQuest((Quest) element, visited, includeSource); + } else if (element instanceof TMXMap) { + visitTMXMap((TMXMap) element, visited, includeSource); + } else if (element instanceof Spritesheet) { + visitSpritesheet((Spritesheet) element, visited, includeSource); + } - private static void visitDialogue(Dialogue element, List visited, boolean includeSource) { - visit(element.switch_to_npc, visited, includeSource); - if (element.replies != null) { - for (Dialogue.Reply reply : element.replies) { - visit(reply.next_phrase, visited, includeSource); - if (reply.requirements != null) { - for (Requirement req : reply.requirements) { - visit(req.required_obj, visited, includeSource); - } - } - } - } - if (element.rewards != null) { - for (Dialogue.Reward reward : element.rewards) { - visit(reward.reward_obj, visited, includeSource); - visit(reward.map, visited, includeSource); - } - } - - for (GameDataElement backlink : element.getBacklinks()) { - visit(backlink, visited, includeSource); - } - } + } - private static void visitDroplist(Droplist element, List visited, boolean includeSource) { - if (element.dropped_items != null) { - for (Droplist.DroppedItem droppedItem : element.dropped_items) { - visit(droppedItem.item, visited, includeSource); - } - } - - for (GameDataElement backlink : element.getBacklinks()) { - visit(backlink, visited, includeSource); - } - } + private static void visitActorCondition(ActorCondition element, List visited, boolean includeSource) { + if (element.icon_id != null) + visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); - private static void visitItem(Item element, List visited, boolean includeSource) { - visit(element.category, visited, includeSource); - if (element.icon_id != null) visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); - if (element.equip_effect != null && element.equip_effect.conditions != null) { - for (Common.ConditionEffect condEffect : element.equip_effect.conditions) { - visit(condEffect.condition, visited, includeSource); - } - } - if (element.hit_effect != null) { - if (element.hit_effect.conditions_source != null) { - for (Common.ConditionEffect condEffect : element.hit_effect.conditions_source) { - visit(condEffect.condition, visited, includeSource); - } - } - if (element.hit_effect.conditions_target != null) { - for (Common.ConditionEffect condEffect : element.hit_effect.conditions_target) { - visit(condEffect.condition, visited, includeSource); - } - } - } - + for (GameDataElement backlink : element.getBacklinks()) { + visit(backlink, visited, includeSource); + } + } - for (GameDataElement backlink : element.getBacklinks()) { - visit(backlink, visited, includeSource); - } - } + private static void visitDialogue(Dialogue element, List visited, boolean includeSource) { + visit(element.switch_to_npc, visited, includeSource); + if (element.replies != null) { + for (Dialogue.Reply reply : element.replies) { + visit(reply.next_phrase, visited, includeSource); + if (reply.requirements != null) { + for (Requirement req : reply.requirements) { + visit(req.required_obj, visited, includeSource); + } + } + } + } + if (element.rewards != null) { + for (Dialogue.Reward reward : element.rewards) { + visit(reward.reward_obj, visited, includeSource); + visit(reward.map, visited, includeSource); + } + } - private static void visitItemCategory(ItemCategory element, List visited, boolean includeSource) { - //Nothing to visit - } + for (GameDataElement backlink : element.getBacklinks()) { + visit(backlink, visited, includeSource); + } + } - private static void visitNPC(NPC element, List visited, boolean includeSource) { - visit(element.dialogue, visited, includeSource); - visit(element.droplist, visited, includeSource); - if (element.icon_id != null) visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); - if (element.hit_effect != null) { - if (element.hit_effect.conditions_source != null) { - for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_source) { - visit(condEffect.condition, visited, includeSource); - } - } - if (element.hit_effect.conditions_target != null) { - for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_target) { - visit(condEffect.condition, visited, includeSource); - } - } - } - + private static void visitDroplist(Droplist element, List visited, boolean includeSource) { + if (element.dropped_items != null) { + for (Droplist.DroppedItem droppedItem : element.dropped_items) { + visit(droppedItem.item, visited, includeSource); + } + } - for (GameDataElement backlink : element.getBacklinks()) { - visit(backlink, visited, includeSource); - } - } + for (GameDataElement backlink : element.getBacklinks()) { + visit(backlink, visited, includeSource); + } + } - private static void visitQuest(Quest element, List visited, boolean includeSource) { - //Nothing to visit - + private static void visitItem(Item element, List visited, boolean includeSource) { + visit(element.category, visited, includeSource); + if (element.icon_id != null) + visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); + if (element.equip_effect != null && element.equip_effect.conditions != null) { + for (Common.ConditionEffect condEffect : element.equip_effect.conditions) { + visit(condEffect.condition, visited, includeSource); + } + } + if (element.hit_effect != null) { + if (element.hit_effect.conditions_source != null) { + for (Common.ConditionEffect condEffect : element.hit_effect.conditions_source) { + visit(condEffect.condition, visited, includeSource); + } + } + if (element.hit_effect.conditions_target != null) { + for (Common.ConditionEffect condEffect : element.hit_effect.conditions_target) { + visit(condEffect.condition, visited, includeSource); + } + } + } - for (GameDataElement backlink : element.getBacklinks()) { - visit(backlink, visited, includeSource); - } - } - private static void visitTMXMap(TMXMap element, List visited, boolean includeSource) { - // TODO Auto-generated method stub - if (element.groups != null) { - for (MapObjectGroup group : element.groups) { - if (group.mapObjects != null) { - for (MapObject obj : group.mapObjects) { - if (obj instanceof ContainerArea) { - visit(((ContainerArea)obj).droplist, visited, includeSource); - } else if (obj instanceof KeyArea) { - visit(((KeyArea)obj).dialogue, visited, includeSource); - if (((KeyArea)obj).requirement != null) { - visit(((KeyArea)obj).requirement.required_obj, visited, includeSource); - } - } else if (obj instanceof MapChange) { - visit(((MapChange)obj).map, visited, includeSource); - } else if (obj instanceof ReplaceArea) { - if (((ReplaceArea)obj).requirement != null) { - visit(((ReplaceArea)obj).requirement.required_obj, visited, includeSource); - } - } else if (obj instanceof RestArea) { - //Nothing to visit - } else if (obj instanceof ScriptArea) { - visit(((ScriptArea)obj).dialogue, visited, includeSource); - } else if (obj instanceof SignArea) { - visit(((SignArea)obj).dialogue, visited, includeSource); - } else if (obj instanceof SpawnArea) { - if (((SpawnArea)obj).spawnGroup != null) { - for (NPC npc : ((SpawnArea)obj).spawnGroup) { - visit(npc, visited, includeSource); - } - } - } - } - } - } - } - - for (GameDataElement backlink : element.getBacklinks()) { - visit(backlink, visited, includeSource); - } - } + for (GameDataElement backlink : element.getBacklinks()) { + visit(backlink, visited, includeSource); + } + } + + private static void visitItemCategory(ItemCategory element, List visited, boolean includeSource) { + //Nothing to visit + } + + private static void visitNPC(NPC element, List visited, boolean includeSource) { + visit(element.dialogue, visited, includeSource); + visit(element.droplist, visited, includeSource); + if (element.icon_id != null) + visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); + if (element.hit_effect != null) { + if (element.hit_effect.conditions_source != null) { + for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_source) { + visit(condEffect.condition, visited, includeSource); + } + } + if (element.hit_effect.conditions_target != null) { + for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_target) { + visit(condEffect.condition, visited, includeSource); + } + } + } + + + for (GameDataElement backlink : element.getBacklinks()) { + visit(backlink, visited, includeSource); + } + } + + private static void visitQuest(Quest element, List visited, boolean includeSource) { + //Nothing to visit + + + for (GameDataElement backlink : element.getBacklinks()) { + visit(backlink, visited, includeSource); + } + } + + private static void visitTMXMap(TMXMap element, List visited, boolean includeSource) { + // TODO Auto-generated method stub + if (element.groups != null) { + for (MapObjectGroup group : element.groups) { + if (group.mapObjects != null) { + for (MapObject obj : group.mapObjects) { + if (obj instanceof ContainerArea) { + visit(((ContainerArea) obj).droplist, visited, includeSource); + } else if (obj instanceof KeyArea) { + visit(((KeyArea) obj).dialogue, visited, includeSource); + if (((KeyArea) obj).requirement != null) { + visit(((KeyArea) obj).requirement.required_obj, visited, includeSource); + } + } else if (obj instanceof MapChange) { + visit(((MapChange) obj).map, visited, includeSource); + } else if (obj instanceof ReplaceArea) { + if (((ReplaceArea) obj).requirement != null) { + visit(((ReplaceArea) obj).requirement.required_obj, visited, includeSource); + } + } else if (obj instanceof RestArea) { + //Nothing to visit + } else if (obj instanceof ScriptArea) { + visit(((ScriptArea) obj).dialogue, visited, includeSource); + } else if (obj instanceof SignArea) { + visit(((SignArea) obj).dialogue, visited, includeSource); + } else if (obj instanceof SpawnArea) { + if (((SpawnArea) obj).spawnGroup != null) { + for (NPC npc : ((SpawnArea) obj).spawnGroup) { + visit(npc, visited, includeSource); + } + } + } + } + } + } + } + + for (GameDataElement backlink : element.getBacklinks()) { + visit(backlink, visited, includeSource); + } + } + + private static void visitSpritesheet(Spritesheet element, List visited, boolean includeSource) { + //Nothing to visit + + //Not even the backlinks. Makes no sense. + } + - private static void visitSpritesheet(Spritesheet element, List visited, boolean includeSource) { - //Nothing to visit - - //Not even the backlinks. Makes no sense. - } - - - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java index aa2383f..5227f89 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java @@ -1,247 +1,372 @@ package com.gpl.rpg.atcontentstudio.ui.tools; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.event.TableModelListener; -import javax.swing.table.TableModel; - import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.Item; import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.*; +import javax.swing.event.TableModelListener; +import javax.swing.table.TableModel; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class ItemsTableView extends ElementTableView { - private static final long serialVersionUID = 1474255176349837609L; + private static final long serialVersionUID = 1474255176349837609L; - public ItemsTableView(Project proj) { - super(new ItemsTableModel(proj), "Compare "+proj.getItemCountIncludingAltered()+" items.", new ImageIcon(DefaultIcons.getItemIcon())); - } - - private static class ItemsTableModel implements TableModel { + public ItemsTableView(Project proj) { + super(new ItemsTableModel(proj), "Compare " + proj.getItemCountIncludingAltered() + " items.", new ImageIcon(DefaultIcons.getItemIcon())); + } - Project proj; - - public ItemsTableModel(Project proj) { - this.proj = proj; - } - - @Override - public int getRowCount() { + private static class ItemsTableModel implements TableModel { + + Project proj; + + public ItemsTableModel(Project proj) { + this.proj = proj; + } + + @Override + public int getRowCount() { // return proj.getItemCount() + 1; - return proj.getItemCountIncludingAltered(); - } + return proj.getItemCountIncludingAltered(); + } - @Override - public int getColumnCount() { - return 43; - } + @Override + public int getColumnCount() { + return 43; + } - @Override - public String getColumnName(int columnIndex) { - switch (columnIndex) { - case 0: return "Icon"; //Icon - case 1: return "ID"; //ID - case 2: return "Name"; //Name - case 3: return "Folder type"; //Source type (created, altered, source) - case 4: return "Use type"; //Use type ("none", "use", or equip slot name). - case 5: return "Category"; //Category id. - case 6: return "DisplayType"; //Display type (ordinary, rare, extraordinary...) - case 7: return "Manually set price ?"; //Has manual price - case 8: return "Price"; //Price - case 9: return "On use/hit - HP min"; - case 10: return "On use/hit - HP max"; - case 11: return "On use/hit - AP min"; - case 12: return "On use/hit - AP max"; - case 13: return "On use/hit - # conditions"; - case 14: return "On kill - HP min"; - case 15: return "On kill - HP max"; - case 16: return "On kill - AP min"; - case 17: return "On kill - AP max"; - case 18: return "On kill - # conditions"; - case 19: return "On hit recv - HP min"; - case 20: return "On hit recv - HP max"; - case 21: return "On hit recv - AP min"; - case 22: return "On hit recv - AP max"; - case 23: return "On hit recv - # conditions"; - case 24: return "On hit recv - Tgt HP min"; - case 25: return "On hit recv - Tgt HP max"; - case 26: return "On hit recv - Tgt AP min"; - case 27: return "On hit recv - Tgt AP max"; - case 28: return "AD min"; - case 29: return "AD max"; - case 30: return "Damage modifier %"; - case 31: return "Max HP"; - case 32: return "Max AP"; - case 33: return "Attack cost"; - case 34: return "AC"; - case 35: return "BC"; - case 36: return "DR"; - case 37: return "CS"; - case 38: return "CM"; - case 39: return "Move cost"; - case 40: return "Use cost"; - case 41: return "Reequip cost"; - case 42: return "# conditions"; - } - return null; - } + @Override + public String getColumnName(int columnIndex) { + switch (columnIndex) { + case 0: + return "Icon"; //Icon + case 1: + return "ID"; //ID + case 2: + return "Name"; //Name + case 3: + return "Folder type"; //Source type (created, altered, source) + case 4: + return "Use type"; //Use type ("none", "use", or equip slot name). + case 5: + return "Category"; //Category id. + case 6: + return "DisplayType"; //Display type (ordinary, rare, extraordinary...) + case 7: + return "Manually set price ?"; //Has manual price + case 8: + return "Price"; //Price + case 9: + return "On use/hit - HP min"; + case 10: + return "On use/hit - HP max"; + case 11: + return "On use/hit - AP min"; + case 12: + return "On use/hit - AP max"; + case 13: + return "On use/hit - # conditions"; + case 14: + return "On kill - HP min"; + case 15: + return "On kill - HP max"; + case 16: + return "On kill - AP min"; + case 17: + return "On kill - AP max"; + case 18: + return "On kill - # conditions"; + case 19: + return "On hit recv - HP min"; + case 20: + return "On hit recv - HP max"; + case 21: + return "On hit recv - AP min"; + case 22: + return "On hit recv - AP max"; + case 23: + return "On hit recv - # conditions"; + case 24: + return "On hit recv - Tgt HP min"; + case 25: + return "On hit recv - Tgt HP max"; + case 26: + return "On hit recv - Tgt AP min"; + case 27: + return "On hit recv - Tgt AP max"; + case 28: + return "AD min"; + case 29: + return "AD max"; + case 30: + return "Damage modifier %"; + case 31: + return "Max HP"; + case 32: + return "Max AP"; + case 33: + return "Attack cost"; + case 34: + return "AC"; + case 35: + return "BC"; + case 36: + return "DR"; + case 37: + return "CS"; + case 38: + return "CM"; + case 39: + return "Move cost"; + case 40: + return "Use cost"; + case 41: + return "Reequip cost"; + case 42: + return "# conditions"; + } + return null; + } - @Override - public Class getColumnClass(int columnIndex) { + @Override + public Class getColumnClass(int columnIndex) { // return String.class; - switch (columnIndex) { - case 0: return Icon.class; // Icon - case 1: return String.class; //ID - case 2: return String.class; //Name - case 3: return String.class; //Source type (created, altered, source) - case 4: return String.class; //Use type ("none", "use", or equip slot name). - case 5: return String.class; //Category id. - case 6: return String.class; //Display type (ordinary, rare, extraordinary...) - case 7: return Boolean.class; //Has manual price - case 8: return Integer.class; //Price - case 9: return Integer.class;//"On use/hit - HP min"; - case 10: return Integer.class;//"On use/hit - HP max"; - case 11: return Integer.class;//"On use/hit - AP min"; - case 12: return Integer.class;//"On use/hit - AP max"; - case 13: return Integer.class;//"On use/hit - # conditions"; - case 14: return Integer.class;//"On kill - HP min"; - case 15: return Integer.class;//"On kill - HP max"; - case 16: return Integer.class;//"On kill - AP min"; - case 17: return Integer.class;//"On kill - AP max"; - case 18: return Integer.class;//"On kill - # conditions"; - case 19: return Integer.class;//"On hit recv - HP min"; - case 20: return Integer.class;//"On hit recv - HP max"; - case 21: return Integer.class;//"On hit recv - AP min"; - case 22: return Integer.class;//"On hit recv - AP max"; - case 23: return Integer.class;//"On hit recv - # conditions"; - case 24: return Integer.class;//"On hit recv - Tgt HP min"; - case 25: return Integer.class;//"On hit recv - Tgt HP max"; - case 26: return Integer.class;//"On hit recv - Tgt AP min"; - case 27: return Integer.class;//"On hit recv - Tgt AP max"; - case 28: return Integer.class;//"AD min"; - case 29: return Integer.class;//"AD max"; - case 30: return Integer.class;//"Damage modifier"; - case 31: return Integer.class;//"Max HP"; - case 32: return Integer.class;//"Max AP"; - case 33: return Integer.class;//"Attack cost"; - case 34: return Integer.class;//"AC"; - case 35: return Integer.class;//"BC"; - case 36: return Integer.class;//"DR"; - case 37: return Integer.class;//"CS"; - case 38: return Double.class;//"CM"; - case 39: return Integer.class;//"Move cost"; - case 40: return Integer.class;//"Use cost"; - case 41: return Integer.class;//"Reequip cost"; - case 42: return Integer.class;//"# conditions"; - } - return null; - } + switch (columnIndex) { + case 0: + return Icon.class; // Icon + case 1: + return String.class; //ID + case 2: + return String.class; //Name + case 3: + return String.class; //Source type (created, altered, source) + case 4: + return String.class; //Use type ("none", "use", or equip slot name). + case 5: + return String.class; //Category id. + case 6: + return String.class; //Display type (ordinary, rare, extraordinary...) + case 7: + return Boolean.class; //Has manual price + case 8: + return Integer.class; //Price + case 9: + return Integer.class;//"On use/hit - HP min"; + case 10: + return Integer.class;//"On use/hit - HP max"; + case 11: + return Integer.class;//"On use/hit - AP min"; + case 12: + return Integer.class;//"On use/hit - AP max"; + case 13: + return Integer.class;//"On use/hit - # conditions"; + case 14: + return Integer.class;//"On kill - HP min"; + case 15: + return Integer.class;//"On kill - HP max"; + case 16: + return Integer.class;//"On kill - AP min"; + case 17: + return Integer.class;//"On kill - AP max"; + case 18: + return Integer.class;//"On kill - # conditions"; + case 19: + return Integer.class;//"On hit recv - HP min"; + case 20: + return Integer.class;//"On hit recv - HP max"; + case 21: + return Integer.class;//"On hit recv - AP min"; + case 22: + return Integer.class;//"On hit recv - AP max"; + case 23: + return Integer.class;//"On hit recv - # conditions"; + case 24: + return Integer.class;//"On hit recv - Tgt HP min"; + case 25: + return Integer.class;//"On hit recv - Tgt HP max"; + case 26: + return Integer.class;//"On hit recv - Tgt AP min"; + case 27: + return Integer.class;//"On hit recv - Tgt AP max"; + case 28: + return Integer.class;//"AD min"; + case 29: + return Integer.class;//"AD max"; + case 30: + return Integer.class;//"Damage modifier"; + case 31: + return Integer.class;//"Max HP"; + case 32: + return Integer.class;//"Max AP"; + case 33: + return Integer.class;//"Attack cost"; + case 34: + return Integer.class;//"AC"; + case 35: + return Integer.class;//"BC"; + case 36: + return Integer.class;//"DR"; + case 37: + return Integer.class;//"CS"; + case 38: + return Double.class;//"CM"; + case 39: + return Integer.class;//"Move cost"; + case 40: + return Integer.class;//"Use cost"; + case 41: + return Integer.class;//"Reequip cost"; + case 42: + return Integer.class;//"# conditions"; + } + return null; + } - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - return false; - } + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } - @Override - public Object getValueAt(int rowIndex, int columnIndex) { + @Override + public Object getValueAt(int rowIndex, int columnIndex) { // if (rowIndex == 0) { // return getColumnName(columnIndex); // } // Item item = proj.getItem(rowIndex - 1); - Item item = proj.getItemIncludingAltered(rowIndex); - boolean canUse = item.category != null && item.category.action_type == ItemCategory.ActionType.use; - boolean canEquip = item.category != null && item.category.action_type == ItemCategory.ActionType.equip; - switch (columnIndex) { - case 0: return new ImageIcon(item.getIcon()); //Icon - case 1: return item.id; //ID - case 2: return item.name; //Name - case 3: return item.getDataType().toString(); //Source type (created, altered, source) - case 4: //Use type ("none", "use", or equip slot name). - if (item.category == null) return "none"; - if (item.category.action_type == null) return "none"; - if (item.category.action_type != ItemCategory.ActionType.equip) return item.category.action_type.toString(); - return item.category.slot.toString(); - case 5: return item.category != null ? item.category.id : (item.category_id != null ? item.category_id : null ); //Category id. - case 6: return item.display_type != null ? item.display_type.toString() : null; //Category id. - case 7: return item.has_manual_price == null ? false : (item.has_manual_price == 1); //Has manual price - case 8: //Price - if (item.has_manual_price == null || item.has_manual_price != 1) return item.computePrice(); - return item.base_market_cost; - case 9: return canUse ? (item.kill_effect != null ? item.kill_effect.hp_boost_min : null) : (item.hit_effect != null ? item.hit_effect.hp_boost_min : null);//"On use/hit - HP min"; - case 10: return canUse ? (item.kill_effect != null ? item.kill_effect.hp_boost_max : null) : (item.hit_effect != null ? item.hit_effect.hp_boost_max : null);//"On use/hit - HP max"; - case 11: return canUse ? (item.kill_effect != null ? item.kill_effect.ap_boost_min : null) : (item.hit_effect != null ? item.hit_effect.ap_boost_min : null);//"On use/hit - AP min"; - case 12: return canUse ? (item.kill_effect != null ? item.kill_effect.ap_boost_max : null) : (item.hit_effect != null ? item.hit_effect.ap_boost_max : null);//"On use/hit - AP max"; - case 13: //"On use/hit - # conditions"; - if (canUse) { - if (item.kill_effect != null && item.kill_effect.conditions_source != null) { - return item.kill_effect.conditions_source.size(); - } - return 0; - } else if (item.hit_effect != null) { - int val = 0; - if (item.hit_effect.conditions_source != null) { - val += item.hit_effect.conditions_source.size(); - } - if (item.hit_effect.conditions_target != null) { - val += item.hit_effect.conditions_target.size(); - } - return val; - } - return null; - case 14: return (!canUse && item.kill_effect != null) ? item.kill_effect.hp_boost_min : null;//"On kill - HP min"; - case 15: return (!canUse && item.kill_effect != null) ? item.kill_effect.hp_boost_max : null;//"On kill - HP max"; - case 16: return (!canUse && item.kill_effect != null) ? item.kill_effect.ap_boost_min : null;//"On kill - AP min"; - case 17: return (!canUse && item.kill_effect != null) ? item.kill_effect.ap_boost_max : null;//"On kill - AP max"; - case 18: return (!canUse && item.kill_effect != null && item.kill_effect.conditions_source != null) ? item.kill_effect.conditions_source.size() : null;//"On kill - # conditions"; - case 19: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_min : null;//"On hit recv - HP min"; - case 20: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_max : null;//"On hit recv - HP max"; - case 21: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_min : null;//"On hit recv - AP min"; - case 22: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_max : null;//"On hit recv - AP max"; - case 23: return (!canUse && item.hit_received_effect != null && item.hit_received_effect.conditions_source != null) ? item.hit_received_effect.conditions_source.size() : null;//"On hit recv - # conditions"; - case 24: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_min : null;//"On hit recv - Tgt HP min"; - case 25: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_max : null;//"On hit recv - Tgt HP max"; - case 26: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_min : null;//"On hit recv - Tgt AP min"; - case 27: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_max : null;//"On hit recv - Tgt AP max"; - case 28: return (canEquip && item.equip_effect != null) ? item.equip_effect.damage_boost_min : null;//"AD min"; - case 29: return (canEquip && item.equip_effect != null) ? item.equip_effect.damage_boost_max : null;//"AD max"; - case 30: return (canEquip && item.equip_effect != null) ? item.equip_effect.damage_modifier : null;//"Damage modifier"; - case 31: return (canEquip && item.equip_effect != null) ? item.equip_effect.max_hp_boost : null;//"Max HP"; - case 32: return (canEquip && item.equip_effect != null) ? item.equip_effect.max_ap_boost : null;//"Max AP"; - case 33: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_attack_cost : null;//"Attack cost"; - case 34: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_attack_chance : null;//"AC"; - case 35: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_block_chance : null;//"BC"; - case 36: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_damage_resistance : null;//"DR"; - case 37: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_critical_skill : null;//"CS"; - case 38: return (canEquip && item.equip_effect != null) ? item.equip_effect.critical_multiplier : null;//"CM"; - case 39: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_move_cost : null;//"Move cost"; - case 40: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_use_item_cost : null;//"Use cost"; - case 41: return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_reequip_cost : null;//"Reequip cost"; - case 42: return (canEquip && item.equip_effect != null && item.equip_effect.conditions != null) ? item.equip_effect.conditions.size() : null;//"# conditions"; - } - return null; - } + Item item = proj.getItemIncludingAltered(rowIndex); + boolean canUse = item.category != null && item.category.action_type == ItemCategory.ActionType.use; + boolean canEquip = item.category != null && item.category.action_type == ItemCategory.ActionType.equip; + switch (columnIndex) { + case 0: + return new ImageIcon(item.getIcon()); //Icon + case 1: + return item.id; //ID + case 2: + return item.name; //Name + case 3: + return item.getDataType().toString(); //Source type (created, altered, source) + case 4: //Use type ("none", "use", or equip slot name). + if (item.category == null) return "none"; + if (item.category.action_type == null) return "none"; + if (item.category.action_type != ItemCategory.ActionType.equip) + return item.category.action_type.toString(); + return item.category.slot.toString(); + case 5: + return item.category != null ? item.category.id : (item.category_id != null ? item.category_id : null); //Category id. + case 6: + return item.display_type != null ? item.display_type.toString() : null; //Category id. + case 7: + return item.has_manual_price == null ? false : (item.has_manual_price == 1); //Has manual price + case 8: //Price + if (item.has_manual_price == null || item.has_manual_price != 1) return item.computePrice(); + return item.base_market_cost; + case 9: + return canUse ? (item.kill_effect != null ? item.kill_effect.hp_boost_min : null) : (item.hit_effect != null ? item.hit_effect.hp_boost_min : null);//"On use/hit - HP min"; + case 10: + return canUse ? (item.kill_effect != null ? item.kill_effect.hp_boost_max : null) : (item.hit_effect != null ? item.hit_effect.hp_boost_max : null);//"On use/hit - HP max"; + case 11: + return canUse ? (item.kill_effect != null ? item.kill_effect.ap_boost_min : null) : (item.hit_effect != null ? item.hit_effect.ap_boost_min : null);//"On use/hit - AP min"; + case 12: + return canUse ? (item.kill_effect != null ? item.kill_effect.ap_boost_max : null) : (item.hit_effect != null ? item.hit_effect.ap_boost_max : null);//"On use/hit - AP max"; + case 13: //"On use/hit - # conditions"; + if (canUse) { + if (item.kill_effect != null && item.kill_effect.conditions_source != null) { + return item.kill_effect.conditions_source.size(); + } + return 0; + } else if (item.hit_effect != null) { + int val = 0; + if (item.hit_effect.conditions_source != null) { + val += item.hit_effect.conditions_source.size(); + } + if (item.hit_effect.conditions_target != null) { + val += item.hit_effect.conditions_target.size(); + } + return val; + } + return null; + case 14: + return (!canUse && item.kill_effect != null) ? item.kill_effect.hp_boost_min : null;//"On kill - HP min"; + case 15: + return (!canUse && item.kill_effect != null) ? item.kill_effect.hp_boost_max : null;//"On kill - HP max"; + case 16: + return (!canUse && item.kill_effect != null) ? item.kill_effect.ap_boost_min : null;//"On kill - AP min"; + case 17: + return (!canUse && item.kill_effect != null) ? item.kill_effect.ap_boost_max : null;//"On kill - AP max"; + case 18: + return (!canUse && item.kill_effect != null && item.kill_effect.conditions_source != null) ? item.kill_effect.conditions_source.size() : null;//"On kill - # conditions"; + case 19: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_min : null;//"On hit recv - HP min"; + case 20: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_max : null;//"On hit recv - HP max"; + case 21: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_min : null;//"On hit recv - AP min"; + case 22: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_max : null;//"On hit recv - AP max"; + case 23: + return (!canUse && item.hit_received_effect != null && item.hit_received_effect.conditions_source != null) ? item.hit_received_effect.conditions_source.size() : null;//"On hit recv - # conditions"; + case 24: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_min : null;//"On hit recv - Tgt HP min"; + case 25: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_max : null;//"On hit recv - Tgt HP max"; + case 26: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_min : null;//"On hit recv - Tgt AP min"; + case 27: + return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_max : null;//"On hit recv - Tgt AP max"; + case 28: + return (canEquip && item.equip_effect != null) ? item.equip_effect.damage_boost_min : null;//"AD min"; + case 29: + return (canEquip && item.equip_effect != null) ? item.equip_effect.damage_boost_max : null;//"AD max"; + case 30: + return (canEquip && item.equip_effect != null) ? item.equip_effect.damage_modifier : null;//"Damage modifier"; + case 31: + return (canEquip && item.equip_effect != null) ? item.equip_effect.max_hp_boost : null;//"Max HP"; + case 32: + return (canEquip && item.equip_effect != null) ? item.equip_effect.max_ap_boost : null;//"Max AP"; + case 33: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_attack_cost : null;//"Attack cost"; + case 34: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_attack_chance : null;//"AC"; + case 35: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_block_chance : null;//"BC"; + case 36: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_damage_resistance : null;//"DR"; + case 37: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_critical_skill : null;//"CS"; + case 38: + return (canEquip && item.equip_effect != null) ? item.equip_effect.critical_multiplier : null;//"CM"; + case 39: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_move_cost : null;//"Move cost"; + case 40: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_use_item_cost : null;//"Use cost"; + case 41: + return (canEquip && item.equip_effect != null) ? item.equip_effect.increase_reequip_cost : null;//"Reequip cost"; + case 42: + return (canEquip && item.equip_effect != null && item.equip_effect.conditions != null) ? item.equip_effect.conditions.size() : null;//"# conditions"; + } + return null; + } - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - //not editable. - } + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + //not editable. + } - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addTableModelListener(TableModelListener l) { - listeners.add(l); - } + List listeners = new CopyOnWriteArrayList(); - @Override - public void removeTableModelListener(TableModelListener l) { - listeners.remove(l); - } - - } + @Override + public void addTableModelListener(TableModelListener l) { + listeners.add(l); + } + + @Override + public void removeTableModelListener(TableModelListener l) { + listeners.remove(l); + } + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/MatrixComposite.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/MatrixComposite.java index 0b5b9d2..e44461e 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/MatrixComposite.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/MatrixComposite.java @@ -1,8 +1,6 @@ package com.gpl.rpg.atcontentstudio.ui.tools; -import java.awt.Composite; -import java.awt.CompositeContext; -import java.awt.RenderingHints; +import java.awt.*; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.Raster; @@ -11,114 +9,113 @@ import java.awt.image.WritableRaster; /** * This Composite emulates the behaviour of Android's ColorMatrixColorFilter, * except that you have to use this one a posteriori instead of a filtering paint. - * + *

* It applies a ColorMatrix to the destination pixels, regardless of potential "source" pixels. * Once created and activated through Graphics2D.setComposite(), just paint anything over the pixels you want "filtered". - * + *

* Works on a per-pixel basis, no sampling of surrounding pixels, or anything. - * - * @author pochat * + * @author pochat */ public class MatrixComposite implements Composite { - - final float[] matrix = new float[20]; - - - /** - * Dismisses the source pixels. Just paint it black, or white, it only affects the dest RGB with the following formulae. - * - * R' = a*R + b*G + c*B + d*A + e; - * G' = f*R + g*G + h*B + i*A + j; - * B' = k*R + l*G + m*B + n*A + o; - * A' = p*R + q*G + r*B + s*A + t; - * - * @param matrix a flat float[20] array, giving the a..t values; - */ - public MatrixComposite(float[] matrix) { - if (matrix.length != this.matrix.length) { - throw new Error("MatrixComposite matrix must be of length "+this.matrix.length); - } - System.arraycopy(matrix, 0, this.matrix, 0, this.matrix.length); - } - - @Override - public CompositeContext createContext(ColorModel srcColorModel, - ColorModel dstColorModel, RenderingHints hints) { - return new MatrixCompositeContext(this); - } - - class MatrixCompositeContext implements CompositeContext { - MatrixComposite composite; - - public MatrixCompositeContext(MatrixComposite composite) { - this.composite = composite; - } - - @Override - public void dispose() { - } + final float[] matrix = new float[20]; - @Override - public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { - if (src.getSampleModel().getDataType() != DataBuffer.TYPE_INT || - dstIn.getSampleModel().getDataType() != DataBuffer.TYPE_INT || - dstOut.getSampleModel().getDataType() != DataBuffer.TYPE_INT) { - throw new IllegalStateException( - "Source and destination must store pixels as INT."); - } - int width = Math.min(src.getWidth(), dstIn.getWidth()); - int height = Math.min(src.getHeight(), dstIn.getHeight()); + /** + * Dismisses the source pixels. Just paint it black, or white, it only affects the dest RGB with the following formulae. + *

+ * R' = a*R + b*G + c*B + d*A + e; + * G' = f*R + g*G + h*B + i*A + j; + * B' = k*R + l*G + m*B + n*A + o; + * A' = p*R + q*G + r*B + s*A + t; + * + * @param matrix a flat float[20] array, giving the a..t values; + */ + public MatrixComposite(float[] matrix) { + if (matrix.length != this.matrix.length) { + throw new Error("MatrixComposite matrix must be of length " + this.matrix.length); + } + System.arraycopy(matrix, 0, this.matrix, 0, this.matrix.length); + } - float alpha = 1.0f; + @Override + public CompositeContext createContext(ColorModel srcColorModel, + ColorModel dstColorModel, RenderingHints hints) { + return new MatrixCompositeContext(this); + } - int[] srcPixel = new int[4]; - int[] dstPixel = new int[4]; - int[] srcPixels = new int[width]; - int[] dstPixels = new int[width]; + class MatrixCompositeContext implements CompositeContext { - for (int y = 0; y < height; y++) { - src.getDataElements(0, y, width, 1, srcPixels); - dstIn.getDataElements(0, y, width, 1, dstPixels); - for (int x = 0; x < width; x++) { - // pixels are stored as INT_ARGB - // our arrays are [R, G, B, A] - int pixel = srcPixels[x]; - srcPixel[0] = (pixel >> 16) & 0xFF; - srcPixel[1] = (pixel >> 8) & 0xFF; - srcPixel[2] = (pixel ) & 0xFF; - srcPixel[3] = (pixel >> 24) & 0xFF; + MatrixComposite composite; - pixel = dstPixels[x]; - dstPixel[0] = (pixel >> 16) & 0xFF; - dstPixel[1] = (pixel >> 8) & 0xFF; - dstPixel[2] = (pixel ) & 0xFF; - dstPixel[3] = (pixel >> 24) & 0xFF; + public MatrixCompositeContext(MatrixComposite composite) { + this.composite = composite; + } - int[] result = applyMatrix(matrix, dstPixel); + @Override + public void dispose() { + } - // mixes the result with the opacity - dstPixels[x] = ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 | - ((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) << 16 | - ((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 | - (int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF; - } - dstOut.setDataElements(0, y, width, 1, dstPixels); - } - } - - private int[] applyMatrix(float[] matrix, int[] dstPixel) { - int[] result = new int[4]; - result[0] = Math.max(0, Math.min(255, (int) (matrix[ 0] * dstPixel[0] + matrix[ 1] * dstPixel[1] + matrix[ 2] * dstPixel[2] + matrix[ 3] * dstPixel[3] + matrix[ 4]) )); - result[1] = Math.max(0, Math.min(255, (int) (matrix[ 5] * dstPixel[0] + matrix[ 6] * dstPixel[1] + matrix[ 7] * dstPixel[2] + matrix[ 8] * dstPixel[3] + matrix[ 9]) )); - result[2] = Math.max(0, Math.min(255, (int) (matrix[10] * dstPixel[0] + matrix[11] * dstPixel[1] + matrix[12] * dstPixel[2] + matrix[13] * dstPixel[3] + matrix[14]) )); - result[3] = Math.max(0, Math.min(255, (int) (matrix[15] * dstPixel[0] + matrix[16] * dstPixel[1] + matrix[17] * dstPixel[2] + matrix[18] * dstPixel[3] + matrix[19]) )); - return result; - } - - } + @Override + public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { + if (src.getSampleModel().getDataType() != DataBuffer.TYPE_INT || + dstIn.getSampleModel().getDataType() != DataBuffer.TYPE_INT || + dstOut.getSampleModel().getDataType() != DataBuffer.TYPE_INT) { + throw new IllegalStateException( + "Source and destination must store pixels as INT."); + } + + int width = Math.min(src.getWidth(), dstIn.getWidth()); + int height = Math.min(src.getHeight(), dstIn.getHeight()); + + float alpha = 1.0f; + + int[] srcPixel = new int[4]; + int[] dstPixel = new int[4]; + int[] srcPixels = new int[width]; + int[] dstPixels = new int[width]; + + for (int y = 0; y < height; y++) { + src.getDataElements(0, y, width, 1, srcPixels); + dstIn.getDataElements(0, y, width, 1, dstPixels); + for (int x = 0; x < width; x++) { + // pixels are stored as INT_ARGB + // our arrays are [R, G, B, A] + int pixel = srcPixels[x]; + srcPixel[0] = (pixel >> 16) & 0xFF; + srcPixel[1] = (pixel >> 8) & 0xFF; + srcPixel[2] = (pixel) & 0xFF; + srcPixel[3] = (pixel >> 24) & 0xFF; + + pixel = dstPixels[x]; + dstPixel[0] = (pixel >> 16) & 0xFF; + dstPixel[1] = (pixel >> 8) & 0xFF; + dstPixel[2] = (pixel) & 0xFF; + dstPixel[3] = (pixel >> 24) & 0xFF; + + int[] result = applyMatrix(matrix, dstPixel); + + // mixes the result with the opacity + dstPixels[x] = ((int) (dstPixel[3] + (result[3] - dstPixel[3]) * alpha) & 0xFF) << 24 | + ((int) (dstPixel[0] + (result[0] - dstPixel[0]) * alpha) & 0xFF) << 16 | + ((int) (dstPixel[1] + (result[1] - dstPixel[1]) * alpha) & 0xFF) << 8 | + (int) (dstPixel[2] + (result[2] - dstPixel[2]) * alpha) & 0xFF; + } + dstOut.setDataElements(0, y, width, 1, dstPixels); + } + } + + private int[] applyMatrix(float[] matrix, int[] dstPixel) { + int[] result = new int[4]; + result[0] = Math.max(0, Math.min(255, (int) (matrix[0] * dstPixel[0] + matrix[1] * dstPixel[1] + matrix[2] * dstPixel[2] + matrix[3] * dstPixel[3] + matrix[4]))); + result[1] = Math.max(0, Math.min(255, (int) (matrix[5] * dstPixel[0] + matrix[6] * dstPixel[1] + matrix[7] * dstPixel[2] + matrix[8] * dstPixel[3] + matrix[9]))); + result[2] = Math.max(0, Math.min(255, (int) (matrix[10] * dstPixel[0] + matrix[11] * dstPixel[1] + matrix[12] * dstPixel[2] + matrix[13] * dstPixel[3] + matrix[14]))); + result[3] = Math.max(0, Math.min(255, (int) (matrix[15] * dstPixel[0] + matrix[16] * dstPixel[1] + matrix[17] * dstPixel[2] + matrix[18] * dstPixel[3] + matrix[19]))); + return result; + } + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/NPCsTableView.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/NPCsTableView.java index 6142ee7..d486766 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/NPCsTableView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/NPCsTableView.java @@ -1,175 +1,247 @@ package com.gpl.rpg.atcontentstudio.ui.tools; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.event.TableModelListener; -import javax.swing.table.TableModel; - import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import javax.swing.*; +import javax.swing.event.TableModelListener; +import javax.swing.table.TableModel; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + public class NPCsTableView extends ElementTableView { - private static final long serialVersionUID = -4196852140899079621L; + private static final long serialVersionUID = -4196852140899079621L; - public NPCsTableView(Project proj) { - super(new NPCsTableModel(proj), "Compare "+proj.getNPCCountIncludingAltered()+" NPCs.", new ImageIcon(DefaultIcons.getNPCIcon())); - } - - private static class NPCsTableModel implements TableModel { + public NPCsTableView(Project proj) { + super(new NPCsTableModel(proj), "Compare " + proj.getNPCCountIncludingAltered() + " NPCs.", new ImageIcon(DefaultIcons.getNPCIcon())); + } - Project proj; - - public NPCsTableModel(Project proj) { - this.proj = proj; - } - - @Override - public int getRowCount() { - return proj.getNPCCountIncludingAltered(); - } + private static class NPCsTableModel implements TableModel { - @Override - public int getColumnCount() { - return 25; - } + Project proj; - @Override - public String getColumnName(int columnIndex) { - switch (columnIndex) { - case 0: return "Icon"; //Icon - case 1: return "ID"; //ID - case 2: return "Name"; //Name - case 3: return "Category type"; //Source type (created, altered, source) - case 4: return "Unique"; - case 5: return "Class"; - case 6: return "Movement type"; - case 7: return "Spawngroup"; - case 8: return "Faction"; - case 9: return "HP"; - case 10: return "AP"; - case 11: return "Attack Cost"; - case 12: return "AC"; - case 13: return "BC"; - case 14: return "AD min"; - case 15: return "AD max"; - case 16: return "DR"; - case 17: return "CS"; - case 18: return "CM"; - case 19: return "On hit - HP min"; - case 20: return "On hit - HP max"; - case 21: return "On hit - AP min"; - case 22: return "On hit - AP max"; - case 23: return "On hit - # conditions"; - case 24: return "Experience reward"; - } - return null; - } + public NPCsTableModel(Project proj) { + this.proj = proj; + } - @Override - public Class getColumnClass(int columnIndex) { - switch (columnIndex) { - case 0: return Icon.class; //Icon - case 1: return String.class; //ID - case 2: return String.class; //Name - case 3: return String.class; //Source type (created, altered, source) - case 4: return Boolean.class; //"Unique"; - case 5: return String.class; //"Class"; - case 6: return String.class; //"Movement type"; - case 7: return String.class; //"Spawngroup"; - case 8: return String.class; //"Faction"; - case 9: return Integer.class; //"HP"; - case 10: return Integer.class; //"AP"; - case 11: return Integer.class; //"Attack Cost"; - case 12: return Integer.class; //"AC"; - case 13: return Integer.class; //"BC"; - case 14: return Integer.class; //"AD min"; - case 15: return Integer.class; //"AD max"; - case 16: return Integer.class; //"DR"; - case 17: return Integer.class; //"CS"; - case 18: return Double.class; //"CM"; - case 19: return Integer.class; //"On hit - HP min"; - case 20: return Integer.class; //"On hit - HP max"; - case 21: return Integer.class; //"On hit - AP min"; - case 22: return Integer.class; //"On hit - AP max"; - case 23: return Integer.class; //"On hit - # conditions"; - case 24: return Integer.class; //"Experience reward"; - } - return null; - } + @Override + public int getRowCount() { + return proj.getNPCCountIncludingAltered(); + } - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - return false; - } + @Override + public int getColumnCount() { + return 25; + } - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - NPC npc = proj.getNPCIncludingAltered(rowIndex); - switch (columnIndex) { - case 0: return new ImageIcon(npc.getIcon()); // Icon - case 1: return npc.id; //ID - case 2: return npc.name; //Name - case 3: return npc.getDataType().toString(); //Source type (created, altered, source) - case 4: return npc.unique != null && npc.unique == 1;//"Unique"; - case 5: return npc.monster_class != null ? npc.monster_class.toString() : null; //"Class"; - case 6: return npc.movement_type != null ? npc.movement_type.toString() : null; //"Movement type"; - case 7: return npc.spawngroup_id; //"Spawngroup"; - case 8: return npc.faction_id; //"Faction"; - case 9: return npc.max_hp; //"HP"; - case 10: return npc.max_ap; //"AP"; - case 11: return npc.attack_cost; //"Attack Cost"; - case 12: return npc.attack_chance; //"AC"; - case 13: return npc.block_chance; //"BC"; - case 14: return npc.attack_damage_min; //"AD min"; - case 15: return npc.attack_damage_max; //"AD max"; - case 16: return npc.damage_resistance; //"DR"; - case 17: return npc.critical_skill; //"CS"; - case 18: return npc.critical_multiplier; //"CM"; - case 19: return npc.hit_effect != null ? npc.hit_effect.hp_boost_min : null; //"On hit - HP min"; - case 20: return npc.hit_effect != null ? npc.hit_effect.hp_boost_max : null; //"On hit - HP max"; - case 21: return npc.hit_effect != null ? npc.hit_effect.ap_boost_min : null; //"On hit - AP min"; - case 22: return npc.hit_effect != null ? npc.hit_effect.ap_boost_max : null; //"On hit - AP max"; - case 23: //"On hit - # conditions"; - if (npc.hit_effect != null) { - Integer val = null; - if (npc.hit_effect.conditions_source != null) { - val = npc.hit_effect.conditions_source.size(); - } - if (npc.hit_effect.conditions_target != null) { - if (val == null) val = npc.hit_effect.conditions_target.size(); - else val += npc.hit_effect.conditions_target.size(); - } - return val; - } - return null; - case 24: return npc.getMonsterExperience(); - } - return null; - } + @Override + public String getColumnName(int columnIndex) { + switch (columnIndex) { + case 0: + return "Icon"; //Icon + case 1: + return "ID"; //ID + case 2: + return "Name"; //Name + case 3: + return "Category type"; //Source type (created, altered, source) + case 4: + return "Unique"; + case 5: + return "Class"; + case 6: + return "Movement type"; + case 7: + return "Spawngroup"; + case 8: + return "Faction"; + case 9: + return "HP"; + case 10: + return "AP"; + case 11: + return "Attack Cost"; + case 12: + return "AC"; + case 13: + return "BC"; + case 14: + return "AD min"; + case 15: + return "AD max"; + case 16: + return "DR"; + case 17: + return "CS"; + case 18: + return "CM"; + case 19: + return "On hit - HP min"; + case 20: + return "On hit - HP max"; + case 21: + return "On hit - AP min"; + case 22: + return "On hit - AP max"; + case 23: + return "On hit - # conditions"; + case 24: + return "Experience reward"; + } + return null; + } - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - //not editable. - } + @Override + public Class getColumnClass(int columnIndex) { + switch (columnIndex) { + case 0: + return Icon.class; //Icon + case 1: + return String.class; //ID + case 2: + return String.class; //Name + case 3: + return String.class; //Source type (created, altered, source) + case 4: + return Boolean.class; //"Unique"; + case 5: + return String.class; //"Class"; + case 6: + return String.class; //"Movement type"; + case 7: + return String.class; //"Spawngroup"; + case 8: + return String.class; //"Faction"; + case 9: + return Integer.class; //"HP"; + case 10: + return Integer.class; //"AP"; + case 11: + return Integer.class; //"Attack Cost"; + case 12: + return Integer.class; //"AC"; + case 13: + return Integer.class; //"BC"; + case 14: + return Integer.class; //"AD min"; + case 15: + return Integer.class; //"AD max"; + case 16: + return Integer.class; //"DR"; + case 17: + return Integer.class; //"CS"; + case 18: + return Double.class; //"CM"; + case 19: + return Integer.class; //"On hit - HP min"; + case 20: + return Integer.class; //"On hit - HP max"; + case 21: + return Integer.class; //"On hit - AP min"; + case 22: + return Integer.class; //"On hit - AP max"; + case 23: + return Integer.class; //"On hit - # conditions"; + case 24: + return Integer.class; //"Experience reward"; + } + return null; + } - List listeners = new CopyOnWriteArrayList(); - - @Override - public void addTableModelListener(TableModelListener l) { - listeners.add(l); - } + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + NPC npc = proj.getNPCIncludingAltered(rowIndex); + switch (columnIndex) { + case 0: + return new ImageIcon(npc.getIcon()); // Icon + case 1: + return npc.id; //ID + case 2: + return npc.name; //Name + case 3: + return npc.getDataType().toString(); //Source type (created, altered, source) + case 4: + return npc.unique != null && npc.unique == 1;//"Unique"; + case 5: + return npc.monster_class != null ? npc.monster_class.toString() : null; //"Class"; + case 6: + return npc.movement_type != null ? npc.movement_type.toString() : null; //"Movement type"; + case 7: + return npc.spawngroup_id; //"Spawngroup"; + case 8: + return npc.faction_id; //"Faction"; + case 9: + return npc.max_hp; //"HP"; + case 10: + return npc.max_ap; //"AP"; + case 11: + return npc.attack_cost; //"Attack Cost"; + case 12: + return npc.attack_chance; //"AC"; + case 13: + return npc.block_chance; //"BC"; + case 14: + return npc.attack_damage_min; //"AD min"; + case 15: + return npc.attack_damage_max; //"AD max"; + case 16: + return npc.damage_resistance; //"DR"; + case 17: + return npc.critical_skill; //"CS"; + case 18: + return npc.critical_multiplier; //"CM"; + case 19: + return npc.hit_effect != null ? npc.hit_effect.hp_boost_min : null; //"On hit - HP min"; + case 20: + return npc.hit_effect != null ? npc.hit_effect.hp_boost_max : null; //"On hit - HP max"; + case 21: + return npc.hit_effect != null ? npc.hit_effect.ap_boost_min : null; //"On hit - AP min"; + case 22: + return npc.hit_effect != null ? npc.hit_effect.ap_boost_max : null; //"On hit - AP max"; + case 23: //"On hit - # conditions"; + if (npc.hit_effect != null) { + Integer val = null; + if (npc.hit_effect.conditions_source != null) { + val = npc.hit_effect.conditions_source.size(); + } + if (npc.hit_effect.conditions_target != null) { + if (val == null) val = npc.hit_effect.conditions_target.size(); + else val += npc.hit_effect.conditions_target.size(); + } + return val; + } + return null; + case 24: + return npc.getMonsterExperience(); + } + return null; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + //not editable. + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public void addTableModelListener(TableModelListener l) { + listeners.add(l); + } + + @Override + public void removeTableModelListener(TableModelListener l) { + listeners.remove(l); + } + + } - @Override - public void removeTableModelListener(TableModelListener l) { - listeners.remove(l); - } - - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java index 9895edb..218dead 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java @@ -1,33 +1,15 @@ package com.gpl.rpg.atcontentstudio.ui.tools.writermode; -import java.awt.BorderLayout; -import java.awt.Image; -import java.awt.Point; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.FocusEvent; -import java.awt.event.FocusListener; -import java.awt.event.KeyEvent; -import java.awt.event.MouseEvent; -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.swing.AbstractAction; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JEditorPane; -import javax.swing.JInternalFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.KeyStroke; -import javax.swing.plaf.basic.BasicInternalFrameUI; - +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; +import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; +import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData; +import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData.*; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import com.gpl.rpg.atcontentstudio.ui.Editor; import com.gpl.rpg.atcontentstudio.utils.TextUtils; +import com.jidesoft.swing.JideBoxLayout; import prefuse.Display; import prefuse.Visualization; import prefuse.action.Action; @@ -42,12 +24,7 @@ import prefuse.controls.ControlAdapter; import prefuse.controls.PanControl; import prefuse.controls.WheelZoomControl; import prefuse.controls.ZoomControl; -import prefuse.data.Edge; -import prefuse.data.FilteredSpanningTree; -import prefuse.data.Graph; -import prefuse.data.Node; -import prefuse.data.Schema; -import prefuse.data.Tree; +import prefuse.data.*; import prefuse.data.expression.ColumnExpression; import prefuse.render.DefaultRendererFactory; import prefuse.render.EdgeRenderer; @@ -60,170 +37,158 @@ import prefuse.visual.EdgeItem; import prefuse.visual.VisualItem; import prefuse.visual.expression.InGroupPredicate; -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; -import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData; -import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData.EmptyReply; -import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData.SpecialDialogue; -import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData.WriterDialogue; -import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData.WriterNode; -import com.gpl.rpg.atcontentstudio.model.tools.writermode.WriterModeData.WriterReply; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.Editor; -import com.jidesoft.swing.JideBoxLayout; +import javax.swing.*; +import javax.swing.plaf.basic.BasicInternalFrameUI; +import java.awt.*; +import java.awt.event.*; +import java.awt.geom.Point2D; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; public class WriterModeEditor extends Editor { - private static final long serialVersionUID = -6591631891278528494L; - - private static final String HELP_TEXT = - "" - + "" - + "" - + "" - + "" - + "
(Esc.) Cancel edition
(Ctrl+Enter) Confirm changes
(Shift+Enter) Create next of same kind
(Alt+Enter) Create next of other kind
"; - + private static final long serialVersionUID = -6591631891278528494L; + + private static final String HELP_TEXT = + "" + + "" + + "" + + "" + + "" + + "
(Esc.) Cancel edition
(Ctrl+Enter) Confirm changes
(Shift+Enter) Create next of same kind
(Alt+Enter) Create next of other kind
"; - private JComponent overlay = null; - private JComponent helpWindow = null; + private JComponent overlay = null; + private JComponent helpWindow = null; private Display view; - + final private WriterModeData data; - private WriterNode selected; - private WriterNode prevSelected = null; - + private WriterNode selected; + private WriterNode prevSelected = null; + public WriterModeEditor(WriterModeData data) { - this.target = data; - this.data = data; - this.name = data.id; - this.icon = new ImageIcon(DefaultIcons.getDialogueIcon()); - selected = data.begin; - view = new WriterGraphView(); - view.setLocation(0, 0); - - setLayout(new BorderLayout()); - add(createButtonPane(), BorderLayout.NORTH); - add(view, BorderLayout.CENTER); + this.target = data; + this.data = data; + this.name = data.id; + this.icon = new ImageIcon(DefaultIcons.getDialogueIcon()); + selected = data.begin; + view = new WriterGraphView(); + view.setLocation(0, 0); + + setLayout(new BorderLayout()); + add(createButtonPane(), BorderLayout.NORTH); + add(view, BorderLayout.CENTER); } - - + + public void dataAltered() { - data.state = GameDataElement.State.modified; - data.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(this); + data.state = GameDataElement.State.modified; + data.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(this); } - + public JPanel createButtonPane() { - JPanel pane = new JPanel(); - pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.LINE_AXIS)); - JButton save = new JButton("Save sketch"); - JButton export = new JButton("Export sketch to game data"); - save.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - data.save(); - data.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(WriterModeEditor.this); - } - }); - export.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - List created = data.toDialogue(); - data.getProject().createElements(created); - //data.begin.dialogue.save(); - data.save(); - data.childrenChanged(new ArrayList()); - ATContentStudio.frame.editorChanged(WriterModeEditor.this); - } - }); - pane.add(save, JideBoxLayout.FIX); - pane.add(export, JideBoxLayout.FIX); - pane.add(new JPanel(), JideBoxLayout.VARY); - return pane; + JPanel pane = new JPanel(); + pane.setLayout(new JideBoxLayout(pane, JideBoxLayout.LINE_AXIS)); + JButton save = new JButton("Save sketch"); + JButton export = new JButton("Export sketch to game data"); + save.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + data.save(); + data.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(WriterModeEditor.this); + } + }); + export.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + List created = data.toDialogue(); + data.getProject().createElements(created); + //data.begin.dialogue.save(); + data.save(); + data.childrenChanged(new ArrayList()); + ATContentStudio.frame.editorChanged(WriterModeEditor.this); + } + }); + pane.add(save, JideBoxLayout.FIX); + pane.add(export, JideBoxLayout.FIX); + pane.add(new JPanel(), JideBoxLayout.VARY); + return pane; } - - - - - - - - - + + private void disposeOverlay() { - if (overlay != null) view.remove(overlay); - overlay = null; - view.requestFocus(); - view.revalidate(); + if (overlay != null) view.remove(overlay); + overlay = null; + view.requestFocus(); + view.revalidate(); } private void createHelpWindow() { - JInternalFrame window = new JInternalFrame("Help", true, true); - window.setLayout(new BorderLayout()); - JEditorPane area = new JEditorPane(); - area.setContentType("text/html"); - area.setText(HELP_TEXT); - area.setEditable(false); - - window.add(new JScrollPane(area)); - window.setSize(350, 250); - window.setLocation(0, 0); - - view.add(window); - helpWindow = window; + JInternalFrame window = new JInternalFrame("Help", true, true); + window.setLayout(new BorderLayout()); + JEditorPane area = new JEditorPane(); + area.setContentType("text/html"); + area.setText(HELP_TEXT); + area.setEditable(false); + + window.add(new JScrollPane(area)); + window.setSize(350, 250); + window.setLocation(0, 0); + + view.add(window); + helpWindow = window; } - - public static final String GRAPH = "graph"; + + public static final String GRAPH = "graph"; public static final String NODES = "graph.nodes"; public static final String NULL_NODES = "graph.nullNodes"; public static final String EDGES = "graph.edges"; public static final String EDGES_LABELS = "edgesLabels"; - + public static final String LABEL = "label"; public static final String ICON = "icon"; public static final String TARGET = "target"; - + public static final String IS_REPLY = "reply"; public static final String THREAD_START = "threadStart"; public static final String SELECTED = "selected"; public static final String IS_TREE_EDGE = "isTreeEdge"; - - private static final Schema DECORATOR_SCHEMA = PrefuseLib.getVisualItemSchema(); - + + private static final Schema DECORATOR_SCHEMA = PrefuseLib.getVisualItemSchema(); + private class WriterGraphView extends Display { - private static final long serialVersionUID = -7992763190713052045L; + private static final long serialVersionUID = -7992763190713052045L; - private MyGraph graph; - private Map cells = new LinkedHashMap(); - - private Node nullNode = null; - private Edge pendingEdge = null; - private boolean edgePending = false; - - public WriterGraphView() { - super(new Visualization()); - loadGraph(); - nullNode = graph.addNode(); - nullNode.setBoolean(NULL_NODES, true); + private MyGraph graph; + private Map cells = new LinkedHashMap(); - // add visual data groups + private Node nullNode = null; + private Edge pendingEdge = null; + private boolean edgePending = false; + + public WriterGraphView() { + super(new Visualization()); + loadGraph(); + nullNode = graph.addNode(); + nullNode.setBoolean(NULL_NODES, true); + + // add visual data groups m_vis.addGraph(GRAPH, graph); m_vis.setInteractive(EDGES, null, false); - + LabelRenderer nodeR = new MyLabelRenderer(LABEL); nodeR.setHorizontalTextAlignment(prefuse.Constants.LEFT); - + EdgeRenderer edgeR = new EdgeRenderer(prefuse.Constants.EDGE_TYPE_LINE, prefuse.Constants.EDGE_ARROW_FORWARD); - + LabelRenderer edgeLabelR = new LabelRenderer(LABEL); edgeLabelR.setRenderType(LabelRenderer.RENDER_TYPE_DRAW); - + DefaultRendererFactory drf = new DefaultRendererFactory(); drf.setDefaultRenderer(nodeR); drf.setDefaultEdgeRenderer(edgeR); @@ -234,14 +199,14 @@ public class WriterModeEditor extends Editor { DECORATOR_SCHEMA.setDefault(VisualItem.STROKECOLOR, ColorLib.rgba(0, 0, 0, 0)); DECORATOR_SCHEMA.setDefault(VisualItem.TEXTCOLOR, ColorLib.gray(0)); m_vis.addDecorators(EDGES_LABELS, EDGES, DECORATOR_SCHEMA); - - // set up the visual operators + + // set up the visual operators // first set up all the color actions ColorAction nStrokeColor = new NodeStrokeColorAction(NODES, VisualItem.STROKECOLOR); // nStrokeColor.setDefaultColor(ColorLib.gray(100)); // nStrokeColor.add("_hover", ColorLib.rgb(255,100,100)); StrokeAction nStroke = new StrokeAction(NODES); - + ColorAction nFill = new ColorAction(NODES, VisualItem.FILLCOLOR); nFill.setDefaultColor(ColorLib.gray(255)); // ColorAction nFill = new NPCPhraseColorAction(NODES, VisualItem.FILLCOLOR); @@ -251,14 +216,14 @@ public class WriterModeEditor extends Editor { ColorAction eArrows = new ConnectedEdgeColorAction(EDGES, VisualItem.FILLCOLOR); // eArrows.setDefaultColor(ColorLib.gray(100)); // ColorAction eEdgesLabels = new ConnectedEdgeColorAction(EDGES_LABELS, VisualItem.TEXTCOLOR); - + // StrokeAction eStroke = new EdgesStrokeAction(EDGES); - + FontAction aFont = new FontAction(); ColorAction aFontColor = new ColorAction(NODES, VisualItem.TEXTCOLOR); aFontColor.setDefaultColor(ColorLib.rgb(0, 0, 0)); - - // bundle the color actions + + // bundle the color actions ActionList colors = new ActionList(Activity.INFINITY); colors.add(nStrokeColor); colors.add(nFill); @@ -271,30 +236,30 @@ public class WriterModeEditor extends Editor { colors.add(aFontColor); colors.add(new RepaintAction()); m_vis.putAction("colors", colors); - + // now create the main layout routine ActionList layout = new ActionList();//Activity.INFINITY); NodeLinkTreeLayout treeLayout = new NodeLinkTreeLayout(GRAPH, prefuse.Constants.ORIENT_LEFT_RIGHT, 120, 40, 40); - treeLayout.setLayoutAnchor(new Point2D.Double(25,300)); + treeLayout.setLayoutAnchor(new Point2D.Double(25, 300)); layout.add(treeLayout); // layout.add(new EdgesLabelDecoratorLayout(EDGES_LABELS)); layout.add(new RepaintAction()); m_vis.putAction("layout", layout); - + ActionList scrollToSelectedList = new ActionList(); Action scrollToSelected = new ScrollToSelectedAction(false); scrollToSelectedList.add(scrollToSelected); m_vis.putAction("scrollToSelected", scrollToSelectedList); - + ActionList scrollToSelectedAndEditList = new ActionList(); Action scrollToSelectedAndEdit = new ScrollToSelectedAction(true); scrollToSelectedAndEditList.add(scrollToSelectedAndEdit); m_vis.putAction("scrollToSelectedAndEdit", scrollToSelectedAndEditList); - - + + // set up the display - setSize(500,500); + setSize(500, 500); pan(250, 250); setHighQuality(true); // addControlListener(new TooltipControl()); @@ -302,591 +267,602 @@ public class WriterModeEditor extends Editor { addControlListener(new WheelZoomControl()); addControlListener(new ZoomControl()); addControlListener(new PanControl()); - + // set things running m_vis.run("colors"); m_vis.run("layout"); m_vis.run("scrollToSelected"); - + setFocusTraversalKeysEnabled(false); - } - - public void loadGraph() { - graph = new MyGraph(true, IS_TREE_EDGE); - - graph.addColumn(LABEL, String.class, ""); - graph.addColumn(ICON, Image.class, DefaultIcons.getNullifyIcon()); - graph.addColumn(TARGET, WriterModeData.WriterNode.class, null); - - graph.addColumn(IS_REPLY, boolean.class, false); - graph.addColumn(THREAD_START, boolean.class, false); - graph.addColumn(SELECTED, boolean.class, false); - graph.addColumn(IS_TREE_EDGE, boolean.class, true); - graph.addColumn(NULL_NODES, boolean.class, false); - - if (data != null && data.begin != null) { - selected = data.begin; - addDialogueNode(data.begin); - } - } - - public Node addDialogueNode(WriterModeData.WriterDialogue dialogue) { - if (cells.get(dialogue) == null) { - Node dNode = graph.addNode(); - cells.put(dialogue, dNode); - dNode.setString(LABEL, dialogue.text); - dNode.set(TARGET, dialogue); - - if (dialogue.index == 0) { - dNode.setBoolean(THREAD_START, true); - } - - Node rNode; + } + + public void loadGraph() { + graph = new MyGraph(true, IS_TREE_EDGE); + + graph.addColumn(LABEL, String.class, ""); + graph.addColumn(ICON, Image.class, DefaultIcons.getNullifyIcon()); + graph.addColumn(TARGET, WriterModeData.WriterNode.class, null); + + graph.addColumn(IS_REPLY, boolean.class, false); + graph.addColumn(THREAD_START, boolean.class, false); + graph.addColumn(SELECTED, boolean.class, false); + graph.addColumn(IS_TREE_EDGE, boolean.class, true); + graph.addColumn(NULL_NODES, boolean.class, false); + + if (data != null && data.begin != null) { + selected = data.begin; + addDialogueNode(data.begin); + } + } + + public Node addDialogueNode(WriterModeData.WriterDialogue dialogue) { + if (cells.get(dialogue) == null) { + Node dNode = graph.addNode(); + cells.put(dialogue, dNode); + dNode.setString(LABEL, dialogue.text); + dNode.set(TARGET, dialogue); + + if (dialogue.index == 0) { + dNode.setBoolean(THREAD_START, true); + } + + Node rNode; // int i = 1; - for (WriterModeData.WriterReply reply : dialogue.replies) { - if (reply instanceof EmptyReply && reply.next_dialogue != null) { - if (cells.get(reply.next_dialogue) == null) { - rNode = addDialogueNode(reply.next_dialogue); - /*Edge e = */graph.addEdge(dNode, rNode); - } else { - rNode = cells.get(reply.next_dialogue); - Edge e = graph.addEdge(dNode, rNode); - e.setBoolean(IS_TREE_EDGE, false); - } - } else { - if (cells.get(reply) == null) { - rNode = addReplyNode(reply); - /*Edge e = */graph.addEdge(dNode, rNode); + for (WriterModeData.WriterReply reply : dialogue.replies) { + if (reply instanceof EmptyReply && reply.next_dialogue != null) { + if (cells.get(reply.next_dialogue) == null) { + rNode = addDialogueNode(reply.next_dialogue); + /*Edge e = */ + graph.addEdge(dNode, rNode); + } else { + rNode = cells.get(reply.next_dialogue); + Edge e = graph.addEdge(dNode, rNode); + e.setBoolean(IS_TREE_EDGE, false); + } + } else { + if (cells.get(reply) == null) { + rNode = addReplyNode(reply); + /*Edge e = */ + graph.addEdge(dNode, rNode); // e.setString(LABEL, "#"+i++); - } else { - rNode = cells.get(reply); - Edge e = graph.addEdge(dNode, rNode); - e.setBoolean(IS_TREE_EDGE, false); - } - } - } - } - return cells.get(dialogue); - } - - public Node addReplyNode(WriterModeData.WriterReply reply) { - if (cells.get(reply) == null) { - Node rNode = graph.addNode(); - rNode.setBoolean(IS_REPLY, true); - cells.put(reply, rNode); - if (reply.text != null) { - rNode.setString(LABEL, reply.text); - rNode.set(TARGET, reply); + } else { + rNode = cells.get(reply); + Edge e = graph.addEdge(dNode, rNode); + e.setBoolean(IS_TREE_EDGE, false); + } + } + } + } + return cells.get(dialogue); + } - if (reply.next_dialogue != null) { - if (cells.get(reply.next_dialogue) == null) { - Node dNode = addDialogueNode(reply.next_dialogue); - /*Edge e = */graph.addEdge(rNode, dNode); - } else { - Node dNode = cells.get(reply.next_dialogue); - Edge e = graph.addEdge(rNode, dNode); - e.setBoolean(IS_TREE_EDGE, false); - } - } - } - } - return cells.get(reply); - } - - public void addEdge(WriterNode source, WriterNode target) { - if (graph.getEdge(cells.get(source), cells.get(target)) != null) return; - Edge e = graph.addEdge(cells.get(source), cells.get(target)); - e.setBoolean(IS_TREE_EDGE, false); - m_vis.run("colors"); + public Node addReplyNode(WriterModeData.WriterReply reply) { + if (cells.get(reply) == null) { + Node rNode = graph.addNode(); + rNode.setBoolean(IS_REPLY, true); + cells.put(reply, rNode); + if (reply.text != null) { + rNode.setString(LABEL, reply.text); + rNode.set(TARGET, reply); + + if (reply.next_dialogue != null) { + if (cells.get(reply.next_dialogue) == null) { + Node dNode = addDialogueNode(reply.next_dialogue); + /*Edge e = */ + graph.addEdge(rNode, dNode); + } else { + Node dNode = cells.get(reply.next_dialogue); + Edge e = graph.addEdge(rNode, dNode); + e.setBoolean(IS_TREE_EDGE, false); + } + } + } + } + return cells.get(reply); + } + + public void addEdge(WriterNode source, WriterNode target) { + if (graph.getEdge(cells.get(source), cells.get(target)) != null) return; + Edge e = graph.addEdge(cells.get(source), cells.get(target)); + e.setBoolean(IS_TREE_EDGE, false); + m_vis.run("colors"); m_vis.run("layout"); - - } - - - class MyLabelRenderer extends LabelRenderer { - public MyLabelRenderer(String label) { - super(label); - } - @Override - protected Image getImage(VisualItem item) { - return item.getBoolean(IS_REPLY) ? DefaultIcons.getHeroIcon() : DefaultIcons.getNPCIcon(); - } - - @Override - protected String getText(VisualItem item) { - if (!item.getBoolean(IS_REPLY) && super.getText(item) == null) return "[Selector]"; - return TextUtils.wordWrap(super.getText(item), 40); - } - } - - class NodeStrokeColorAction extends ColorAction { - - final int defaultColor = ColorLib.gray(100); - final int hoverColor = ColorLib.rgb(255,100,100); - final int selectedColor = ColorLib.rgb(100,100,255); - - public NodeStrokeColorAction(String group, String field) { - super(group, field); - } - - @Override - public int getColor(VisualItem item) { - if (item.get(TARGET) != null && item.get(TARGET) == selected) { - return selectedColor; - } - if (item.isHover()) { - return hoverColor; - } - return defaultColor; - } - } - - class ConnectedEdgeColorAction extends ColorAction { + } - final int outgoing = ColorLib.rgb(255, 100, 100); - final int incoming = ColorLib.rgb(100, 255, 100); - final int none = ColorLib.gray(100); - - public ConnectedEdgeColorAction(String group, String field) { - super(group, field); - } - - @Override - public int getColor(VisualItem item) { - if (item instanceof DecoratorItem) { - item = ((DecoratorItem) item).getDecoratedItem(); - } - if (item instanceof EdgeItem) { - if (((EdgeItem) item).getSourceItem() != null && ((EdgeItem) item).getSourceItem().isHover()) { - return outgoing; - } else if (((EdgeItem) item).getTargetItem().isHover()) { - return incoming; - } - } - return none; - } - } - - class GraphInputControl extends ControlAdapter { - @Override - public void itemClicked(VisualItem item, MouseEvent e) { - if (edgePending) { - WriterNode target = (WriterNode) item.get(TARGET); - lockPendingEdge(target); - } else { - if (e.getClickCount() == 1) { - if (item.get(TARGET) != null) { - prevSelected = selected; - selected = (WriterNode)item.get(TARGET); - } - } else if (e.getClickCount() == 2) { - if (item.get(TARGET) != null) { - - showEditorOnSelectedAt(e.getPoint()); - } - } - } - } - - @Override - public void mouseClicked(MouseEvent e) { - selected = null; - view.requestFocus(); - } - - @Override - public void keyReleased(KeyEvent e) { - if (edgePending && e.getKeyCode() == KeyEvent.VK_SHIFT) { - stopPendingEdge(); - } - KeyStroke event = KeyStroke.getKeyStrokeForEvent(e); - if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true))) { - selectAndScroll(nextNodeUp(selected)); - } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true))) { - selectAndScroll(nextNodeDown(selected)); - } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true)) || event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK, true))) { - selectAndScroll(nextNodeLeft(selected)); - } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true)) || event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, true))) { - selectAndScroll(nextNodeRight(selected)); - } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true))) { - showEditorOnSelected(); - } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.ALT_DOWN_MASK, true))) { - createNextDefaultNode.actionPerformed(null); - } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true))) { - if (selected instanceof WriterDialogue) { - createContinueTalkingNode.actionPerformed(null); - } else if (selected instanceof WriterReply) { - createOtherReplyNode.actionPerformed(null); - } - } - } - - @Override - public void itemKeyReleased(VisualItem item, KeyEvent e) { - keyReleased(e); - } - - @Override - public void keyPressed(KeyEvent e) { - if (selected != null && e.getKeyCode() == KeyEvent.VK_SHIFT) { - startPendingEdge(); - } - } - - @Override - public void itemKeyPressed(VisualItem item, KeyEvent e) { - keyPressed(e); - } - - @Override - public void mouseMoved(MouseEvent e) { - if (edgePending) { - Point p = e.getPoint(); - Point2D p2 = getAbsoluteCoordinate(p, null); - m_vis.getVisualItem(NODES, nullNode).setX(p2.getX()); - m_vis.getVisualItem(NODES, nullNode).setY(p2.getY()); - m_vis.run("colors"); - revalidate(); - repaint(); - disposeOverlay(); - } - } - - @Override - public void itemMoved(VisualItem item, MouseEvent e) { - mouseMoved(e); - } - - } - + class MyLabelRenderer extends LabelRenderer { + public MyLabelRenderer(String label) { + super(label); + } - public void startPendingEdge() { - if (edgePending) return; - if (selected instanceof WriterDialogue || - (selected instanceof WriterReply && ((WriterReply)selected).next_dialogue == null )) { - pendingEdge = graph.addEdge(cells.get(selected), nullNode); - edgePending = true; - m_vis.run("colors"); - m_vis.run("layout"); - revalidate(); - repaint(); - } - } - + @Override + protected Image getImage(VisualItem item) { + return item.getBoolean(IS_REPLY) ? DefaultIcons.getHeroIcon() : DefaultIcons.getNPCIcon(); + } + + @Override + protected String getText(VisualItem item) { + if (!item.getBoolean(IS_REPLY) && super.getText(item) == null) return "[Selector]"; + return TextUtils.wordWrap(super.getText(item), 40); + } + } + + class NodeStrokeColorAction extends ColorAction { + + final int defaultColor = ColorLib.gray(100); + final int hoverColor = ColorLib.rgb(255, 100, 100); + final int selectedColor = ColorLib.rgb(100, 100, 255); + + public NodeStrokeColorAction(String group, String field) { + super(group, field); + } + + @Override + public int getColor(VisualItem item) { + if (item.get(TARGET) != null && item.get(TARGET) == selected) { + return selectedColor; + } + if (item.isHover()) { + return hoverColor; + } + return defaultColor; + } + } + + class ConnectedEdgeColorAction extends ColorAction { + + final int outgoing = ColorLib.rgb(255, 100, 100); + final int incoming = ColorLib.rgb(100, 255, 100); + final int none = ColorLib.gray(100); + + public ConnectedEdgeColorAction(String group, String field) { + super(group, field); + } + + @Override + public int getColor(VisualItem item) { + if (item instanceof DecoratorItem) { + item = ((DecoratorItem) item).getDecoratedItem(); + } + if (item instanceof EdgeItem) { + if (((EdgeItem) item).getSourceItem() != null && ((EdgeItem) item).getSourceItem().isHover()) { + return outgoing; + } else if (((EdgeItem) item).getTargetItem().isHover()) { + return incoming; + } + } + + return none; + } + } + + class GraphInputControl extends ControlAdapter { + @Override + public void itemClicked(VisualItem item, MouseEvent e) { + if (edgePending) { + WriterNode target = (WriterNode) item.get(TARGET); + lockPendingEdge(target); + } else { + if (e.getClickCount() == 1) { + if (item.get(TARGET) != null) { + prevSelected = selected; + selected = (WriterNode) item.get(TARGET); + } + } else if (e.getClickCount() == 2) { + if (item.get(TARGET) != null) { + + showEditorOnSelectedAt(e.getPoint()); + } + } + } + } + + @Override + public void mouseClicked(MouseEvent e) { + selected = null; + view.requestFocus(); + } + + @Override + public void keyReleased(KeyEvent e) { + if (edgePending && e.getKeyCode() == KeyEvent.VK_SHIFT) { + stopPendingEdge(); + } + KeyStroke event = KeyStroke.getKeyStrokeForEvent(e); + if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true))) { + selectAndScroll(nextNodeUp(selected)); + } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true))) { + selectAndScroll(nextNodeDown(selected)); + } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true)) || event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK, true))) { + selectAndScroll(nextNodeLeft(selected)); + } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true)) || event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, true))) { + selectAndScroll(nextNodeRight(selected)); + } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true))) { + showEditorOnSelected(); + } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.ALT_DOWN_MASK, true))) { + createNextDefaultNode.actionPerformed(null); + } else if (event.equals(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true))) { + if (selected instanceof WriterDialogue) { + createContinueTalkingNode.actionPerformed(null); + } else if (selected instanceof WriterReply) { + createOtherReplyNode.actionPerformed(null); + } + } + } + + @Override + public void itemKeyReleased(VisualItem item, KeyEvent e) { + keyReleased(e); + } + + @Override + public void keyPressed(KeyEvent e) { + if (selected != null && e.getKeyCode() == KeyEvent.VK_SHIFT) { + startPendingEdge(); + } + } + + @Override + public void itemKeyPressed(VisualItem item, KeyEvent e) { + keyPressed(e); + } + + @Override + public void mouseMoved(MouseEvent e) { + if (edgePending) { + Point p = e.getPoint(); + Point2D p2 = getAbsoluteCoordinate(p, null); + m_vis.getVisualItem(NODES, nullNode).setX(p2.getX()); + m_vis.getVisualItem(NODES, nullNode).setY(p2.getY()); + m_vis.run("colors"); + revalidate(); + repaint(); + disposeOverlay(); + } + } + + @Override + public void itemMoved(VisualItem item, MouseEvent e) { + mouseMoved(e); + } + + } + + + public void startPendingEdge() { + if (edgePending) return; + if (selected instanceof WriterDialogue || + (selected instanceof WriterReply && ((WriterReply) selected).next_dialogue == null)) { + pendingEdge = graph.addEdge(cells.get(selected), nullNode); + edgePending = true; + m_vis.run("colors"); + m_vis.run("layout"); + revalidate(); + repaint(); + } + } + + + public void stopPendingEdge() { + if (!edgePending) return; + graph.removeEdge(pendingEdge); + pendingEdge = null; + edgePending = false; + m_vis.run("colors"); + m_vis.run("layout"); + revalidate(); + repaint(); + } + + public void lockPendingEdge(WriterNode target) { + if (selected instanceof WriterReply) { + if (target instanceof WriterDialogue && ((WriterReply) selected).next_dialogue == null) { + ((WriterReply) selected).next_dialogue = (WriterDialogue) target; + stopPendingEdge(); + addEdge(selected, target); + } + } else if (selected instanceof WriterDialogue) { + if (target instanceof WriterReply) { + WriterReply clone = data.new WriterReply((WriterDialogue) selected); + clone.text = ((WriterReply) target).text; + if (((WriterReply) target).next_dialogue instanceof SpecialDialogue) { + clone.next_dialogue = ((SpecialDialogue) ((WriterReply) target).next_dialogue).duplicate(); + } else { + clone.next_dialogue = ((WriterReply) target).next_dialogue; + } + stopPendingEdge(); + addReplyNode(clone); + addEdge(selected, clone); + if (clone.next_dialogue != null) addEdge(clone, clone.next_dialogue); + } else if (target instanceof WriterDialogue) { + WriterReply empty = data.new EmptyReply((WriterDialogue) selected); + empty.next_dialogue = (WriterDialogue) target; + stopPendingEdge(); + addEdge(selected, target); + } + } + dataAltered(); + } - public void stopPendingEdge() { - if (!edgePending) return; - graph.removeEdge(pendingEdge); - pendingEdge = null; - edgePending = false; - m_vis.run("colors"); - m_vis.run("layout"); - revalidate(); - repaint(); - } - - public void lockPendingEdge(WriterNode target) { - if (selected instanceof WriterReply) { - if (target instanceof WriterDialogue && ((WriterReply)selected).next_dialogue == null) { - ((WriterReply)selected).next_dialogue = (WriterDialogue) target; - stopPendingEdge(); - addEdge(selected, target); - } - } else if (selected instanceof WriterDialogue) { - if (target instanceof WriterReply) { - WriterReply clone = data.new WriterReply((WriterDialogue)selected); - clone.text = ((WriterReply)target).text; - if (((WriterReply)target).next_dialogue instanceof SpecialDialogue) { - clone.next_dialogue = ((SpecialDialogue)((WriterReply)target).next_dialogue).duplicate(); - } else { - clone.next_dialogue = ((WriterReply)target).next_dialogue; - } - stopPendingEdge(); - addReplyNode(clone); - addEdge(selected, clone); - if (clone.next_dialogue != null) addEdge(clone, clone.next_dialogue); - } else if (target instanceof WriterDialogue) { - WriterReply empty = data.new EmptyReply((WriterDialogue)selected); - empty.next_dialogue = (WriterDialogue)target; - stopPendingEdge(); - addEdge(selected, target); - } - } - dataAltered(); - } - static final String disposeEditorString = "disposeEditor"; final AbstractAction disposeEditor = new AbstractAction("Dispose Editor") { - private static final long serialVersionUID = 6640035253411399809L; + private static final long serialVersionUID = 6640035253411399809L; + + @Override + public void actionPerformed(ActionEvent e) { + disposeOverlay(); + } + }; - @Override - public void actionPerformed(ActionEvent e) { - disposeOverlay(); - } - }; - static final String commitEditAndDisposeEditorString = "commitEditAndDisposeEditor"; final AbstractAction commitEditAndDisposeEditor = new AbstractAction("Commit Edit") { - private static final long serialVersionUID = 8039766217709796328L; + private static final long serialVersionUID = 8039766217709796328L; - @Override - public void actionPerformed(ActionEvent e) { - if (area == null) return; - commitAreaText(); - m_vis.run("colors"); - revalidate(); - repaint(); - disposeOverlay(); - dataAltered(); - } - }; - - private void commitAreaText() { - selected.text = area.getText(); - cells.get(selected).set(LABEL, selected.text); - } - -// static final String createNextDefaultNodeString = "createNextDefaultNode"; - final AbstractAction createNextDefaultNode = new AbstractAction("Create next default") { - private static final long serialVersionUID = 1658086056088672748L; - - @Override - public void actionPerformed(ActionEvent e) { - stopPendingEdge(); - if (selected == null) return; - WriterNode newWrNode = null; - Node newNode = null; - if (selected instanceof WriterDialogue) { - newWrNode = data.new WriterReply((WriterDialogue) selected); - newNode = addReplyNode(((WriterReply)newWrNode)); - } else if (selected instanceof WriterReply) { - if (((WriterReply)selected).next_dialogue != null) { - newWrNode = ((WriterReply)selected).next_dialogue; - newNode = cells.get(newWrNode); - } else { - newWrNode = data.new WriterDialogue(((WriterReply)selected).parent.id_prefix); - ((WriterReply)selected).next_dialogue = ((WriterDialogue)newWrNode); - newNode = addDialogueNode(((WriterDialogue)newWrNode)); - } - } - if (newNode!= null) { - /*Edge edge = */graph.addEdge(cells.get(selected), newNode); - setSelected(newWrNode); - - m_vis.run("colors"); - m_vis.run("layout"); - m_vis.run("scrollToSelectedAndEdit"); - - revalidate(); - repaint(); - } - dataAltered(); - } - }; - - static final String commitAndCreateNextDefaultNodeString = "commitAndCreateNextDefaultNode"; - final AbstractAction commitAndCreateNextDefaultNode = new AbstractAction("Commit And Create next default") { - private static final long serialVersionUID = 1658086056088672748L; - - @Override - public void actionPerformed(ActionEvent e) { - commitAreaText(); - stopPendingEdge(); - createNextDefaultNode.actionPerformed(e); - } - }; - - - static final String createContinueTalkingNodeString = "createContinueTalkingNode"; - final AbstractAction createContinueTalkingNode = new AbstractAction("Create next phrase without reply") { - private static final long serialVersionUID = 1658086056088672748L; - - @Override - public void actionPerformed(ActionEvent e) { - commitAreaText(); - stopPendingEdge(); - WriterDialogue newWrNode; - Node newNode; - if (selected instanceof WriterDialogue) { - EmptyReply temp = data.new EmptyReply((WriterDialogue) selected); - newWrNode = data.new WriterDialogue(((WriterDialogue) selected).id_prefix); - temp.next_dialogue = newWrNode; - - newNode = addDialogueNode(newWrNode); - /*Edge edge = */graph.addEdge(cells.get(selected), newNode); - setSelected(newWrNode); - - m_vis.run("colors"); - m_vis.run("layout"); - m_vis.run("scrollToSelectedAndEdit"); - revalidate(); - repaint(); - } - dataAltered(); - } - }; - - static final String createOtherReplyNodeString = "createOtherReplyNode"; - final AbstractAction createOtherReplyNode = new AbstractAction("Create another reply with the same parent") { - private static final long serialVersionUID = 1658086056088672748L; - - @Override - public void actionPerformed(ActionEvent e) { - commitAreaText(); - stopPendingEdge(); - WriterReply newWrNode; - Node newNode; - if (selected instanceof WriterReply) { - newWrNode = data.new WriterReply(((WriterReply) selected).parent); - newNode = addReplyNode(newWrNode); - /*Edge edge = */graph.addEdge(cells.get(((WriterReply) selected).parent), newNode); - setSelected(newWrNode); - - m_vis.run("colors"); - m_vis.run("layout"); - m_vis.run("scrollToSelectedAndEdit"); - revalidate(); - repaint(); - } - dataAltered(); - } - }; - - static final String showHelpString = "showHelp"; - final AbstractAction showHelp = new AbstractAction("Show help window") { - private static final long serialVersionUID = 1658086056088672748L; - - @Override - public void actionPerformed(ActionEvent e) { - if (helpWindow == null) { - createHelpWindow(); - } - helpWindow.setVisible(true); - } - }; - - class ScrollToSelectedAction extends Action { - - final boolean openEditor; - - public ScrollToSelectedAction(boolean openEditor) { - super(); - this.openEditor = openEditor; - } - - @Override - public void run(double frac) { - new Thread() { - @Override - public void run() { - if (selected == null) return; - VisualItem newItem = WriterGraphView.this.m_vis.getVisualItem(NODES, cells.get(selected)); - if (prevSelected != null) { - VisualItem prevItem = m_vis.getVisualItem(NODES, cells.get(prevSelected)); - Point2D target = getScreenCoordinates(new Point2D.Double(prevItem.getX(), prevItem.getY()), null); - animatePan(prevItem.getX() - newItem.getX(), prevItem.getY() - newItem.getY(), 200); - if (openEditor)showEditorOnSelectedAt(target); - } else { - animatePanToAbs(new Point2D.Double(newItem.getX(), newItem.getY()), 200); - } - } - }.start(); - } - }; - - - private void showEditorOnSelected() { - if (selected == null) return; - Node selNode = cells.get(selected); - if (selNode != null) { - VisualItem vItem = m_vis.getVisualItem(NODES, selNode); - if (vItem != null) { - showEditorOnSelectedAt(getScreenCoordinates(new Point2D.Double(vItem.getX(), vItem.getY()),null)); - } - } - } - - JTextArea area; - private void showEditorOnSelectedAt(final Point2D p) { - if (overlay != null) disposeOverlay(); - - //System.out.println(p); - area = new JTextArea(selected.text); - JInternalFrame frame = new JInternalFrame(selected.getTitle(), true); - frame.getContentPane().setLayout(new BorderLayout()); - JPanel pane = new JPanel(); - pane.setLayout(new BorderLayout()); - pane.add(new JScrollPane(area)); - frame.setSize(250, 80); - frame.setLocation(new Point((int)p.getX(), (int)p.getY())); - frame.setVisible(true); - frame.getContentPane().add(pane, BorderLayout.CENTER); - ((BasicInternalFrameUI)frame.getUI()).getNorthPane().remove(0); - - JButton commit = new JButton(commitEditAndDisposeEditor); - commit.setToolTipText("Save text and close editor (Ctrl + Enter)"); - - JButton cancel = new JButton(disposeEditor); - cancel.setToolTipText("Discard changes and close editor (Escape)"); - - - view.add(frame); - overlay = frame; - frame.requestFocus(); - area.requestFocus(); - area.addFocusListener(new FocusListener() { - @Override - public void focusLost(FocusEvent e) { - disposeOverlay(); - } - @Override - public void focusGained(FocusEvent e) {} - }); - - area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), disposeEditorString); - area.getActionMap().put(disposeEditorString, disposeEditor); - - area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK, true), commitEditAndDisposeEditorString); - area.getActionMap().put(commitEditAndDisposeEditorString, commitEditAndDisposeEditor); - - area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.ALT_DOWN_MASK, true), commitAndCreateNextDefaultNodeString); - area.getActionMap().put(commitAndCreateNextDefaultNodeString, commitAndCreateNextDefaultNode); - - area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, true), showHelpString); - area.getActionMap().put(showHelpString, showHelp); - - if (selected instanceof WriterDialogue) { - area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true), createContinueTalkingNodeString); - area.getActionMap().put(createContinueTalkingNodeString, createContinueTalkingNode); - } else if (selected instanceof WriterReply) { - area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true), createOtherReplyNodeString); - area.getActionMap().put(createOtherReplyNodeString, createOtherReplyNode); + @Override + public void actionPerformed(ActionEvent e) { + if (area == null) return; + commitAreaText(); + m_vis.run("colors"); + revalidate(); + repaint(); + disposeOverlay(); + dataAltered(); } - + }; + + private void commitAreaText() { + selected.text = area.getText(); + cells.get(selected).set(LABEL, selected.text); } - - + + // static final String createNextDefaultNodeString = "createNextDefaultNode"; + final AbstractAction createNextDefaultNode = new AbstractAction("Create next default") { + private static final long serialVersionUID = 1658086056088672748L; + + @Override + public void actionPerformed(ActionEvent e) { + stopPendingEdge(); + if (selected == null) return; + WriterNode newWrNode = null; + Node newNode = null; + if (selected instanceof WriterDialogue) { + newWrNode = data.new WriterReply((WriterDialogue) selected); + newNode = addReplyNode(((WriterReply) newWrNode)); + } else if (selected instanceof WriterReply) { + if (((WriterReply) selected).next_dialogue != null) { + newWrNode = ((WriterReply) selected).next_dialogue; + newNode = cells.get(newWrNode); + } else { + newWrNode = data.new WriterDialogue(((WriterReply) selected).parent.id_prefix); + ((WriterReply) selected).next_dialogue = ((WriterDialogue) newWrNode); + newNode = addDialogueNode(((WriterDialogue) newWrNode)); + } + } + if (newNode != null) { + /*Edge edge = */ + graph.addEdge(cells.get(selected), newNode); + setSelected(newWrNode); + + m_vis.run("colors"); + m_vis.run("layout"); + m_vis.run("scrollToSelectedAndEdit"); + + revalidate(); + repaint(); + } + dataAltered(); + } + }; + + static final String commitAndCreateNextDefaultNodeString = "commitAndCreateNextDefaultNode"; + final AbstractAction commitAndCreateNextDefaultNode = new AbstractAction("Commit And Create next default") { + private static final long serialVersionUID = 1658086056088672748L; + + @Override + public void actionPerformed(ActionEvent e) { + commitAreaText(); + stopPendingEdge(); + createNextDefaultNode.actionPerformed(e); + } + }; + + + static final String createContinueTalkingNodeString = "createContinueTalkingNode"; + final AbstractAction createContinueTalkingNode = new AbstractAction("Create next phrase without reply") { + private static final long serialVersionUID = 1658086056088672748L; + + @Override + public void actionPerformed(ActionEvent e) { + commitAreaText(); + stopPendingEdge(); + WriterDialogue newWrNode; + Node newNode; + if (selected instanceof WriterDialogue) { + EmptyReply temp = data.new EmptyReply((WriterDialogue) selected); + newWrNode = data.new WriterDialogue(((WriterDialogue) selected).id_prefix); + temp.next_dialogue = newWrNode; + + newNode = addDialogueNode(newWrNode); + /*Edge edge = */ + graph.addEdge(cells.get(selected), newNode); + setSelected(newWrNode); + + m_vis.run("colors"); + m_vis.run("layout"); + m_vis.run("scrollToSelectedAndEdit"); + revalidate(); + repaint(); + } + dataAltered(); + } + }; + + static final String createOtherReplyNodeString = "createOtherReplyNode"; + final AbstractAction createOtherReplyNode = new AbstractAction("Create another reply with the same parent") { + private static final long serialVersionUID = 1658086056088672748L; + + @Override + public void actionPerformed(ActionEvent e) { + commitAreaText(); + stopPendingEdge(); + WriterReply newWrNode; + Node newNode; + if (selected instanceof WriterReply) { + newWrNode = data.new WriterReply(((WriterReply) selected).parent); + newNode = addReplyNode(newWrNode); + /*Edge edge = */ + graph.addEdge(cells.get(((WriterReply) selected).parent), newNode); + setSelected(newWrNode); + + m_vis.run("colors"); + m_vis.run("layout"); + m_vis.run("scrollToSelectedAndEdit"); + revalidate(); + repaint(); + } + dataAltered(); + } + }; + + static final String showHelpString = "showHelp"; + final AbstractAction showHelp = new AbstractAction("Show help window") { + private static final long serialVersionUID = 1658086056088672748L; + + @Override + public void actionPerformed(ActionEvent e) { + if (helpWindow == null) { + createHelpWindow(); + } + helpWindow.setVisible(true); + } + }; + + class ScrollToSelectedAction extends Action { + + final boolean openEditor; + + public ScrollToSelectedAction(boolean openEditor) { + super(); + this.openEditor = openEditor; + } + + @Override + public void run(double frac) { + new Thread() { + @Override + public void run() { + if (selected == null) return; + VisualItem newItem = WriterGraphView.this.m_vis.getVisualItem(NODES, cells.get(selected)); + if (prevSelected != null) { + VisualItem prevItem = m_vis.getVisualItem(NODES, cells.get(prevSelected)); + Point2D target = getScreenCoordinates(new Point2D.Double(prevItem.getX(), prevItem.getY()), null); + animatePan(prevItem.getX() - newItem.getX(), prevItem.getY() - newItem.getY(), 200); + if (openEditor) showEditorOnSelectedAt(target); + } else { + animatePanToAbs(new Point2D.Double(newItem.getX(), newItem.getY()), 200); + } + } + }.start(); + } + } + + ; + + + private void showEditorOnSelected() { + if (selected == null) return; + Node selNode = cells.get(selected); + if (selNode != null) { + VisualItem vItem = m_vis.getVisualItem(NODES, selNode); + if (vItem != null) { + showEditorOnSelectedAt(getScreenCoordinates(new Point2D.Double(vItem.getX(), vItem.getY()), null)); + } + } + } + + JTextArea area; + + private void showEditorOnSelectedAt(final Point2D p) { + if (overlay != null) disposeOverlay(); + + //System.out.println(p); + area = new JTextArea(selected.text); + JInternalFrame frame = new JInternalFrame(selected.getTitle(), true); + frame.getContentPane().setLayout(new BorderLayout()); + JPanel pane = new JPanel(); + pane.setLayout(new BorderLayout()); + pane.add(new JScrollPane(area)); + frame.setSize(250, 80); + frame.setLocation(new Point((int) p.getX(), (int) p.getY())); + frame.setVisible(true); + frame.getContentPane().add(pane, BorderLayout.CENTER); + ((BasicInternalFrameUI) frame.getUI()).getNorthPane().remove(0); + + JButton commit = new JButton(commitEditAndDisposeEditor); + commit.setToolTipText("Save text and close editor (Ctrl + Enter)"); + + JButton cancel = new JButton(disposeEditor); + cancel.setToolTipText("Discard changes and close editor (Escape)"); + + + view.add(frame); + overlay = frame; + frame.requestFocus(); + area.requestFocus(); + area.addFocusListener(new FocusListener() { + @Override + public void focusLost(FocusEvent e) { + disposeOverlay(); + } + + @Override + public void focusGained(FocusEvent e) { + } + }); + + area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), disposeEditorString); + area.getActionMap().put(disposeEditorString, disposeEditor); + + area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK, true), commitEditAndDisposeEditorString); + area.getActionMap().put(commitEditAndDisposeEditorString, commitEditAndDisposeEditor); + + area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.ALT_DOWN_MASK, true), commitAndCreateNextDefaultNodeString); + area.getActionMap().put(commitAndCreateNextDefaultNodeString, commitAndCreateNextDefaultNode); + + area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0, true), showHelpString); + area.getActionMap().put(showHelpString, showHelp); + + if (selected instanceof WriterDialogue) { + area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true), createContinueTalkingNodeString); + area.getActionMap().put(createContinueTalkingNodeString, createContinueTalkingNode); + } else if (selected instanceof WriterReply) { + area.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true), createOtherReplyNodeString); + area.getActionMap().put(createOtherReplyNodeString, createOtherReplyNode); + } + + } + + public void setSelected(WriterNode wrNode) { - prevSelected = selected; - selected = wrNode; - } - + prevSelected = selected; + selected = wrNode; + } + public void selectAndScroll(WriterNode node) { - if (node != null) { - setSelected(node); + if (node != null) { + setSelected(node); - m_vis.run("colors"); - m_vis.run("layout"); - m_vis.run("scrollToSelected"); + m_vis.run("colors"); + m_vis.run("layout"); + m_vis.run("scrollToSelected"); + + revalidate(); + repaint(); + } + } - revalidate(); - repaint(); - } - } - // public void selectScrollAndEdit(WriterNode node) { // if (node != null) { // setSelected(node); @@ -899,145 +875,140 @@ public class WriterModeEditor extends Editor { // repaint(); // } // } - - - + + public WriterNode nextNodeRight(WriterNode wrNode) { - Node node = cells.get(wrNode); - Node nextNode = graph.getFirstTreeChild(node); - return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); + Node node = cells.get(wrNode); + Node nextNode = graph.getFirstTreeChild(node); + return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); } - + public WriterNode nextNodeLeft(WriterNode wrNode) { - Node node = cells.get(wrNode); - Node nextNode = graph.getTreeParent(node); - return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); + Node node = cells.get(wrNode); + Node nextNode = graph.getTreeParent(node); + return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); } - + public WriterNode nextNodeUp(WriterNode wrNode) { - if (wrNode == null) return null; - Node node = cells.get(wrNode); - Node nextNode = graph.getPreviousTreeSibling(node); - if (nextNode == null) nextNode = findPreviousSiblingWithLastChildAtDepth(node, 0); - return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); + if (wrNode == null) return null; + Node node = cells.get(wrNode); + Node nextNode = graph.getPreviousTreeSibling(node); + if (nextNode == null) nextNode = findPreviousSiblingWithLastChildAtDepth(node, 0); + return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); } - - + + private Node findPreviousSiblingWithLastChildAtDepth(Node node, int depth) { - if (graph.getTreeParent(node) == null) return null; - Node prevSibl = graph.getPreviousTreeSibling(node); - if (prevSibl != null) { - Node candidate = findLastChildAtDepth(prevSibl, depth); - return candidate != null ? candidate : findPreviousSiblingWithLastChildAtDepth(prevSibl, depth); - } else { - return findPreviousSiblingWithLastChildAtDepth(graph.getTreeParent(node), depth + 1); - } + if (graph.getTreeParent(node) == null) return null; + Node prevSibl = graph.getPreviousTreeSibling(node); + if (prevSibl != null) { + Node candidate = findLastChildAtDepth(prevSibl, depth); + return candidate != null ? candidate : findPreviousSiblingWithLastChildAtDepth(prevSibl, depth); + } else { + return findPreviousSiblingWithLastChildAtDepth(graph.getTreeParent(node), depth + 1); + } } - + private Node findLastChildAtDepth(Node node, int depth) { - if (depth == 0) return node; - if (graph.getLastTreeChild(node) != null) return findLastChildAtDepth(graph.getLastTreeChild(node), depth - 1); - return findPreviousSiblingWithLastChildAtDepth(node, depth); + if (depth == 0) return node; + if (graph.getLastTreeChild(node) != null) + return findLastChildAtDepth(graph.getLastTreeChild(node), depth - 1); + return findPreviousSiblingWithLastChildAtDepth(node, depth); } - - - + + public WriterNode nextNodeDown(WriterNode wrNode) { - if (wrNode == null) return null; - Node node = cells.get(wrNode); - Node nextNode = graph.getNextTreeSibling(node); - if (nextNode == null) nextNode = findNextSiblingWithLastChildAtDepth(node, 0); - return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); + if (wrNode == null) return null; + Node node = cells.get(wrNode); + Node nextNode = graph.getNextTreeSibling(node); + if (nextNode == null) nextNode = findNextSiblingWithLastChildAtDepth(node, 0); + return nextNode == null ? null : (WriterNode) nextNode.get(TARGET); } - - + + private Node findNextSiblingWithLastChildAtDepth(Node node, int depth) { - if (graph.getTreeParent(node) == null) return null; - Node nextSibl = graph.getNextTreeSibling(node); - if (nextSibl != null) { - Node candidate = findFirstChildAtDepth(nextSibl, depth); - return candidate != null ? candidate : findNextSiblingWithLastChildAtDepth(nextSibl, depth); - } else { - return findNextSiblingWithLastChildAtDepth(graph.getTreeParent(node), depth + 1); - } + if (graph.getTreeParent(node) == null) return null; + Node nextSibl = graph.getNextTreeSibling(node); + if (nextSibl != null) { + Node candidate = findFirstChildAtDepth(nextSibl, depth); + return candidate != null ? candidate : findNextSiblingWithLastChildAtDepth(nextSibl, depth); + } else { + return findNextSiblingWithLastChildAtDepth(graph.getTreeParent(node), depth + 1); + } } - + private Node findFirstChildAtDepth(Node node, int depth) { - if (depth == 0) return node; - if (graph.getFirstTreeChild(node) != null) return findFirstChildAtDepth(graph.getFirstTreeChild(node), depth - 1); - return findNextSiblingWithLastChildAtDepth(node, depth); + if (depth == 0) return node; + if (graph.getFirstTreeChild(node) != null) + return findFirstChildAtDepth(graph.getFirstTreeChild(node), depth - 1); + return findNextSiblingWithLastChildAtDepth(node, depth); } - - - - - + + public Point2D getScreenCoordinates(Point2D abs, Point2D screen) { - return getTransform().transform(abs, screen); - } - - - - + return getTransform().transform(abs, screen); + } + + public class MyGraph extends Graph { - - - private String m_spanningTreeFilter; - private FilteredSpanningTree m_filteredSpanning = null; - - public MyGraph(boolean directed, String spanningFilterColumn) { - super(directed); - m_spanningTreeFilter = spanningFilterColumn; - } - + + + private String m_spanningTreeFilter; + private FilteredSpanningTree m_filteredSpanning = null; + + public MyGraph(boolean directed, String spanningFilterColumn) { + super(directed); + m_spanningTreeFilter = spanningFilterColumn; + } + public Tree getFilteredSpanningTree() { - if ( m_filteredSpanning == null ) - return getFilteredSpanningTree((Node)nodes().next()); + if (m_filteredSpanning == null) + return getFilteredSpanningTree((Node) nodes().next()); else return m_filteredSpanning; } public Tree getFilteredSpanningTree(Node root) { nodeCheck(root, true); - if ( m_filteredSpanning == null ) { - m_filteredSpanning = new FilteredSpanningTree(this, root, m_spanningTreeFilter); - } else if ( m_filteredSpanning.getRoot() != root ) { - m_filteredSpanning.buildSpanningTree(root); + if (m_filteredSpanning == null) { + m_filteredSpanning = new FilteredSpanningTree(this, root, m_spanningTreeFilter); + } else if (m_filteredSpanning.getRoot() != root) { + m_filteredSpanning.buildSpanningTree(root); } return m_filteredSpanning; } - + @Override protected void updateDegrees(int e, int s, int t, int incr) { - super.updateDegrees(e, s, t, incr); - clearFilteredSpanningTree(); + super.updateDegrees(e, s, t, incr); + clearFilteredSpanningTree(); } - + public void clearFilteredSpanningTree() { - m_filteredSpanning = null; + m_filteredSpanning = null; } - + public Node getTreeParent(Node n) { - return getFilteredSpanningTree().getParent(n); + return getFilteredSpanningTree().getParent(n); } - + public Node getNextTreeSibling(Node n) { - return getFilteredSpanningTree().getNextSibling(n); + return getFilteredSpanningTree().getNextSibling(n); } public Node getPreviousTreeSibling(Node n) { - return getFilteredSpanningTree().getPreviousSibling(n); + return getFilteredSpanningTree().getPreviousSibling(n); } - + public Node getFirstTreeChild(Node n) { - return getFilteredSpanningTree().getFirstChild(n); + return getFilteredSpanningTree().getFirstChild(n); } - + public Node getLastTreeChild(Node n) { - return getFilteredSpanningTree().getLastChild(n); + return getFilteredSpanningTree().getLastChild(n); } } - + // class TooltipControl extends ControlAdapter { // // @Override @@ -1121,13 +1092,13 @@ public class WriterModeEditor extends Editor { // tt.setPreferredSize(tt.getLayout().preferredLayoutSize(tt)); // return tt; // } - + + } + + @Override + public void targetUpdated() { + this.icon = new ImageIcon(((GameDataElement) target).getIcon()); + this.name = ((GameDataElement) target).getDesc(); } - @Override - public void targetUpdated() { - this.icon = new ImageIcon(((GameDataElement)target).getIcon()); - this.name = ((GameDataElement)target).getDesc(); - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/DesktopIntegration.java b/src/com/gpl/rpg/atcontentstudio/utils/DesktopIntegration.java index cd229ff..bb5db3a 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/DesktopIntegration.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/DesktopIntegration.java @@ -1,6 +1,8 @@ package com.gpl.rpg.atcontentstudio.utils; -import java.awt.Desktop; +import com.gpl.rpg.atcontentstudio.model.Workspace; + +import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; @@ -8,101 +10,99 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; -import com.gpl.rpg.atcontentstudio.model.Workspace; - public class DesktopIntegration { - - public static void openTmxMap(File f) { - if (Workspace.activeWorkspace.settings.useSystemDefaultMapEditor.getCurrentValue()) { - try { - Desktop.getDesktop().open(f); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - try { - Runtime.getRuntime().exec(tokenize(Workspace.activeWorkspace.settings.mapEditorCommand.getCurrentValue()+" \""+f.getAbsolutePath()+"\"")); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public static void openImage(File f) { - if (Workspace.activeWorkspace.settings.useSystemDefaultImageViewer.getCurrentValue()) { - try { - Desktop.getDesktop().open(f); - } catch (IOException e) { - e.printStackTrace(); - } - } else if (Workspace.activeWorkspace.settings.useSystemDefaultImageEditor.getCurrentValue()) { - try { - Desktop.getDesktop().edit(f); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - try { - Runtime.getRuntime().exec(tokenize(Workspace.activeWorkspace.settings.imageEditorCommand.getCurrentValue()+" \""+f.getAbsolutePath()+"\"")); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - - - public static enum OSType { - Windows, MacOS, NIX, Other - } - - public static OSType detectedOS = detectOS(); - - private static OSType detectOS() { - String os = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); - if ((os.indexOf("mac") >= 0) || (os.indexOf("darwin") >= 0)) return OSType.MacOS; - if (os.indexOf("win") >= 0) return OSType.Windows; - if ((os.indexOf("nux") >= 0) || (os.indexOf("nix") >= 0) || (os.indexOf("aix") >= 0) || (os.indexOf("sunos") >= 0) || (os.indexOf("solaris") >= 0)) return OSType.NIX; - return OSType.Other; - } - - - private static List quotes = Arrays.asList(new Character[]{'\'', '"'}); - private static List delims = Arrays.asList(new Character[]{' ', '\r', '\n', '\t'}); - - private static String[] tokenize(String command) { - List tokens = new ArrayList(); - boolean inQuote = false; - char usedQuote = '\0'; - StringBuilder sb = new StringBuilder(); - - for (char c : command.toCharArray()) { - if (inQuote) { - if (c == usedQuote) { - inQuote = false; - continue; - } else { - sb.append(c); - } - } else { - if (quotes.contains(c)) { - inQuote = true; - usedQuote = c; - } else if (delims.contains(c)) { - if (sb.length() > 0) { - tokens.add(sb.toString()); - sb = new StringBuilder(); - } - } else { - sb.append(c); - } - } - } - if (sb.length() > 0) { - tokens.add(sb.toString()); - } - return tokens.toArray(new String[tokens.size()]); - } - + + public static void openTmxMap(File f) { + if (Workspace.activeWorkspace.settings.useSystemDefaultMapEditor.getCurrentValue()) { + try { + Desktop.getDesktop().open(f); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + try { + Runtime.getRuntime().exec(tokenize(Workspace.activeWorkspace.settings.mapEditorCommand.getCurrentValue() + " \"" + f.getAbsolutePath() + "\"")); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static void openImage(File f) { + if (Workspace.activeWorkspace.settings.useSystemDefaultImageViewer.getCurrentValue()) { + try { + Desktop.getDesktop().open(f); + } catch (IOException e) { + e.printStackTrace(); + } + } else if (Workspace.activeWorkspace.settings.useSystemDefaultImageEditor.getCurrentValue()) { + try { + Desktop.getDesktop().edit(f); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + try { + Runtime.getRuntime().exec(tokenize(Workspace.activeWorkspace.settings.imageEditorCommand.getCurrentValue() + " \"" + f.getAbsolutePath() + "\"")); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + + public static enum OSType { + Windows, MacOS, NIX, Other + } + + public static OSType detectedOS = detectOS(); + + private static OSType detectOS() { + String os = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH); + if ((os.indexOf("mac") >= 0) || (os.indexOf("darwin") >= 0)) return OSType.MacOS; + if (os.indexOf("win") >= 0) return OSType.Windows; + if ((os.indexOf("nux") >= 0) || (os.indexOf("nix") >= 0) || (os.indexOf("aix") >= 0) || (os.indexOf("sunos") >= 0) || (os.indexOf("solaris") >= 0)) + return OSType.NIX; + return OSType.Other; + } + + + private static List quotes = Arrays.asList(new Character[]{'\'', '"'}); + private static List delims = Arrays.asList(new Character[]{' ', '\r', '\n', '\t'}); + + private static String[] tokenize(String command) { + List tokens = new ArrayList(); + boolean inQuote = false; + char usedQuote = '\0'; + StringBuilder sb = new StringBuilder(); + + for (char c : command.toCharArray()) { + if (inQuote) { + if (c == usedQuote) { + inQuote = false; + continue; + } else { + sb.append(c); + } + } else { + if (quotes.contains(c)) { + inQuote = true; + usedQuote = c; + } else if (delims.contains(c)) { + if (sb.length() > 0) { + tokens.add(sb.toString()); + sb = new StringBuilder(); + } + } else { + sb.append(c); + } + } + } + if (sb.length() > 0) { + tokens.add(sb.toString()); + } + return tokens.toArray(new String[tokens.size()]); + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java index 4e54ae8..b4ce56d 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java @@ -1,15 +1,6 @@ package com.gpl.rpg.atcontentstudio.utils; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; +import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -19,206 +10,209 @@ import java.util.zip.ZipOutputStream; public class FileUtils { - public static void deleteDir(File dir) { - if (dir.exists()) { - for (File f : dir.listFiles()) { - if (f.isDirectory()) { - deleteDir(f); - } else { - f.delete(); - } - } - dir.delete(); - } - } - - public static void copyFile(File sourceLocation , File targetLocation) { - try { - InputStream in = new FileInputStream(sourceLocation); - OutputStream out = new FileOutputStream(targetLocation); + public static void deleteDir(File dir) { + if (dir.exists()) { + for (File f : dir.listFiles()) { + if (f.isDirectory()) { + deleteDir(f); + } else { + f.delete(); + } + } + dir.delete(); + } + } - // Copy the bits from instream to outstream - byte[] buf = new byte[1024]; - int len; - try { - while ((len = in.read(buf)) > 0) { - out.write(buf, 0, len); - } - } catch (IOException e) { - // TODO Auto-generated catch block - } finally { - try { - in.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - } - try { - out.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - } - } - } catch (FileNotFoundException e1) { - // TODO Auto-generated catch block - } - } - - private static final int BUFFER = 2048; - public static void writeToZip(File folder, File target) { - try { - FileOutputStream dest = new FileOutputStream(target); - ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); - zipDir(folder, "", out); - out.flush(); - out.close(); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + public static void copyFile(File sourceLocation, File targetLocation) { + try { + InputStream in = new FileInputStream(sourceLocation); + OutputStream out = new FileOutputStream(targetLocation); - } - - /** - * cp sourceFolder/* targetFolder/ - * @param sourceFolder - * @param targetFolder - */ - public static void copyOver(File sourceFolder, File targetFolder) { - if (!sourceFolder.isDirectory() || !targetFolder.isDirectory()) return; - for (File f : sourceFolder.listFiles()) { - if (Files.isSymbolicLink(f.toPath())) { - //Skip symlinks - continue; - } else if (f.isDirectory()) { - File dest = new File(targetFolder, f.getName()); - if (!dest.exists()) { - dest.mkdir(); - } - copyOver(f, dest); - } else { - copyFile(f, new File(targetFolder, f.getName())); - } - } - } - - private static void zipDir(File dir, String prefix, ZipOutputStream zos) { - if (prefix != "") { - prefix = prefix + File.separator; - } - for (File f : dir.listFiles()) { - if (f.isDirectory()) { - zipDir(f, prefix+f.getName(), zos); - } else { - FileInputStream fis; - try { - fis = new FileInputStream(f); - BufferedInputStream origin = new BufferedInputStream(fis, BUFFER); - ZipEntry entry = new ZipEntry(prefix+f.getName()); - try { - zos.putNextEntry(entry); - int count; - byte data[] = new byte[BUFFER]; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - zos.write(data, 0, count); - zos.flush(); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } finally { - try { - origin.close(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - } - - public static boolean makeSymlink(File targetFile, File linkFile) { - Path target = Paths.get(targetFile.getAbsolutePath()); - Path link = Paths.get(linkFile.getAbsolutePath()); - if (!Files.exists(link)) { - try { - Files.createSymbolicLink(link, target); - } catch (Exception e) { - System.err.println("Failed to create symbolic link to target \""+targetFile.getAbsolutePath()+"\" as \""+linkFile.getAbsolutePath()+"\" the java.nio way:"); - e.printStackTrace(); - switch (DesktopIntegration.detectedOS) { - case Windows: - System.err.println("Trying the Windows way with mklink"); - try { - Runtime.getRuntime().exec("cmd.exe /C mklink "+(targetFile.isDirectory() ? "/J " : "")+"\""+linkFile.getAbsolutePath()+"\" \""+targetFile.getAbsolutePath()+"\""); - } catch (IOException e1) { - e1.printStackTrace(); - } - if (!linkFile.exists()) { - System.err.println("Attempting UAC elevation through VBS script."); - runWithUac("cmd.exe /C mklink "+(targetFile.isDirectory() ? "/J " : "")+"\""+linkFile.getAbsolutePath()+"\" \""+targetFile.getAbsolutePath()+"\"", 3, linkFile); - } - break; - case MacOS: - case NIX: - case Other: - System.err.println("Trying the unix way with ln -s"); - try { - Runtime.getRuntime().exec("ln -s "+targetFile.getAbsolutePath()+" "+linkFile.getAbsolutePath()); - } catch (IOException e1) { - e1.printStackTrace(); - } - break; - default: - System.out.println("Unrecognized OS. Please contact ATCS dev."); - break; - - } - } - } - if (!Files.exists(link)) { - System.err.println("Failed to create link \""+linkFile.getAbsolutePath()+"\" targetting \""+targetFile.getAbsolutePath()+"\""); - System.err.println("You can try running ATCS with administrative privileges once, or create the symbolic link manually."); - } - return true; - } + // Copy the bits from instream to outstream + byte[] buf = new byte[1024]; + int len; + try { + while ((len = in.read(buf)) > 0) { + out.write(buf, 0, len); + } + } catch (IOException e) { + // TODO Auto-generated catch block + } finally { + try { + in.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + } + try { + out.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + } + } + } catch (FileNotFoundException e1) { + // TODO Auto-generated catch block + } + } + + private static final int BUFFER = 2048; + + public static void writeToZip(File folder, File target) { + try { + FileOutputStream dest = new FileOutputStream(target); + ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); + zipDir(folder, "", out); + out.flush(); + out.close(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + /** + * cp sourceFolder/* targetFolder/ + * + * @param sourceFolder + * @param targetFolder + */ + public static void copyOver(File sourceFolder, File targetFolder) { + if (!sourceFolder.isDirectory() || !targetFolder.isDirectory()) return; + for (File f : sourceFolder.listFiles()) { + if (Files.isSymbolicLink(f.toPath())) { + //Skip symlinks + continue; + } else if (f.isDirectory()) { + File dest = new File(targetFolder, f.getName()); + if (!dest.exists()) { + dest.mkdir(); + } + copyOver(f, dest); + } else { + copyFile(f, new File(targetFolder, f.getName())); + } + } + } + + private static void zipDir(File dir, String prefix, ZipOutputStream zos) { + if (prefix != "") { + prefix = prefix + File.separator; + } + for (File f : dir.listFiles()) { + if (f.isDirectory()) { + zipDir(f, prefix + f.getName(), zos); + } else { + FileInputStream fis; + try { + fis = new FileInputStream(f); + BufferedInputStream origin = new BufferedInputStream(fis, BUFFER); + ZipEntry entry = new ZipEntry(prefix + f.getName()); + try { + zos.putNextEntry(entry); + int count; + byte data[] = new byte[BUFFER]; + while ((count = origin.read(data, 0, BUFFER)) != -1) { + zos.write(data, 0, count); + zos.flush(); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + try { + origin.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + } + + public static boolean makeSymlink(File targetFile, File linkFile) { + Path target = Paths.get(targetFile.getAbsolutePath()); + Path link = Paths.get(linkFile.getAbsolutePath()); + if (!Files.exists(link)) { + try { + Files.createSymbolicLink(link, target); + } catch (Exception e) { + System.err.println("Failed to create symbolic link to target \"" + targetFile.getAbsolutePath() + "\" as \"" + linkFile.getAbsolutePath() + "\" the java.nio way:"); + e.printStackTrace(); + switch (DesktopIntegration.detectedOS) { + case Windows: + System.err.println("Trying the Windows way with mklink"); + try { + Runtime.getRuntime().exec("cmd.exe /C mklink " + (targetFile.isDirectory() ? "/J " : "") + "\"" + linkFile.getAbsolutePath() + "\" \"" + targetFile.getAbsolutePath() + "\""); + } catch (IOException e1) { + e1.printStackTrace(); + } + if (!linkFile.exists()) { + System.err.println("Attempting UAC elevation through VBS script."); + runWithUac("cmd.exe /C mklink " + (targetFile.isDirectory() ? "/J " : "") + "\"" + linkFile.getAbsolutePath() + "\" \"" + targetFile.getAbsolutePath() + "\"", 3, linkFile); + } + break; + case MacOS: + case NIX: + case Other: + System.err.println("Trying the unix way with ln -s"); + try { + Runtime.getRuntime().exec("ln -s " + targetFile.getAbsolutePath() + " " + linkFile.getAbsolutePath()); + } catch (IOException e1) { + e1.printStackTrace(); + } + break; + default: + System.out.println("Unrecognized OS. Please contact ATCS dev."); + break; + + } + } + } + if (!Files.exists(link)) { + System.err.println("Failed to create link \"" + linkFile.getAbsolutePath() + "\" targetting \"" + targetFile.getAbsolutePath() + "\""); + System.err.println("You can try running ATCS with administrative privileges once, or create the symbolic link manually."); + } + return true; + } + + public static File backupFile(File f) { + try { + Path returned = Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(f.getAbsolutePath() + ".bak"), StandardCopyOption.REPLACE_EXISTING); + return returned.toFile(); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + static final String uacBatName = "ATCS_elevateWithUac.bat"; + + public static void runWithUac(String command, int tries, File checkExists) { + File tmpFolder = new File(System.getProperty("java.io.tmpdir")); + File batFile = new File(tmpFolder, uacBatName); + batFile.deleteOnExit(); + FileWriter writer; + try { + writer = new FileWriter(batFile, false); + writer.write( + "@echo Set objShell = CreateObject(\"Shell.Application\") > %temp%\\sudo.tmp.vbs\r\n" + + "@echo args = Right(\"%*\", (Len(\"%*\") - Len(\"%1\"))) >> %temp%\\sudo.tmp.vbs\r\n" + + "@echo objShell.ShellExecute \"%1\", args, \"\", \"runas\" >> %temp%\\sudo.tmp.vbs\r\n" + + "@cscript %temp%\\sudo.tmp.vbs\r\n" + + "del /f %temp%\\sudo.tmp.vbs\r\n"); + writer.close(); + while (!checkExists.exists() && tries-- > 0) { + Runtime.getRuntime().exec(new String[]{"cmd.exe", "/C", batFile.getAbsolutePath() + " " + command}); + } + } catch (IOException e) { + e.printStackTrace(); + } + + } - public static File backupFile(File f) { - try { - Path returned = Files.copy(Paths.get(f.getAbsolutePath()), Paths.get(f.getAbsolutePath()+".bak"), StandardCopyOption.REPLACE_EXISTING); - return returned.toFile(); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - static final String uacBatName = "ATCS_elevateWithUac.bat"; - public static void runWithUac(String command, int tries, File checkExists) { - File tmpFolder = new File(System.getProperty("java.io.tmpdir")); - File batFile = new File(tmpFolder, uacBatName); - batFile.deleteOnExit(); - FileWriter writer; - try { - writer = new FileWriter(batFile, false); - writer.write( - "@echo Set objShell = CreateObject(\"Shell.Application\") > %temp%\\sudo.tmp.vbs\r\n" - + "@echo args = Right(\"%*\", (Len(\"%*\") - Len(\"%1\"))) >> %temp%\\sudo.tmp.vbs\r\n" - + "@echo objShell.ShellExecute \"%1\", args, \"\", \"runas\" >> %temp%\\sudo.tmp.vbs\r\n" - + "@cscript %temp%\\sudo.tmp.vbs\r\n" - + "del /f %temp%\\sudo.tmp.vbs\r\n"); - writer.close(); - while (!checkExists.exists() && tries-- > 0) { - Runtime.getRuntime().exec(new String[]{"cmd.exe","/C", batFile.getAbsolutePath()+" "+command}); - } - } catch (IOException e) { - e.printStackTrace(); - } - - } - } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/HashUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/HashUtils.java index 7d89d84..bf2a0da 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/HashUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/HashUtils.java @@ -1,30 +1,30 @@ package com.gpl.rpg.atcontentstudio.utils; -import java.util.LinkedHashMap; -import java.util.Map; - import com.zackehh.siphash.SipHash; import com.zackehh.siphash.SipHashResult; +import java.util.LinkedHashMap; +import java.util.Map; + public class HashUtils { - private static final Map HASHER_CACHE = new LinkedHashMap(); - - static String siphash(String key, byte[] data) { - SipHash hasher = HASHER_CACHE.get(key); - if (hasher == null) { - hasher= new SipHash("Weblate Sip Hash".getBytes()); - HASHER_CACHE.put(key, hasher); - } - - if (data != null) { - SipHashResult result = hasher.hash(data); - return result.getHex(); - } - - - return null; - - } - + private static final Map HASHER_CACHE = new LinkedHashMap(); + + static String siphash(String key, byte[] data) { + SipHash hasher = HASHER_CACHE.get(key); + if (hasher == null) { + hasher = new SipHash("Weblate Sip Hash".getBytes()); + HASHER_CACHE.put(key, hasher); + } + + if (data != null) { + SipHashResult result = hasher.hash(data); + return result.getHex(); + } + + + return null; + + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/SpriteUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/SpriteUtils.java index 05af148..fba5828 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/SpriteUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/SpriteUtils.java @@ -5,30 +5,30 @@ import java.awt.image.WritableRaster; public final class SpriteUtils { - /** - * Check if the image is empty (transparent ) - * - * @param img The image to check - * @return true if the image is empty - */ - public static boolean checkIsImageEmpty(BufferedImage img) { - int width = img.getWidth(null); - int height = img.getHeight(null); - WritableRaster raster = img.getAlphaRaster(); - if (raster == null) { - return false; - } - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - //get pixel alpha value - int alpha = raster.getSample(x, y, 0); - //if alpha is not 0 then the pixel is not transparent - if (alpha != 0) { - return false; - } - } - } - //no non-transparent pixel found - return true; - } + /** + * Check if the image is empty (transparent ) + * + * @param img The image to check + * @return true if the image is empty + */ + public static boolean checkIsImageEmpty(BufferedImage img) { + int width = img.getWidth(null); + int height = img.getHeight(null); + WritableRaster raster = img.getAlphaRaster(); + if (raster == null) { + return false; + } + for (int x = 0; x < width; x++) { + for (int y = 0; y < height; y++) { + //get pixel alpha value + int alpha = raster.getSample(x, y, 0); + //if alpha is not 0 then the pixel is not transparent + if (alpha != 0) { + return false; + } + } + } + //no non-transparent pixel found + return true; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java index dfc534f..e9a70e5 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/TextUtils.java @@ -2,18 +2,19 @@ package com.gpl.rpg.atcontentstudio.utils; public class TextUtils { public static String wordWrap(String in, int length) { - if(in == null || length <= 0) return in; + if (in == null || length <= 0) return in; final String newline = "\n"; //:: Trim - while(in.length() > 0 && (in.charAt(0) == '\t' || in.charAt(0) == ' ')) in = in.substring(1); + while (in.length() > 0 && (in.charAt(0) == '\t' || in.charAt(0) == ' ')) in = in.substring(1); //:: If Small Enough Already, Return Original - if(in.length() < length) return in; + if (in.length() < length) return in; //:: If Next length Contains Newline, Split There - if(in.substring(0, length).contains(newline)) return in.substring(0, in.indexOf(newline)).trim() + newline + wordWrap(in.substring(in.indexOf("\n") + 1), length); + if (in.substring(0, length).contains(newline)) + return in.substring(0, in.indexOf(newline)).trim() + newline + wordWrap(in.substring(in.indexOf("\n") + 1), length); //:: Otherwise, Split Along Nearest Previous Space/Tab/Dash - int spaceIndex = Math.max(Math.max( in.lastIndexOf(" ", length), in.lastIndexOf("\t", length)), in.lastIndexOf("-", length)); + int spaceIndex = Math.max(Math.max(in.lastIndexOf(" ", length), in.lastIndexOf("\t", length)), in.lastIndexOf("-", length)); //:: If No Nearest Space, Split At length - if(spaceIndex == -1) spaceIndex = length; + if (spaceIndex == -1) spaceIndex = length; //:: Split return in.substring(0, spaceIndex).trim() + newline + wordWrap(in.substring(spaceIndex), length); } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index 7fcabd7..5c0b9c2 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -3,13 +3,16 @@ package com.gpl.rpg.atcontentstudio.utils; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; -import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; -import java.awt.event.*; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; import java.util.function.Supplier; public class UiUtils { @@ -70,7 +73,7 @@ public class UiUtils { addRemoveAndAddButtons(listener, itemsListModel, selectedItemReset, selectedItem, tempSupplier, createBtn, itemsList, listButtonsPane, deleteBtn); - if(withMoveButtons) { + if (withMoveButtons) { addMoveButtonListeners(listener, itemsListModel, selectedItem, moveUpBtn, itemsList, listButtonsPane, moveDownBtn); } listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); @@ -85,7 +88,8 @@ public class UiUtils { return new CollapsibleItemListCreation() { { collapsiblePanel = itemsPane; - list = itemsList;} + list = itemsList; + } }; } @@ -140,7 +144,7 @@ public class UiUtils { GameDataElement referencedObj = getReferencedObj.doIt(selectedValue); if (referencedObj != null) { ATContentStudio.frame.openEditor(referencedObj); - ATContentStudio.frame.selectInTree( referencedObj); + ATContentStudio.frame.selectInTree(referencedObj); } } } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/WeblateIntegration.java b/src/com/gpl/rpg/atcontentstudio/utils/WeblateIntegration.java index f27c047..fc23bb2 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/WeblateIntegration.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/WeblateIntegration.java @@ -1,106 +1,105 @@ package com.gpl.rpg.atcontentstudio.utils; -import java.io.IOException; -import java.io.UnsupportedEncodingException; - +import com.gpl.rpg.atcontentstudio.model.Workspace; +import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration.WeblateTranslationUnit.Status; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; -import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration.WeblateTranslationUnit.Status; +import java.io.IOException; +import java.io.UnsupportedEncodingException; public class WeblateIntegration { - static final String WEBLATE_SIPASH_KEY = "Weblate Sip Hash"; + static final String WEBLATE_SIPASH_KEY = "Weblate Sip Hash"; - public static String weblateHash(String str, String ctx) { - - byte[] data = null; - - if (str != null) { - byte[] strBytes; - try { - strBytes = str.getBytes("UTF-8"); - byte[] ctxBytes = ctx.getBytes("UTF-8"); - data = new byte[strBytes.length + ctxBytes.length]; - System.arraycopy(strBytes, 0, data, 0, strBytes.length); - System.arraycopy(ctxBytes, 0, data, strBytes.length, ctxBytes.length); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - - } else { - try { - data = ctx.getBytes("UTF-8"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - - return HashUtils.siphash(WEBLATE_SIPASH_KEY, data); - } + public static String weblateHash(String str, String ctx) { - public static String getWeblateLabelURI(String text) { - return "https://hosted.weblate.org/translate/andors-trail/game-content/"+Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue()+"/?checksum="+weblateHash(text, ""); - } + byte[] data = null; - public static class WeblateTranslationUnit { - public enum Status { - notAllowed, error, absent, notTranslated, warning, fuzzy, done - } + if (str != null) { + byte[] strBytes; + try { + strBytes = str.getBytes("UTF-8"); + byte[] ctxBytes = ctx.getBytes("UTF-8"); + data = new byte[strBytes.length + ctxBytes.length]; + System.arraycopy(strBytes, 0, data, 0, strBytes.length); + System.arraycopy(ctxBytes, 0, data, strBytes.length, ctxBytes.length); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } - public Status status; - public String translatedText; - } + } else { + try { + data = ctx.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } - public static WeblateTranslationUnit getTranslationUnit(String text) { - WeblateTranslationUnit unit = new WeblateTranslationUnit(); - if (!Workspace.activeWorkspace.settings.useInternet.getCurrentValue()) { - unit.status = Status.notAllowed; - unit.translatedText = "Allow internet connection in the workspace settings to get translation status"; - } else if (Workspace.activeWorkspace.settings.translatorLanguage == null) { - unit.status = Status.notAllowed; - unit.translatedText = "Select a target language in the workspace settings to get translation status"; - } else { - unit.status = Status.absent; - unit.translatedText = "Cannot find this on weblate"; - String hash = weblateHash(text, ""); - try { - Document wlDoc = Jsoup.connect(getWeblateLabelURI(text)).get(); - Element textArea = wlDoc.getElementById("id_"+hash+"_0"); - if (textArea != null) { - String trans = textArea.text(); - if (trans != null) { - unit.translatedText = trans.trim(); - if (unit.translatedText.isEmpty()) { - unit.translatedText = "Not yet translated"; - unit.status = Status.notTranslated; - } else { - unit.status = Status.done; - } - } - Element fuzzyBox = wlDoc.getElementById("id_"+hash+"_fuzzy"); - if (fuzzyBox != null && fuzzyBox.hasAttr("checked")) { - if ("checked".equals(fuzzyBox.attr("checked"))) { - unit.status = Status.fuzzy; - } - } else { - Elements dangerZone = wlDoc.getElementsByAttributeValue("class", "panel panel-danger"); - if (dangerZone != null && !dangerZone.isEmpty()) { - unit.status = Status.warning; - } - } - } - } catch (IOException e) { - unit.status = Status.error; - unit.translatedText = "Cannot connect to weblate: "+e.getMessage(); - e.printStackTrace(); - } - } - return unit; - } + return HashUtils.siphash(WEBLATE_SIPASH_KEY, data); + } + + public static String getWeblateLabelURI(String text) { + return "https://hosted.weblate.org/translate/andors-trail/game-content/" + Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() + "/?checksum=" + weblateHash(text, ""); + } + + public static class WeblateTranslationUnit { + public enum Status { + notAllowed, error, absent, notTranslated, warning, fuzzy, done + } + + public Status status; + public String translatedText; + } + + public static WeblateTranslationUnit getTranslationUnit(String text) { + WeblateTranslationUnit unit = new WeblateTranslationUnit(); + if (!Workspace.activeWorkspace.settings.useInternet.getCurrentValue()) { + unit.status = Status.notAllowed; + unit.translatedText = "Allow internet connection in the workspace settings to get translation status"; + } else if (Workspace.activeWorkspace.settings.translatorLanguage == null) { + unit.status = Status.notAllowed; + unit.translatedText = "Select a target language in the workspace settings to get translation status"; + } else { + unit.status = Status.absent; + unit.translatedText = "Cannot find this on weblate"; + String hash = weblateHash(text, ""); + try { + Document wlDoc = Jsoup.connect(getWeblateLabelURI(text)).get(); + Element textArea = wlDoc.getElementById("id_" + hash + "_0"); + if (textArea != null) { + String trans = textArea.text(); + if (trans != null) { + unit.translatedText = trans.trim(); + if (unit.translatedText.isEmpty()) { + unit.translatedText = "Not yet translated"; + unit.status = Status.notTranslated; + } else { + unit.status = Status.done; + } + } + Element fuzzyBox = wlDoc.getElementById("id_" + hash + "_fuzzy"); + if (fuzzyBox != null && fuzzyBox.hasAttr("checked")) { + if ("checked".equals(fuzzyBox.attr("checked"))) { + unit.status = Status.fuzzy; + } + } else { + Elements dangerZone = wlDoc.getElementsByAttributeValue("class", "panel panel-danger"); + if (dangerZone != null && !dangerZone.isEmpty()) { + unit.status = Status.warning; + } + } + } + } catch (IOException e) { + unit.status = Status.error; + unit.translatedText = "Cannot connect to weblate: " + e.getMessage(); + e.printStackTrace(); + } + } + return unit; + } } From 18cb73385f2b0fc16fe0d28aaa8d83dfef197b80 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 18:37:54 +0200 Subject: [PATCH 25/94] remove Unnecessary semicolons --- .../rpg/atcontentstudio/ATContentStudio.java | 1 - .../model/gamedata/ActorCondition.java | 1 - .../atcontentstudio/model/gamedata/Item.java | 1 - .../atcontentstudio/model/gamedata/NPC.java | 2 -- .../atcontentstudio/model/maps/TMXMapSet.java | 1 - .../model/sprites/Spritesheet.java | 2 -- .../gpl/rpg/atcontentstudio/ui/Editor.java | 7 ---- .../atcontentstudio/ui/ScrollablePanel.java | 4 +-- .../rpg/atcontentstudio/ui/WorkerDialog.java | 1 - .../atcontentstudio/ui/WorkspaceActions.java | 36 ------------------- .../ui/gamedataeditors/ItemEditor.java | 1 - .../dialoguetree/DialogueGraphView.java | 2 -- .../ui/map/WorldMapEditor.java | 1 - .../ui/sprites/SpritesheetEditor.java | 1 - .../ui/tools/writermode/WriterModeEditor.java | 2 -- 15 files changed, 2 insertions(+), 61 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java index 926d52d..30c787d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java +++ b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java @@ -113,7 +113,6 @@ public class ATContentStudio { frame.setDefaultCloseOperation(StudioFrame.DO_NOTHING_ON_CLOSE); } - ; }); for (File f : ConfigCache.getKnownWorkspaces()) { if (workspaceRoot.equals(f)) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java index e43088f..882c006 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java @@ -22,7 +22,6 @@ public class ActorCondition extends JSONElement { public static final Integer MAGNITUDE_CLEAR = -99; public static final Integer DURATION_FOREVER = 999; - ; public static final Integer DURATION_NONE = 0; // Available from init state diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index ba03e82..c7cfa2c 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -614,7 +614,6 @@ public class Item extends JSONElement { price += kill_effect == null ? 0 : calculateUseCost(); } else if (category.action_type == ItemCategory.ActionType.equip) { price += equip_effect == null ? 0 : calculateEquipCost(isWeapon()); - ; price += hit_effect == null ? 0 : calculateHitCost(); price += kill_effect == null ? 0 : calculateKillCost(); } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 37c0c0e..743245a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -574,7 +574,5 @@ public class NPC extends JSONElement { return new Double(Math.ceil(experience)).intValue(); } - ; - } diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java index a71e298..39c9c3d 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/TMXMapSet.java @@ -119,7 +119,6 @@ public class TMXMapSet implements ProjectTreeNode { } } - ; }; watcher.start(); } diff --git a/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java b/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java index dc1e72e..389434a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java +++ b/src/com/gpl/rpg/atcontentstudio/model/sprites/Spritesheet.java @@ -37,8 +37,6 @@ public class Spritesheet extends GameDataElement { actorcondition } - ; - //Lazy initialization. public BufferedImage spritesheet = null; public Map cache_full_size = new LinkedHashMap(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index b07c7c9..bc83e62 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -126,7 +126,6 @@ public abstract class Editor extends JPanel implements ProjectElementListener { translationStatus.setText(unit.translatedText); } - ; }.start(); pane.add(labelPane, JideBoxLayout.FIX); tfComponent.getDocument().addDocumentListener(new DocumentListener() { @@ -333,18 +332,15 @@ public abstract class Editor extends JPanel implements ProjectElementListener { defaultChance = Integer.parseInt(defaultValue.substring(0, c)); } catch (NumberFormatException nfe) { } - ; try { defaultMaxChance = Integer.parseInt(defaultValue.substring(c + 1)); } catch (NumberFormatException nfe) { } - ; } else { try { defaultChance = Integer.parseInt(defaultValue); } catch (NumberFormatException nfe) { } - ; } } @@ -358,19 +354,16 @@ public abstract class Editor extends JPanel implements ProjectElementListener { chance = Integer.parseInt(initialValue.substring(0, c)); } catch (NumberFormatException nfe) { } - ; try { maxChance = Integer.parseInt(initialValue.substring(c + 1)); } catch (NumberFormatException nfe) { } - ; } else { try { chance = Integer.parseInt(initialValue); currentFormIsRatio = false; } catch (NumberFormatException nfe) { } - ; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java b/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java index 38312d5..72900bb 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ScrollablePanel.java @@ -10,12 +10,12 @@ public class ScrollablePanel extends JPanel implements Scrollable, SwingConstant public enum ScrollableSizeHint { NONE, FIT, - STRETCH; + STRETCH } public enum IncrementType { PERCENT, - PIXELS; + PIXELS } private ScrollableSizeHint scrollableHeight = ScrollableSizeHint.NONE; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java index 4f3c4cc..38e67ea 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkerDialog.java @@ -45,7 +45,6 @@ public class WorkerDialog extends JDialog { JOptionPane.showMessageDialog(parent, "Done !"); } - ; }.start(); } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java index 4ead144..a2072f0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java @@ -33,7 +33,6 @@ public class WorkspaceActions { new ProjectCreationWizard().setVisible(true); } - ; }; @@ -44,13 +43,10 @@ public class WorkspaceActions { selectedNode = null; } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(selectedNode instanceof Project); } - ; }; @@ -60,13 +56,10 @@ public class WorkspaceActions { Workspace.openProject((ClosedProject) selectedNode); } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(selectedNode instanceof ClosedProject); } - ; }; public ATCSAction deleteProject = new ATCSAction("Delete project", "Deletes the project, and all created/altered data, from disk") { @@ -82,13 +75,10 @@ public class WorkspaceActions { } } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(selectedNode instanceof Project || selectedNode instanceof ClosedProject); } - ; }; public ATCSAction saveElement = new ATCSAction("Save this element", "Saves the current state of this element on disk") { @@ -101,8 +91,6 @@ public class WorkspaceActions { } } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { if (selectedNode instanceof GameDataElement) { setEnabled(((GameDataElement) selectedNode).needsSaving()); @@ -111,7 +99,6 @@ public class WorkspaceActions { } } - ; }; public ATCSAction deleteSelected = new ATCSAction("Delete", "Deletes the selected items") { @@ -122,8 +109,6 @@ public class WorkspaceActions { putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); } - ; - public void actionPerformed(ActionEvent e) { if (multiMode) { if (elementsToDelete == null) return; @@ -253,8 +238,6 @@ public class WorkspaceActions { } } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { elementsToDelete = null; if (selectedPaths != null && selectedPaths.length > 1) { @@ -284,7 +267,6 @@ public class WorkspaceActions { } } - ; }; public ATCSAction createGDE = new ATCSAction("Create Game Data Element (JSON)", "Opens the game object creation wizard") { @@ -341,13 +323,10 @@ public class WorkspaceActions { } } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(selectedNode instanceof Project || selectedNode instanceof SavedGamesSet); } - ; }; public ATCSAction compareItems = new ATCSAction("Items comparator", "Opens an editor showing all the items of the project in a table") { @@ -378,13 +357,10 @@ public class WorkspaceActions { new ExportProjectWizard(selectedNode.getProject()).setVisible(true); } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(selectedNode != null && selectedNode.getProject() != null); } - ; }; public ATCSAction runBeanShell = new ATCSAction("Run Beanshell console", "Opens a beanshell scripting pad.") { @@ -392,7 +368,6 @@ public class WorkspaceActions { new BeanShellView(); } - ; }; public ATCSAction showAbout = new ATCSAction("About...", "Displays credits and other informations about ATCS") { @@ -400,7 +375,6 @@ public class WorkspaceActions { ATContentStudio.frame.showAbout(); } - ; }; public ATCSAction exitATCS = new ATCSAction("Exit", "Closes the program") { @@ -415,7 +389,6 @@ public class WorkspaceActions { } } - ; }; public ATCSAction createWriter = new ATCSAction("Create dialogue sketch", "Create a dialogue sketch for fast dialogue edition") { @@ -435,8 +408,6 @@ public class WorkspaceActions { // frame.setVisible(true); } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(selectedNode != null && selectedNode.getProject() != null); } @@ -464,8 +435,6 @@ public class WorkspaceActions { } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(selectedNode != null && selectedNode instanceof Dialogue); } @@ -476,13 +445,10 @@ public class WorkspaceActions { new WorkspaceSettingsEditor(Workspace.activeWorkspace.settings); } - ; - public void selectionChanged(ProjectTreeNode selectedNode, TreePath[] selectedPaths) { setEnabled(true); } - ; }; List actions = new ArrayList(); @@ -541,8 +507,6 @@ public class WorkspaceActions { public void actionPerformed(ActionEvent e) { } - ; - public Map values = new LinkedHashMap(); @Override diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 50d7bd6..3f57134 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -1165,7 +1165,6 @@ public class ItemEditor extends JSONElementEditor { public static class SourceTimedConditionsListModel extends OrderedListenerListModel { public SourceTimedConditionsListModel(Common.DeathEffect effect) { super(effect); - ; } @Override diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java index 0c8a36f..aedbfa7 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/dialoguetree/DialogueGraphView.java @@ -204,7 +204,6 @@ public class DialogueGraphView extends Display { dNode.setString(LABEL, message + translationHeader + unit.translatedText); } - ; }; } else { label = dialogue.message; @@ -244,7 +243,6 @@ public class DialogueGraphView extends Display { rNode.setString(LABEL, message + translationHeader + unit.translatedText); } - ; }; } else { label = r.text; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java index 0f0d4f7..6b2f68c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/WorldMapEditor.java @@ -985,7 +985,6 @@ public class WorldMapEditor extends Editor implements FieldUpdateListener { repaintMap(); } - ; }; private void setCurrentSelectionModel(ListModel listModel, ListSelectionModel listSelectionModel) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java index da8acb0..a7cf830 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/sprites/SpritesheetEditor.java @@ -323,7 +323,6 @@ public class SpritesheetEditor extends Editor { } } - ; }; animator.start(); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java index 218dead..866daf2 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/writermode/WriterModeEditor.java @@ -768,8 +768,6 @@ public class WriterModeEditor extends Editor { } } - ; - private void showEditorOnSelected() { if (selected == null) return; From 685ce223daafe4a94028bac834664b1def46d2fb Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 19:09:35 +0200 Subject: [PATCH 26/94] extract refresh button creation --- .../ui/gamedataeditors/DialogueEditor.java | 11 ++--------- .../ui/gamedataeditors/NPCEditor.java | 13 ++++--------- .../gpl/rpg/atcontentstudio/utils/UiUtils.java | 16 ++++++++++++---- 3 files changed, 18 insertions(+), 22 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index b7dc0b8..e554c0d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -108,15 +108,7 @@ public class DialogueEditor extends JSONElementEditor { dialogueGraphView = new DialogueGraphView(dialogue, null); pane.add(dialogueGraphView, BorderLayout.CENTER); - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - JButton reloadButton = new JButton("Refresh graph"); - buttonPane.add(reloadButton, JideBoxLayout.FIX); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - pane.add(buttonPane, BorderLayout.NORTH); - - - reloadButton.addActionListener(new ActionListener() { + JPanel buttonPane = UiUtils.createRefreshButtonPane(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { pane.remove(dialogueGraphView); @@ -126,6 +118,7 @@ public class DialogueEditor extends JSONElementEditor { pane.repaint(); } }); + pane.add(buttonPane, BorderLayout.NORTH); return pane; } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 705dbc0..7dc86bb 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -8,6 +8,7 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; +import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; @@ -170,20 +171,14 @@ public class NPCEditor extends JSONElementEditor { dialogueGraphView = new DialogueGraphView(npc.dialogue, npc); dialogueGraphPane.add(dialogueGraphView, BorderLayout.CENTER); - JPanel buttonPane = new JPanel(); - buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); - JButton reloadButton = new JButton("Refresh graph"); - buttonPane.add(reloadButton, JideBoxLayout.FIX); - buttonPane.add(new JPanel(), JideBoxLayout.VARY); - dialogueGraphPane.add(buttonPane, BorderLayout.NORTH); - - - reloadButton.addActionListener(new ActionListener() { + JPanel buttonPane = UiUtils.createRefreshButtonPane(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { reloadGraphView(npc); } }); + dialogueGraphPane.add(buttonPane, BorderLayout.NORTH); + return dialogueGraphPane; } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index 5c0b9c2..a9d5ba0 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -9,10 +9,8 @@ import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; +import java.awt.*; +import java.awt.event.*; import java.util.function.Supplier; public class UiUtils { @@ -20,6 +18,16 @@ public class UiUtils { public CollapsiblePanel collapsiblePanel; public JList list; } + public static JPanel createRefreshButtonPane(ActionListener reloadButtonEditor){ + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); + JButton reloadButton = new JButton("Refresh graph"); + buttonPane.add(reloadButton, JideBoxLayout.FIX); + buttonPane.add(new JPanel(), JideBoxLayout.VARY); + + reloadButton.addActionListener(reloadButtonEditor); + return buttonPane; + } public static > CollapsibleItemListCreation getCollapsibleItemList(FieldUpdateListener listener, M itemsListModel, From d1568cd2edbb6b1ff31958e19026cecbe9a9639e Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 19:10:03 +0200 Subject: [PATCH 27/94] extract common stuff of addTextField & addTextArea --- .../gpl/rpg/atcontentstudio/ui/Editor.java | 79 +++++++------------ 1 file changed, 28 insertions(+), 51 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index bc83e62..eeffe1c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -179,13 +179,29 @@ public abstract class Editor extends JPanel implements ProjectElementListener { } public static JTextField addTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + final JTextField tfField = new JTextField(initialValue); + addTextComponent(pane, label, editable, listener, tfField, false, false); + tfField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(tfField, tfField.getText()); + } + }); + return tfField; + } + public static T addTextComponent(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T tfField, boolean specialNewLinesHandling, boolean scrollable) { JPanel tfPane = new JPanel(); tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); JLabel tfLabel = new JLabel(label); tfPane.add(tfLabel, JideBoxLayout.FIX); - final JTextField tfField = new JTextField(initialValue); tfField.setEditable(editable); - tfPane.add(tfField, JideBoxLayout.VARY); + JComponent component; + if (scrollable){ + component = new JScrollPane(tfField); + }else{ + component = tfField; + } + tfPane.add(component, JideBoxLayout.VARY); JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); tfPane.add(nullify, JideBoxLayout.FIX); nullify.setEnabled(editable); @@ -201,23 +217,23 @@ public abstract class Editor extends JPanel implements ProjectElementListener { tfField.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { - listener.valueChanged(tfField, tfField.getText()); + String text = tfField.getText(); + if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + listener.valueChanged(tfField, text); } @Override public void insertUpdate(DocumentEvent e) { - listener.valueChanged(tfField, tfField.getText()); + String text = tfField.getText(); + if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + listener.valueChanged(tfField, text); } @Override public void changedUpdate(DocumentEvent e) { - listener.valueChanged(tfField, tfField.getText()); - } - }); - tfField.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(tfField, tfField.getText()); + String text = tfField.getText(); + if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + listener.valueChanged(tfField, text); } }); return tfField; @@ -232,51 +248,12 @@ public abstract class Editor extends JPanel implements ProjectElementListener { public static JTextArea addTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { String text = initialValue == null ? "" : initialValue.replaceAll("\\n", "\n"); - - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); final JTextArea tfArea = new JTextArea(text); - tfArea.setEditable(editable); tfArea.setRows(2); tfArea.setLineWrap(true); tfArea.setWrapStyleWord(true); - tfPane.add(new JScrollPane(tfArea), JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - tfArea.setText(""); - listener.valueChanged(tfArea, null); - } - }); - tfArea.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); - } - - @Override - public void insertUpdate(DocumentEvent e) { - listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); - } - - @Override - public void changedUpdate(DocumentEvent e) { - listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))); - } - }); -// tfArea.addActionListener(new ActionListener() { -// @Override -// public void actionPerformed(ActionEvent e) { -// listener.valueChanged(tfArea, tfArea.getText().replaceAll("\n", "\\n")); -// } -// }); + addTextComponent(pane, label, editable, listener, tfArea, true, true); return tfArea; } From d166e49f4d0f0c8f2260de2e1089c10bc1eb03ee Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 19:25:44 +0200 Subject: [PATCH 28/94] extract common stuff of addIntegerField & addDoubleField --- .../gpl/rpg/atcontentstudio/ui/Editor.java | 36 ++++--------------- 1 file changed, 6 insertions(+), 30 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index eeffe1c..f43e830 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -265,12 +265,12 @@ public abstract class Editor extends JPanel implements ProjectElementListener { return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener); } - public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { + public static > JSpinner addNumberField(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, Number initialValue, Number defaultValue, T minimum, T maxValue, Number stepSize) { JPanel tfPane = new JPanel(); tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); JLabel tfLabel = new JLabel(label); tfPane.add(tfLabel, JideBoxLayout.FIX); - final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.intValue() : defaultValue.intValue(), allowNegatives ? Integer.MIN_VALUE : 0, Integer.MAX_VALUE, 1)); + final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue : defaultValue, minimum, maxValue, stepSize)); ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); spinner.setEnabled(editable); ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); @@ -294,6 +294,9 @@ public abstract class Editor extends JPanel implements ProjectElementListener { }); return spinner; } + public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { + return addNumberField(pane, label, editable, listener, initialValue, defaultValue, allowNegatives ? Integer.MIN_VALUE : 0, Integer.MAX_VALUE, 1); + } private static final String percent = "%"; @@ -450,34 +453,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener { // } public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) { - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue.doubleValue() : 0.0d, 0.0d, new Float(Float.MAX_VALUE).doubleValue(), 1.0d)); - ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - spinner.setEnabled(editable); - ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(spinner, JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - pane.add(tfPane, JideBoxLayout.FIX); - spinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - listener.valueChanged(spinner, spinner.getValue()); - } - }); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - spinner.setValue(0.0d); - listener.valueChanged(spinner, null); - } - }); - return spinner; + return addNumberField(pane, label, editable, listener, initialValue, 0.0d, 0.0d, new Float(Float.MAX_VALUE).doubleValue(), 1.0d); } public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) { From 3cc6eb9edb65d937e11807255e5387d9ceb6e6b4 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 20:01:01 +0200 Subject: [PATCH 29/94] enable buttons to move up and down on all (extracted) list panels --- .../ui/gamedataeditors/DialogueEditor.java | 9 +++------ .../ui/gamedataeditors/DroplistEditor.java | 3 +-- .../gpl/rpg/atcontentstudio/utils/UiUtils.java | 17 +++++------------ 3 files changed, 9 insertions(+), 20 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index e554c0d..fd05036 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -152,8 +152,7 @@ public class DialogueEditor extends JSONElementEditor { Dialogue.Reward::new, cellRendererRewards, titleRewards, - (x) -> null, - false + (x) -> null ).collapsiblePanel; if (dialogue.rewards == null || dialogue.rewards.isEmpty()) { rewards.collapse(); @@ -181,8 +180,7 @@ public class DialogueEditor extends JSONElementEditor { Dialogue.Reply::new, cellRendererReplies, titleReplies, - (x) -> null, - true + (x) -> null ).collapsiblePanel; if (dialogue.replies == null || dialogue.replies.isEmpty()) { replies.collapse(); @@ -459,8 +457,7 @@ public class DialogueEditor extends JSONElementEditor { Requirement::new, cellRendererRequirements, titleRequirements, - (x) -> x.required_obj, - false + (x) -> x.required_obj ); CollapsiblePanel requirementsPane = itemsPane.collapsiblePanel; requirementsList = itemsPane.list; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java index 44e50a5..9ac4bab 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DroplistEditor.java @@ -66,8 +66,7 @@ public class DroplistEditor extends JSONElementEditor { DroppedItem::new, new DroppedItemsCellRenderer(), "Items in this droplist: ", - (x) -> x.item, - false + (x) -> x.item ).collapsiblePanel; if (droplist.dropped_items == null || droplist.dropped_items.isEmpty()) { itemsPane.collapse(); diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index a9d5ba0..a40dbcc 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -9,7 +9,6 @@ import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; -import java.awt.*; import java.awt.event.*; import java.util.function.Supplier; @@ -40,8 +39,7 @@ public class UiUtils { Supplier tempSupplier, DefaultListCellRenderer cellRenderer, String title, - BasicLambdaWithArgAndReturn getReferencedObj, - boolean withMoveButtons) { + BasicLambdaWithArgAndReturn getReferencedObj) { CollapsiblePanel itemsPane = new CollapsiblePanel(title); itemsPane.setLayout(new JideBoxLayout(itemsPane, JideBoxLayout.PAGE_AXIS)); final JList itemsList = new JList<>(itemsListModel); @@ -62,16 +60,13 @@ public class UiUtils { setSelectedItem.doIt(selectedValue); if (selectedValue == null) { deleteBtn.setEnabled(false); - if (withMoveButtons) { - moveUpBtn.setEnabled(false); - moveDownBtn.setEnabled(false); - } + moveUpBtn.setEnabled(false); + moveDownBtn.setEnabled(false); } else { deleteBtn.setEnabled(true); - if (withMoveButtons) { moveUpBtn.setEnabled(itemsList.getSelectedIndex() > 0); moveDownBtn.setEnabled(itemsList.getSelectedIndex() < (itemsListModel.getSize() - 1)); - } + } updateEditorPane.doIt(editorPane); }); @@ -80,10 +75,8 @@ public class UiUtils { listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); addRemoveAndAddButtons(listener, itemsListModel, selectedItemReset, selectedItem, tempSupplier, createBtn, itemsList, listButtonsPane, deleteBtn); + addMoveButtonListeners(listener, itemsListModel, selectedItem, moveUpBtn, itemsList, listButtonsPane, moveDownBtn); - if (withMoveButtons) { - addMoveButtonListeners(listener, itemsListModel, selectedItem, moveUpBtn, itemsList, listButtonsPane, moveDownBtn); - } listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); itemsPane.add(listButtonsPane, JideBoxLayout.FIX); } From b5a6aa67064a8957f82addcb11303d8af55ffc54 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 20:12:17 +0200 Subject: [PATCH 30/94] rename some stuff and be more specific on some usages --- .../model/GameDataElement.java | 53 +++++++++++-------- .../model/gamedata/ActorCondition.java | 5 +- .../model/gamedata/Dialogue.java | 5 +- .../model/gamedata/Droplist.java | 5 +- .../atcontentstudio/model/gamedata/Item.java | 5 +- .../model/gamedata/ItemCategory.java | 5 +- .../model/gamedata/JSONElement.java | 3 +- .../atcontentstudio/model/gamedata/NPC.java | 5 +- .../atcontentstudio/model/gamedata/Quest.java | 5 +- .../model/gamedata/QuestStage.java | 5 +- .../model/gamedata/Requirement.java | 5 +- .../tools/writermode/WriterModeData.java | 2 +- .../rpg/atcontentstudio/utils/UiUtils.java | 40 +++++++------- 13 files changed, 88 insertions(+), 55 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java index 46bc743..65f5fae 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java @@ -36,29 +36,6 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable { public String id = null; - protected boolean linkCheck() { - if (checkNotRelatedToParseOrLink()) { - //This type of state is unrelated to parsing/linking. - return false; - } else if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } else if (this.state == State.linked) { - //Already linked. - return false; - } - return true; - - } - - protected boolean checkNotRelatedToParseOrLink() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. - return true; - } - return false; - } - @Override public Enumeration children() { return null; @@ -226,4 +203,34 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable { public abstract List attemptSave(); + /** + * Checks if the current state indicates that parsing/linking should be skipped. + * @return true if the operation should be skipped, false otherwise + */ + protected boolean shouldSkipParseOrLink() { + if (shouldSkipParse()) return true; + if (this.state == State.linked) { + //Already linked. + return true; + } + return false; + } + + protected boolean shouldSkipParse() { + if (this.state == State.created || this.state == State.modified || this.state == State.saved) { + //This type of state is unrelated to parsing/linking. + return true; + } + return false; + } + + /** + * Ensures the element is parsed if needed based on its current state. + */ + protected void ensureParseIfNeeded() { + if (this.state == State.init) { + //Not parsed yet. + this.parse(); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java index 882c006..2643a4f 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java @@ -222,7 +222,10 @@ public class ActorCondition extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); if (this.icon_id != null) { String spritesheetId = this.icon_id.split(":")[0]; if (getProject().getSpritesheet(spritesheetId) == null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java index d3e17c7..657217f 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java @@ -205,7 +205,10 @@ public class Dialogue extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking dialogue " + id + ". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java index c835ee5..900b80c 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java @@ -128,7 +128,10 @@ public class Droplist extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking droplist " + id + ". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index c7cfa2c..1daaeda 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -206,7 +206,10 @@ public class Item extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item " + id + ". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java index 7c8db56..1b9fe82 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java @@ -171,7 +171,10 @@ public class ItemCategory extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java index b044670..fdc9502 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java @@ -21,8 +21,7 @@ public abstract class JSONElement extends GameDataElement { @SuppressWarnings("rawtypes") public void parse() { - if (this.state == State.created || this.state == State.modified || this.state == State.saved) { - //This type of state is unrelated to parsing/linking. + if (shouldSkipParse()) { return; } JSONParser parser = new JSONParser(); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 743245a..505c2d9 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -210,7 +210,10 @@ public class NPC extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item " + id + ". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java index 176dc63..6a2a79a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java @@ -112,7 +112,10 @@ public class Quest extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); for (QuestStage stage : stages) { stage.link(); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java index 838a158..f8133ca 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java @@ -59,7 +59,10 @@ public class QuestStage extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java index 9a15578..7bd1de9 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Requirement.java @@ -122,7 +122,10 @@ public class Requirement extends JSONElement { @Override public void link() { - if (!this.linkCheck()) return; + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking requirement " + getDesc() + ". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java index d2bf908..bdb7995 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java +++ b/src/com/gpl/rpg/atcontentstudio/model/tools/writermode/WriterModeData.java @@ -530,7 +530,7 @@ public class WriterModeData extends GameDataElement { @SuppressWarnings("rawtypes") public void parse() { - if (checkNotRelatedToParseOrLink()) return; + if (shouldSkipParse()) return; JSONParser parser = new JSONParser(); FileReader reader = null; try { diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index a40dbcc..65631b8 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -29,23 +29,23 @@ public class UiUtils { } public static > CollapsibleItemListCreation getCollapsibleItemList(FieldUpdateListener listener, - M itemsListModel, - BasicLambda selectedItemReset, - BasicLambdaWithArg setSelectedItem, - BasicLambdaWithReturn selectedItem, + M listModel, + BasicLambda selectedReset, + BasicLambdaWithArg setSelected, + BasicLambdaWithReturn getSelected, BasicLambdaWithArg valueChanged, BasicLambdaWithArg updateEditorPane, boolean writable, - Supplier tempSupplier, + Supplier newValueSupplier, DefaultListCellRenderer cellRenderer, String title, BasicLambdaWithArgAndReturn getReferencedObj) { CollapsiblePanel itemsPane = new CollapsiblePanel(title); itemsPane.setLayout(new JideBoxLayout(itemsPane, JideBoxLayout.PAGE_AXIS)); - final JList itemsList = new JList<>(itemsListModel); - itemsList.setCellRenderer(cellRenderer); - itemsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - itemsPane.add(new JScrollPane(itemsList), JideBoxLayout.FIX); + final JList list = new JList<>(listModel); + list.setCellRenderer(cellRenderer); + list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + itemsPane.add(new JScrollPane(list), JideBoxLayout.FIX); final JPanel editorPane = new JPanel(); final JButton createBtn = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); final JButton deleteBtn = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); @@ -54,18 +54,18 @@ public class UiUtils { deleteBtn.setEnabled(false); moveUpBtn.setEnabled(false); moveDownBtn.setEnabled(false); - itemsList.addListSelectionListener(e -> { - E selectedValue = itemsList.getSelectedValue(); + list.addListSelectionListener(e -> { + E selectedValue = list.getSelectedValue(); valueChanged.doIt(selectedValue); - setSelectedItem.doIt(selectedValue); + setSelected.doIt(selectedValue); if (selectedValue == null) { deleteBtn.setEnabled(false); moveUpBtn.setEnabled(false); moveDownBtn.setEnabled(false); } else { deleteBtn.setEnabled(true); - moveUpBtn.setEnabled(itemsList.getSelectedIndex() > 0); - moveDownBtn.setEnabled(itemsList.getSelectedIndex() < (itemsListModel.getSize() - 1)); + moveUpBtn.setEnabled(list.getSelectedIndex() > 0); + moveDownBtn.setEnabled(list.getSelectedIndex() < (listModel.getSize() - 1)); } updateEditorPane.doIt(editorPane); @@ -74,14 +74,14 @@ public class UiUtils { JPanel listButtonsPane = new JPanel(); listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - addRemoveAndAddButtons(listener, itemsListModel, selectedItemReset, selectedItem, tempSupplier, createBtn, itemsList, listButtonsPane, deleteBtn); - addMoveButtonListeners(listener, itemsListModel, selectedItem, moveUpBtn, itemsList, listButtonsPane, moveDownBtn); + addRemoveAndAddButtons(listener, listModel, selectedReset, getSelected, newValueSupplier, createBtn, list, listButtonsPane, deleteBtn); + addMoveButtonListeners(listener, listModel, getSelected, moveUpBtn, list, listButtonsPane, moveDownBtn); listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); itemsPane.add(listButtonsPane, JideBoxLayout.FIX); } - addNavigationListeners(getReferencedObj, itemsList); + addNavigationListeners(getReferencedObj, list); editorPane.setLayout(new JideBoxLayout(editorPane, JideBoxLayout.PAGE_AXIS)); itemsPane.add(editorPane, JideBoxLayout.FIX); @@ -89,14 +89,14 @@ public class UiUtils { return new CollapsibleItemListCreation() { { collapsiblePanel = itemsPane; - list = itemsList; + list = list; } }; } - private static > void addRemoveAndAddButtons(FieldUpdateListener listener, M itemsListModel, BasicLambda selectedItemReset, BasicLambdaWithReturn selectedItem, Supplier tempSupplier, JButton createBtn, JList itemsList, JPanel listButtonsPane, JButton deleteBtn) { + private static > void addRemoveAndAddButtons(FieldUpdateListener listener, M itemsListModel, BasicLambda selectedItemReset, BasicLambdaWithReturn selectedItem, Supplier newValueSupplier, JButton createBtn, JList itemsList, JPanel listButtonsPane, JButton deleteBtn) { createBtn.addActionListener(e -> { - E tempItem = tempSupplier.get(); + E tempItem = newValueSupplier.get(); itemsListModel.addItem(tempItem); itemsList.setSelectedValue(tempItem, true); listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. From 21005f1ba6199cabedbd841f604e36320ab971b2 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 20:16:31 +0200 Subject: [PATCH 31/94] improve bounds check in getElementAt --- .../gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java index 22c7f40..5e7a0d2 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java @@ -25,12 +25,12 @@ public abstract class OrderedListenerListModel implements ListenerCollecti @Override public E getElementAt(int index) { - if (getItems() == null) return null; + if (index < 0 || index >= getSize()) return null; return getItems().get(index); } public E setElementAt(int index, E value) { - if (getItems() == null) return null; + if (index < 0 || index >= getSize()) return null; return getItems().set(index, value); } From 70cc9450102d65e1c63853810f32f56eb952b115 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 20:24:33 +0200 Subject: [PATCH 32/94] misc --- .../atcontentstudio/ui/gamedataeditors/DialogueEditor.java | 4 ++-- src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java | 3 +-- src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java | 6 ++++-- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index fd05036..4b84538 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -135,8 +135,8 @@ public class DialogueEditor extends JSONElementEditor { messageField = addTranslatableTextArea(pane, "Message: ", dialogue.message, dialogue.writable, listener); switchToNpcBox = addNPCBox(pane, dialogue.getProject(), "Switch active NPC to: ", dialogue.switch_to_npc, dialogue.writable, listener); - RewardsCellRenderer cellRendererRewards = new RewardsCellRenderer(); String titleRewards = "Reaching this phrase gives the following rewards: "; + RewardsCellRenderer cellRendererRewards = new RewardsCellRenderer(); rewardsListModel = new RewardsListModel(dialogue); CollapsiblePanel rewards = UiUtils.getCollapsibleItemList( @@ -441,9 +441,9 @@ public class DialogueEditor extends JSONElementEditor { updateRepliesParamsEditorPane(repliesParamsPane, reply, listener); pane.add(repliesParamsPane, JideBoxLayout.FIX); + ReplyRequirementsCellRenderer cellRendererRequirements = new ReplyRequirementsCellRenderer(); String titleRequirements = "Requirements the player must fulfill to select this reply: "; requirementsListModel = new ReplyRequirementsListModel(reply); - ReplyRequirementsCellRenderer cellRendererRequirements = new ReplyRequirementsCellRenderer(); UiUtils.CollapsibleItemListCreation itemsPane = UiUtils.getCollapsibleItemList( listener, requirementsListModel, diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index 7a354e9..a774e5b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -1080,8 +1080,7 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe } public void addObject(String source, String target) { - ReplaceArea.Replacement repl = this.source.createReplacement(source, target); - addObject(repl); + addObject(this.source.createReplacement(source, target)); } } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index 65631b8..bfda654 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -157,8 +157,10 @@ public class UiUtils { E selectedValue = itemsList.getSelectedValue(); if (selectedValue == null) return; GameDataElement referencedObj = getReferencedObj.doIt(selectedValue); - ATContentStudio.frame.openEditor(referencedObj); - ATContentStudio.frame.selectInTree(referencedObj); + if (referencedObj != null) { + ATContentStudio.frame.openEditor(referencedObj); + ATContentStudio.frame.selectInTree(referencedObj); + } } } }); From 00147c27085f00ddc5cf6d8791f470ebc06426a2 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sat, 21 Jun 2025 21:07:45 +0200 Subject: [PATCH 33/94] extract one CollapsibleItemList defs in ItemEditor --- .../ui/gamedataeditors/ItemEditor.java | 87 ++++++++----------- 1 file changed, 34 insertions(+), 53 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 3f57134..a0be7a5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -4,12 +4,13 @@ import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; -import com.gpl.rpg.atcontentstudio.model.gamedata.Common; -import com.gpl.rpg.atcontentstudio.model.gamedata.Item; -import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.utils.BasicLambda; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithReturn; +import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; @@ -83,7 +84,7 @@ public class ItemEditor extends JSONElementEditor { private JSpinner hitAPMax; private SourceTimedConditionsListModel hitSourceConditionsModel; @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; + private JList hitSourceConditionsList; private MyComboBox hitSourceConditionBox; private JSpinner hitSourceConditionChance; private JRadioButton hitSourceConditionClear; @@ -282,59 +283,39 @@ public class ItemEditor extends JSONElementEditor { hitHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, item.writable, listener); hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); - final CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); - hitSourceConditionsList = new JList(hitSourceConditionsModel); - hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); final JPanel sourceTimedConditionsEditorPane = new JPanel(); final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); - updateHitSourceTimedConditionEditorPane(sourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); - if (selectedHitEffectSourceCondition == null) { - deleteHitSourceCondition.setEnabled(false); - } else { - deleteHitSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitSourceConditionsModel.addItem(condition); - hitSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectSourceCondition != null) { - hitSourceConditionsModel.removeItem(selectedHitEffectSourceCondition); - selectedHitEffectSourceCondition = null; - hitSourceConditionsList.clearSelection(); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - sourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(sourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsPane.add(sourceTimedConditionsEditorPane, JideBoxLayout.FIX); + BasicLambdaWithReturn getSelected = () -> hitSourceConditionsList.getSelectedValue(); + BasicLambda resetSelected = () -> { + selectedHitEffectSourceCondition = null; + }; + BasicLambdaWithArg setSelected = (selectedItem) -> { + selectedHitEffectSourceCondition = selectedItem; + }; + BasicLambdaWithArg valueChanged = (selectedReply) -> { + }; + BasicLambdaWithArg updateEditorPane = (editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener); + TimedConditionsCellRenderer cellRenderer = new TimedConditionsCellRenderer(); + String title = "Actor Conditions applied to the source: "; + var collapsibleItemList = UiUtils.getCollapsibleItemList( + listener, + hitSourceConditionsModel, + resetSelected, + setSelected, + getSelected, + valueChanged, + updateEditorPane, + item.writable, + Common.TimedConditionEffect::new, + cellRenderer, + title, + (x) -> null + ); + CollapsiblePanel hitSourceConditionsPane = collapsibleItemList.collapsiblePanel; + hitSourceConditionsList = collapsibleItemList.list; if (item.hit_effect == null || item.hit_effect.conditions_source == null || item.hit_effect.conditions_source.isEmpty()) { hitSourceConditionsPane.collapse(); } From 7b780462eafd7a624c061078ebe9f4b7f3b58daa Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 22 Jun 2025 17:48:12 +0200 Subject: [PATCH 34/94] handle wrong values passed to addNumberField better --- .idea/inspectionProfiles/duplicates.xml | 1684 +++++++++++++++++ .../gpl/rpg/atcontentstudio/ui/Editor.java | 24 +- 2 files changed, 1704 insertions(+), 4 deletions(-) create mode 100644 .idea/inspectionProfiles/duplicates.xml diff --git a/.idea/inspectionProfiles/duplicates.xml b/.idea/inspectionProfiles/duplicates.xml new file mode 100644 index 0000000..4915121 --- /dev/null +++ b/.idea/inspectionProfiles/duplicates.xml @@ -0,0 +1,1684 @@ + + + + \ No newline at end of file diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index f43e830..cd462a2 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -265,12 +265,21 @@ public abstract class Editor extends JPanel implements ProjectElementListener { return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener); } - public static > JSpinner addNumberField(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, Number initialValue, Number defaultValue, T minimum, T maxValue, Number stepSize) { + public static > JSpinner addNumberField(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T minimum, T maximum, Number stepSize, Number value, Number defaultValue) { JPanel tfPane = new JPanel(); tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); JLabel tfLabel = new JLabel(label); tfPane.add(tfLabel, JideBoxLayout.FIX); - final JSpinner spinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? initialValue : defaultValue, minimum, maxValue, stepSize)); + if (!(((minimum == null) || (((Comparable)minimum).compareTo(value) <= 0)) && + ((maximum == null) || (((Comparable)maximum).compareTo(value) >= 0)))) { + try{ + throw new IllegalArgumentException("Value for number field outside of range: %s <= %s <= %s".formatted(minimum, value, maximum)); + }catch (IllegalArgumentException e){ + e.printStackTrace(); + value = defaultValue; + } + } + final JSpinner spinner = new JSpinner(new SpinnerNumberModel(value, minimum, maximum, stepSize)); ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); spinner.setEnabled(editable); ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); @@ -295,7 +304,10 @@ public abstract class Editor extends JPanel implements ProjectElementListener { return spinner; } public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { - return addNumberField(pane, label, editable, listener, initialValue, defaultValue, allowNegatives ? Integer.MIN_VALUE : 0, Integer.MAX_VALUE, 1); + int value = initialValue != null ? initialValue : defaultValue; + int minimum = allowNegatives ? Integer.MIN_VALUE : 0; + int maxValue = Integer.MAX_VALUE; + return addNumberField(pane, label, editable, listener, minimum, maxValue, 1, value, defaultValue); } @@ -453,7 +465,11 @@ public abstract class Editor extends JPanel implements ProjectElementListener { // } public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) { - return addNumberField(pane, label, editable, listener, initialValue, 0.0d, 0.0d, new Float(Float.MAX_VALUE).doubleValue(), 1.0d); + double minimum = 0.0d; + double defaultValue = 0.0d; + double value = initialValue != null ? initialValue : minimum; + double maximum = new Float(Float.MAX_VALUE).doubleValue(); + return addNumberField(pane, label, editable, listener, minimum, maximum, 1.0d, value, defaultValue); } public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) { From 919e65187f97ef9b438ce6429b4b232d2ac70b38 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 22 Jun 2025 18:55:05 +0200 Subject: [PATCH 35/94] improve addNumberField --- .../gpl/rpg/atcontentstudio/ui/Editor.java | 2228 ++++++++--------- 1 file changed, 1108 insertions(+), 1120 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index cd462a2..4175412 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -1,1120 +1,1108 @@ -package com.gpl.rpg.atcontentstudio.ui; - -import com.gpl.rpg.atcontentstudio.ATContentStudio; -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Project; -import com.gpl.rpg.atcontentstudio.model.ProjectElementListener; -import com.gpl.rpg.atcontentstudio.model.Workspace; -import com.gpl.rpg.atcontentstudio.model.gamedata.*; -import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; -import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; -import com.jidesoft.swing.ComboBoxSearchable; -import com.jidesoft.swing.JideBoxLayout; - -import javax.swing.*; -import javax.swing.JSpinner.NumberEditor; -import javax.swing.event.*; -import javax.swing.text.DefaultFormatter; -import javax.swing.text.JTextComponent; -import java.awt.*; -import java.awt.event.*; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.*; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.regex.Matcher; - -public abstract class Editor extends JPanel implements ProjectElementListener { - - private static final long serialVersionUID = 241750514033596878L; - private static final FieldUpdateListener nullListener = new FieldUpdateListener() { - @Override - public void valueChanged(JComponent source, Object value) { - } - }; - - public static final String SAVE = "Save"; - public static final String DELETE = "Delete"; - public static final String REVERT = "Revert to original"; - public static final String ALTER = "Alter"; - public static final String GO_TO_ALTERED = "Go to altered"; - - - public static final String READ_ONLY_MESSAGE = - "" + - "This element is not modifiable.
" + - "Click on the \"Alter\" button to create a writable copy." + - "
"; - - public static final String ALTERED_EXISTS_MESSAGE = - "" + - "This element is not modifiable.
" + - "A writable copy exists in this project. Click on \"Go to altered\" to open it." + - "
"; - - public static final String ALTERED_MESSAGE = - "" + - "This element is a writable copy of an element of the referenced game source.
" + - "Take care not to break existing content when modifying it." + - "
"; - - public static final String CREATED_MESSAGE = - "" + - "This element is a creation of yours.
" + - "Do as you please." + - "
"; - - - public String name = "Editor"; - public Icon icon = null; - public GameDataElement target = null; - - public JLabel message = null; - - - public static JTextField addLabelField(JPanel pane, String label, String value) { - return addTextField(pane, label, value, false, nullListener); - } - - public static void addTranslationPane(JPanel pane, final JTextComponent tfComponent, final String initialValue) { - if (Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null) { - JPanel labelPane = new JPanel(); - labelPane.setLayout(new JideBoxLayout(labelPane, JideBoxLayout.LINE_AXIS, 6)); - final JLabel translateLinkLabel = new JLabel(getWeblateLabelLink(initialValue)); - labelPane.add(translateLinkLabel, JideBoxLayout.FIX); - labelPane.add(new JLabel(" "), JideBoxLayout.FIX); - final JLabel translationStatus = new JLabel("Retrieving..."); - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusUnknownIcon())); - translationStatus.setToolTipText("Connecting to weblate..."); - labelPane.add(translationStatus, JideBoxLayout.VARY); - new Thread() { - public void run() { - WeblateIntegration.WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(initialValue); - switch (unit.status) { - case absent: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); - translationStatus.setToolTipText("This string isn't managed by weblate (yet)."); - break; - case done: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusGreenIcon())); - translationStatus.setToolTipText("This string is translated on weblate."); - break; - case fuzzy: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); - translationStatus.setToolTipText("This string is translated on weblate, but needs a review."); - break; - case notTranslated: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); - translationStatus.setToolTipText("This string isn't translated in your language on weblate yet."); - break; - case warning: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); - translationStatus.setToolTipText("This string is translated on weblate, but triggered some weblate checks."); - break; - case error: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); - translationStatus.setToolTipText("Cannot connect to weblate. Check internet connection and firewall settings."); - break; - case notAllowed: - translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusBlueIcon())); - translationStatus.setToolTipText("You have not allowed ATCS to access to internet. You can change this in the workspace settings."); - break; - } - translationStatus.setText(unit.translatedText); - } - - }.start(); - pane.add(labelPane, JideBoxLayout.FIX); - tfComponent.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); - translateLinkLabel.revalidate(); - translateLinkLabel.repaint(); - } - - @Override - public void insertUpdate(DocumentEvent e) { - translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); - translateLinkLabel.revalidate(); - translateLinkLabel.repaint(); - } - - @Override - public void changedUpdate(DocumentEvent e) { - translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); - translateLinkLabel.revalidate(); - translateLinkLabel.repaint(); - } - }); - translateLinkLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); - translateLinkLabel.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - try { - Desktop.getDesktop().browse(new URI(WeblateIntegration.getWeblateLabelURI(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))))); - } catch (IOException e1) { - e1.printStackTrace(); - } catch (URISyntaxException e1) { - e1.printStackTrace(); - } - } - } - }); - } - } - - public static JTextField addTranslatableTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - final JTextField tfField = addTextField(pane, label, initialValue, editable, listener); - addTranslationPane(pane, tfField, initialValue); - return tfField; - } - - public static String getWeblateLabelLink(String text) { - return "Translate on weblate"; - } - - public static JTextField addTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - final JTextField tfField = new JTextField(initialValue); - addTextComponent(pane, label, editable, listener, tfField, false, false); - tfField.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(tfField, tfField.getText()); - } - }); - return tfField; - } - public static T addTextComponent(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T tfField, boolean specialNewLinesHandling, boolean scrollable) { - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - tfField.setEditable(editable); - JComponent component; - if (scrollable){ - component = new JScrollPane(tfField); - }else{ - component = tfField; - } - tfPane.add(component, JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - tfField.setText(""); - listener.valueChanged(tfField, null); - } - }); - tfField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void removeUpdate(DocumentEvent e) { - String text = tfField.getText(); - if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); - listener.valueChanged(tfField, text); - } - - @Override - public void insertUpdate(DocumentEvent e) { - String text = tfField.getText(); - if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); - listener.valueChanged(tfField, text); - } - - @Override - public void changedUpdate(DocumentEvent e) { - String text = tfField.getText(); - if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); - listener.valueChanged(tfField, text); - } - }); - return tfField; - } - - - public static JTextArea addTranslatableTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - final JTextArea tfArea = addTextArea(pane, label, initialValue, editable, listener); - addTranslationPane(pane, tfArea, initialValue); - return tfArea; - } - - public static JTextArea addTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { - String text = initialValue == null ? "" : initialValue.replaceAll("\\n", "\n"); - final JTextArea tfArea = new JTextArea(text); - tfArea.setRows(2); - tfArea.setLineWrap(true); - tfArea.setWrapStyleWord(true); - - addTextComponent(pane, label, editable, listener, tfArea, true, true); - return tfArea; - } - -// public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, boolean allowNegatives, boolean editable) { -// return addIntegerField(pane, label, initialValue, allowNegatives, editable, nullListener); -// } - - public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { - return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener); - } - - public static > JSpinner addNumberField(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T minimum, T maximum, Number stepSize, Number value, Number defaultValue) { - JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - if (!(((minimum == null) || (((Comparable)minimum).compareTo(value) <= 0)) && - ((maximum == null) || (((Comparable)maximum).compareTo(value) >= 0)))) { - try{ - throw new IllegalArgumentException("Value for number field outside of range: %s <= %s <= %s".formatted(minimum, value, maximum)); - }catch (IllegalArgumentException e){ - e.printStackTrace(); - value = defaultValue; - } - } - final JSpinner spinner = new JSpinner(new SpinnerNumberModel(value, minimum, maximum, stepSize)); - ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - spinner.setEnabled(editable); - ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(spinner, JideBoxLayout.VARY); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - spinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - listener.valueChanged(spinner, spinner.getValue()); - } - }); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - spinner.setValue(0); - listener.valueChanged(spinner, null); - } - }); - return spinner; - } - public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { - int value = initialValue != null ? initialValue : defaultValue; - int minimum = allowNegatives ? Integer.MIN_VALUE : 0; - int maxValue = Integer.MAX_VALUE; - return addNumberField(pane, label, editable, listener, minimum, maxValue, 1, value, defaultValue); - } - - - private static final String percent = "%"; - private static final String ratio = "x/y"; - - public static JComponent addChanceField(JPanel pane, String label, String initialValue, String defaultValue, boolean editable, final FieldUpdateListener listener) { - int defaultChance = 1; - int defaultMaxChance = 100; - if (defaultValue != null) { - if (defaultValue.contains("/")) { - int c = defaultValue.indexOf('/'); - try { - defaultChance = Integer.parseInt(defaultValue.substring(0, c)); - } catch (NumberFormatException nfe) { - } - try { - defaultMaxChance = Integer.parseInt(defaultValue.substring(c + 1)); - } catch (NumberFormatException nfe) { - } - } else { - try { - defaultChance = Integer.parseInt(defaultValue); - } catch (NumberFormatException nfe) { - } - } - } - - boolean currentFormIsRatio = true; - int chance = defaultChance; - int maxChance = defaultMaxChance; - if (initialValue != null) { - if (initialValue.contains("/")) { - int c = initialValue.indexOf('/'); - try { - chance = Integer.parseInt(initialValue.substring(0, c)); - } catch (NumberFormatException nfe) { - } - try { - maxChance = Integer.parseInt(initialValue.substring(c + 1)); - } catch (NumberFormatException nfe) { - } - } else { - try { - chance = Integer.parseInt(initialValue); - currentFormIsRatio = false; - } catch (NumberFormatException nfe) { - } - } - } - - final JPanel tfPane = new JPanel(); - tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel tfLabel = new JLabel(label); - tfPane.add(tfLabel, JideBoxLayout.FIX); - - final JComboBox entryTypeBox = new JComboBox(new String[]{percent, ratio}); - if (currentFormIsRatio) { - entryTypeBox.setSelectedItem(ratio); - } else { - entryTypeBox.setSelectedItem(percent); - } - entryTypeBox.setEnabled(editable); - tfPane.add(entryTypeBox, JideBoxLayout.FIX); - /////////////////////////////////////////////////////////////////////////////////////////////////// make sure "chance" is between 1 and 100. If lower than 1 get 1. If higher than 100, get chance/maxChance * 100... Then do the same with defaultChance, in case no value exist. - final SpinnerNumberModel percentModel = new SpinnerNumberModel(initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 / defaultMaxChance)), 1, 100, 1); - final SpinnerNumberModel ratioChanceModel = new SpinnerNumberModel(initialValue != null ? chance : defaultChance, 1, Integer.MAX_VALUE, 1); - - final JSpinner chanceSpinner = new JSpinner(currentFormIsRatio ? ratioChanceModel : percentModel); - if (!currentFormIsRatio) - ((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - chanceSpinner.setEnabled(editable); - ((DefaultFormatter) ((NumberEditor) chanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(chanceSpinner, JideBoxLayout.FLEXIBLE); - - final JLabel ratioLabel = new JLabel("/"); - tfPane.add(ratioLabel, JideBoxLayout.FIX); - - final JSpinner maxChanceSpinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? maxChance : defaultMaxChance, 1, Integer.MAX_VALUE, 1)); - ((JSpinner.DefaultEditor) maxChanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - maxChanceSpinner.setEnabled(editable); - ((DefaultFormatter) ((NumberEditor) maxChanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); - tfPane.add(maxChanceSpinner, JideBoxLayout.FLEXIBLE); - - if (!currentFormIsRatio) { - ratioLabel.setVisible(false); - maxChanceSpinner.setVisible(false); - tfPane.revalidate(); - tfPane.repaint(); - } - - final JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - tfPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(editable); - pane.add(tfPane, JideBoxLayout.FIX); - - entryTypeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (entryTypeBox.getSelectedItem() == percent) { - int chance = ((Integer) chanceSpinner.getValue()); - int maxChance = ((Integer) maxChanceSpinner.getValue()); - chance *= 100; - chance /= maxChance; - chance = Math.max(0, Math.min(100, chance)); - chanceSpinner.setModel(percentModel); - chanceSpinner.setValue(chance); - ((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); - ratioLabel.setVisible(false); - maxChanceSpinner.setVisible(false); - tfPane.revalidate(); - tfPane.repaint(); - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); - } else if (entryTypeBox.getSelectedItem() == ratio) { - int chance = ((Integer) chanceSpinner.getValue()); - chanceSpinner.setModel(ratioChanceModel); - chanceSpinner.setValue(chance); - maxChanceSpinner.setValue(100); - ratioLabel.setVisible(true); - maxChanceSpinner.setVisible(true); - tfPane.revalidate(); - tfPane.repaint(); - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); - } - } - }); - chanceSpinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - if (entryTypeBox.getSelectedItem() == percent) { - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); - } else if (entryTypeBox.getSelectedItem() == ratio) { - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); - } - } - }); - maxChanceSpinner.addChangeListener(new ChangeListener() { - @Override - public void stateChanged(ChangeEvent e) { - listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); - } - }); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - chanceSpinner.setValue(1); - listener.valueChanged(chanceSpinner, null); - } - }); - return chanceSpinner; - } - -// public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable) { -// return addDoubleField(pane, label, initialValue, editable, nullListener); -// } - - public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) { - double minimum = 0.0d; - double defaultValue = 0.0d; - double value = initialValue != null ? initialValue : minimum; - double maximum = new Float(Float.MAX_VALUE).doubleValue(); - return addNumberField(pane, label, editable, listener, minimum, maximum, 1.0d, value, defaultValue); - } - - public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) { - return addIntegerBasedCheckBox(pane, label, initialValue, editable, nullListener); - } - - public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable, final FieldUpdateListener listener) { - JPanel ibcbPane = new JPanel(); - ibcbPane.setLayout(new BorderLayout()); - final IntegerBasedCheckBox ibcb = new IntegerBasedCheckBox(); - ibcb.setText(label); - ibcb.setIntegerValue(initialValue); - ibcb.setEnabled(editable); - ibcbPane.add(ibcb, BorderLayout.WEST); - ibcbPane.add(new JPanel(), BorderLayout.CENTER); - pane.add(ibcbPane, JideBoxLayout.FIX); - ibcb.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(ibcb, ibcb.getIntegerValue()); - } - }); - return ibcb; - } - - public static BooleanBasedCheckBox addBooleanBasedCheckBox(JPanel pane, String label, Boolean initialValue, boolean editable, final FieldUpdateListener listener) { - JPanel bbcbPane = new JPanel(); - bbcbPane.setLayout(new BorderLayout()); - final BooleanBasedCheckBox bbcb = new BooleanBasedCheckBox(); - bbcb.setText(label); - bbcb.setBooleanValue(initialValue); - bbcb.setEnabled(editable); - bbcbPane.add(bbcb, BorderLayout.WEST); - bbcbPane.add(new JPanel(), BorderLayout.CENTER); - pane.add(bbcbPane, JideBoxLayout.FIX); - bbcb.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(bbcb, bbcb.isSelected()); - } - }); - return bbcb; - } - - @SuppressWarnings("rawtypes") - public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable) { - return addEnumValueBox(pane, label, values, initialValue, writable, new FieldUpdateListener() { - @Override - public void valueChanged(JComponent source, Object value) { - } - }); - } - - @SuppressWarnings("rawtypes") - public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable, final FieldUpdateListener listener) { - JPanel comboPane = new JPanel(); - comboPane.setLayout(new JideBoxLayout(comboPane, JideBoxLayout.LINE_AXIS, 6)); - JLabel comboLabel = new JLabel(label); - comboPane.add(comboLabel, JideBoxLayout.FIX); - @SuppressWarnings("unchecked") final JComboBox enumValuesCombo = new JComboBox(values); - enumValuesCombo.setEnabled(writable); - enumValuesCombo.setSelectedItem(initialValue); - comboPane.add(enumValuesCombo, JideBoxLayout.VARY); - enumValuesCombo.addItemListener(new ItemListener() { - @Override - public void itemStateChanged(ItemEvent e) { - if (e.getStateChange() == ItemEvent.SELECTED) { - listener.valueChanged(enumValuesCombo, e.getItem()); - } - } - }); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - comboPane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(writable); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - enumValuesCombo.setSelectedItem(null); - listener.valueChanged(enumValuesCombo, null); - } - }); - - pane.add(comboPane, JideBoxLayout.FIX); - return enumValuesCombo; - } - - - public MyComboBox addNPCBox(JPanel pane, Project proj, String label, NPC npc, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, npc) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public NPC getTypedElementAt(int index) { - return project.getNPC(index); - } - - @Override - public int getSize() { - return project.getNPCCount() + 1; - } - }; - return addGDEBox(pane, label, npc, NPC.class, comboModel, writable, listener); - } - - public MyComboBox addActorConditionBox(JPanel pane, Project proj, String label, ActorCondition acond, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, acond) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public ActorCondition getTypedElementAt(int index) { - return project.getActorCondition(index); - } - - @Override - public int getSize() { - return project.getActorConditionCount() + 1; - } - }; - return addGDEBox(pane, label, acond, ActorCondition.class, comboModel, writable, listener); - } - - public MyComboBox addItemBox(JPanel pane, Project proj, String label, Item item, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, item) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public Item getTypedElementAt(int index) { - return project.getItem(index); - } - - @Override - public int getSize() { - return project.getItemCount() + 1; - } - }; - return addGDEBox(pane, label, item, Item.class, comboModel, writable, listener); - } - - public MyComboBox addItemCategoryBox(JPanel pane, Project proj, String label, ItemCategory ic, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, ic) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public ItemCategory getTypedElementAt(int index) { - return project.getItemCategory(index); - } - - @Override - public int getSize() { - return project.getItemCategoryCount() + 1; - } - }; - return addGDEBox(pane, label, ic, ItemCategory.class, comboModel, writable, listener); - } - - public MyComboBox addQuestBox(JPanel pane, Project proj, String label, Quest quest, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, quest) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public Quest getTypedElementAt(int index) { - return project.getQuest(index); - } - - @Override - public int getSize() { - return project.getQuestCount() + 1; - } - }; - return addGDEBox(pane, label, quest, Quest.class, comboModel, writable, listener); - } - - public MyComboBox addDroplistBox(JPanel pane, Project proj, String label, Droplist droplist, boolean writable, FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, droplist) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public Droplist getTypedElementAt(int index) { - return project.getDroplist(index); - } - - @Override - public int getSize() { - return project.getDroplistCount() + 1; - } - }; - return addGDEBox(pane, label, droplist, Droplist.class, comboModel, writable, listener); - } - - public MyComboBox addDialogueBox(JPanel pane, Project proj, String label, Dialogue dialogue, boolean writable, final FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, dialogue) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public Dialogue getTypedElementAt(int index) { - return project.getDialogue(index); - } - - @Override - public int getSize() { - return project.getDialogueCount() + 1; - } - }; - return addGDEBox(pane, label, dialogue, Dialogue.class, comboModel, writable, listener); - } - - public MyComboBox addMapBox(JPanel pane, Project proj, String label, TMXMap map, boolean writable, final FieldUpdateListener listener) { - final GDEComboModel comboModel = new GDEComboModel(proj, map) { - private static final long serialVersionUID = 2638082961277241764L; - - @Override - public TMXMap getTypedElementAt(int index) { - return project.getMap(index); - } - - @Override - public int getSize() { - return project.getMapCount() + 1; - } - }; - return addGDEBox(pane, label, map, TMXMap.class, comboModel, writable, listener); - } - - @SuppressWarnings("unchecked") - public MyComboBox addGDEBox(JPanel pane, String label, GameDataElement gde, final Class dataClass, final GDEComboModel comboModel, final boolean writable, final FieldUpdateListener listener) { - JPanel gdePane = new JPanel(); - gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); - JLabel gdeLabel = new JLabel(label); - gdePane.add(gdeLabel, JideBoxLayout.FIX); - final MyComboBox gdeBox = new MyComboBox(dataClass, comboModel); - gdeBox.setRenderer(new GDERenderer(false, writable)); - new ComboBoxSearchable(gdeBox) { - @Override - protected String convertElementToString(Object object) { - if (object == null) return "none"; - else return ((GameDataElement) object).getDesc(); - } - }; - gdeBox.setEnabled(writable); - gdePane.add(gdeBox, JideBoxLayout.VARY); - final JButton goToGde = new JButton((Icon) ((gde != null) ? new ImageIcon(gde.getIcon()) : (writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null))); - goToGde.setEnabled(gde != null || writable); - goToGde.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - GameDataElement selected = ((GameDataElement) comboModel.getSelectedItem()); - if (selected != null) { - ATContentStudio.frame.openEditor(((GameDataElement) comboModel.getSelectedItem())); - ATContentStudio.frame.selectInTree((GameDataElement) comboModel.getSelectedItem()); - } else if (writable) { - JSONCreationWizard wizard = new JSONCreationWizard(((GameDataElement) target).getProject(), dataClass); - wizard.addCreationListener(new JSONCreationWizard.CreationCompletedListener() { - - @Override - public void elementCreated(JSONElement created) { - gdeBox.setSelectedItem(created); - } - }); - wizard.setVisible(true); - } - } - }); - gdePane.add(goToGde, JideBoxLayout.FIX); - gdeBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (gdeBox.getModel().getSelectedItem() == null) { - goToGde.setIcon((writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null)); - goToGde.setEnabled(writable); - } else { - goToGde.setIcon(new ImageIcon(((GameDataElement) comboModel.getSelectedItem()).getIcon())); - goToGde.setEnabled(true); - } - listener.valueChanged(gdeBox, gdeBox.getModel().getSelectedItem()); - } - }); - JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - gdePane.add(nullify, JideBoxLayout.FIX); - nullify.setEnabled(writable); - nullify.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - gdeBox.setSelectedItem(null); - } - }); - pane.add(gdePane, JideBoxLayout.FIX); - - return gdeBox; - } - - public JComboBox addQuestStageBox(JPanel pane, Project proj, String label, Integer initialValue, boolean writable, final FieldUpdateListener listener, Quest quest, @SuppressWarnings("rawtypes") final JComboBox questSelectionBox) { - JPanel gdePane = new JPanel(); - gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); - JLabel gdeLabel = new JLabel(label); - gdePane.add(gdeLabel, JideBoxLayout.FIX); - - QuestStage initial = null; - if (quest != null) { - initial = quest.getStage(initialValue); - } - final QuestStageComboModel comboModel = new QuestStageComboModel(proj, initial, quest); - final JComboBox combo = new JComboBox(comboModel); - combo.setRenderer(new GDERenderer(false, writable)); - new ComboBoxSearchable(combo) { - @Override - protected String convertElementToString(Object object) { - if (object == null) return "none"; - else return ((GameDataElement) object).getDesc(); - } - }; - questSelectionBox.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (comboModel.selected != null) { - Editor.this.target.removeBacklink(comboModel.selected); - } - Quest newQuest = (Quest) questSelectionBox.getSelectedItem(); - comboModel.changeQuest(newQuest); - combo.revalidate(); - } - }); - combo.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(combo, comboModel.selected == null ? null : comboModel.selected.progress); - } - }); - - - combo.setEnabled(writable); - gdePane.add(combo, JideBoxLayout.VARY); - - pane.add(gdePane, JideBoxLayout.FIX); - - return combo; - } - - - @SuppressWarnings({"rawtypes"}) - public JList addBacklinksList(JPanel pane, GameDataElement gde) { - return addBacklinksList(pane, gde, "Elements linking to this one"); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public JList addBacklinksList(JPanel pane, GameDataElement gde, String title) { - final JList list = new JList(new GDEBacklinksListModel(gde)); - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (e.getClickCount() == 2) { - ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); - ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); - } - } - }); - list.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (e.getKeyCode() == KeyEvent.VK_ENTER) { - ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); - ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); - } - } - }); - list.setCellRenderer(new GDERenderer(true, false)); - CollapsiblePanel colPane = new CollapsiblePanel(title); - colPane.setLayout(new JideBoxLayout(colPane, JideBoxLayout.PAGE_AXIS)); - colPane.add(new JScrollPane(list), JideBoxLayout.FIX); - colPane.add(new JPanel(), JideBoxLayout.FIX); - if (gde.getBacklinks() == null || gde.getBacklinks().isEmpty()) { - colPane.collapse(); - } - pane.add(colPane, JideBoxLayout.FIX); - return list; - } - - public static abstract class GDEComboModel extends AbstractListModel implements ComboBoxModel { - - private static final long serialVersionUID = -5854574666510314715L; - - public Project project; - public E selected; - - public GDEComboModel(Project proj, E initial) { - this.project = proj; - this.selected = initial; - } - - @Override - public abstract int getSize(); - - @Override - public E getElementAt(int index) { - if (index == 0) { - return null; - } - return getTypedElementAt(index - 1); - } - - public abstract E getTypedElementAt(int index); - - @SuppressWarnings("unchecked") - @Override - public void setSelectedItem(Object anItem) { - selected = (E) anItem; - } - - @Override - public Object getSelectedItem() { - return selected; - } - - public void itemAdded(E item, int index) { - fireIntervalAdded(this, index, index); - } - - public void itemRemoved(E item, int index) { - fireIntervalRemoved(this, index, index); - } - - } - - public static class GDERenderer extends DefaultListCellRenderer { - - private static final long serialVersionUID = 6819681566800482793L; - - private boolean includeType; - private boolean writable; - - public GDERenderer(boolean includeType, boolean writable) { - super(); - this.includeType = includeType; - this.writable = writable; - } - - @SuppressWarnings("rawtypes") - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (value == null) { - label.setText("None" + (writable ? ". Click on the button to create one." : "")); - } else { - if (includeType && ((GameDataElement) value).getDataType() != null) { - if (value instanceof QuestStage) { - String text = ((GameDataElement) value).getDesc(); - if (text.length() > 60) { - text = text.substring(0, 57) + "..."; - } - label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((Quest) ((QuestStage) value).parent).id + "#" + ((QuestStage) value).progress + ":" + text); - } else { - label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((GameDataElement) value).getDesc()); - } - } else { - if (value instanceof QuestStage) { - String text = ((GameDataElement) value).getDesc(); - if (text.length() > 60) { - text = text.substring(0, 57) + "..."; - } - label.setText(text); - } else { - label.setText(((GameDataElement) value).getDesc()); - } - } - if (((GameDataElement) value).getIcon() == null) { - Notification.addError("Unable to find icon for " + ((GameDataElement) value).getDesc()); - } else { - label.setIcon(new ImageIcon(((GameDataElement) value).getIcon())); - } - } - return label; - } - - } - - public static class QuestStageComboModel extends AbstractListModel implements ComboBoxModel { - - private static final long serialVersionUID = -5854574666510314715L; - - public Project project; - public Quest currentQuest; - public QuestStage selected; - - public QuestStageComboModel(Project proj, QuestStage initial, Quest quest) { - this.project = proj; - this.currentQuest = quest; - this.selected = initial; - } - - @Override - public int getSize() { - if (currentQuest == null) return 1; - return currentQuest.stages.size() + 1; - } - - @Override - public QuestStage getElementAt(int index) { - if (index == 0) { - return null; - } - return currentQuest.stages.get(index - 1); - } - - @Override - public void setSelectedItem(Object anItem) { - selected = (QuestStage) anItem; - } - - @Override - public Object getSelectedItem() { - return selected; - } - - public void itemAdded(QuestStage item, int index) { - fireIntervalAdded(this, index, index); - } - - public void itemRemoved(QuestStage item, int index) { - fireIntervalRemoved(this, index, index); - } - - public void changeQuest(Quest newQuest) { - int size = getSize(); - currentQuest = null; - selected = null; - fireIntervalRemoved(this, 1, size); - currentQuest = newQuest; - fireIntervalAdded(this, 1, getSize()); - } - - } - - - public static class GDEBacklinksListModel implements ListenerCollectionModel { - - GameDataElement source; - - public GDEBacklinksListModel(GameDataElement source) { - super(); - this.source = source; - source.addBacklinkListener(new GameDataElement.BacklinksListener() { - @Override - public void backlinkRemoved(GameDataElement gde) { - fireListChanged(); - } - - @Override - public void backlinkAdded(GameDataElement gde) { - fireListChanged(); - } - }); - } - - @Override - public Collection getElements() { - return source.getBacklinks(); - } - - List listeners = new CopyOnWriteArrayList(); - - @Override - public List getListeners() { - return listeners; - } - - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - public class MyComboBox extends JComboBox implements ProjectElementListener { - - private static final long serialVersionUID = -4184228604170642567L; - - Class dataType; - - public MyComboBox(Class dataType, ComboBoxModel model) { - super(model); - this.dataType = dataType; - Editor.this.addElementListener(dataType, this); - } - - @Override - public void elementAdded(GameDataElement added, int index) { - ((GDEComboModel) getModel()).itemAdded(added, index); - } - - @Override - public void elementRemoved(GameDataElement removed, int index) { - ((GDEComboModel) getModel()).itemRemoved(removed, index); - } - - @Override - public Class getDataType() { - return dataType; - } - - } - - public abstract void targetUpdated(); - - - transient Map, List> projectElementListeners = new HashMap, List>(); - - public void addElementListener(Class interestingType, ProjectElementListener listener) { - if (projectElementListeners.get(interestingType) == null) { - projectElementListeners.put(interestingType, new ArrayList()); - target.getProject().addElementListener(interestingType, this); - } - projectElementListeners.get(interestingType).add(listener); - } - - public void removeElementListener(ProjectElementListener listener) { - if (listener == null) return; - if (projectElementListeners.get(listener.getDataType()) != null) { - projectElementListeners.get(listener.getDataType()).remove(listener); - if (projectElementListeners.get(listener.getDataType()).isEmpty()) { - target.getProject().removeElementListener(listener.getDataType(), this); - projectElementListeners.remove(listener.getDataType()); - } - } - } - - public void elementAdded(GameDataElement element, int index) { - if (projectElementListeners.get(element.getClass()) != null) { - for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { - l.elementAdded(element, index); - } - } - } - - public void elementRemoved(GameDataElement element, int index) { - if (projectElementListeners.get(element.getClass()) != null) { - for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { - l.elementRemoved(element, index); - } - } - } - - public void clearElementListeners() { - for (Class type : projectElementListeners.keySet()) { - target.getProject().removeElementListener(type, this); - } - } - - public Class getDataType() { - return null; - } - - -} +package com.gpl.rpg.atcontentstudio.ui; + +import com.gpl.rpg.atcontentstudio.ATContentStudio; +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.Project; +import com.gpl.rpg.atcontentstudio.model.ProjectElementListener; +import com.gpl.rpg.atcontentstudio.model.Workspace; +import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.maps.TMXMap; +import com.gpl.rpg.atcontentstudio.utils.WeblateIntegration; +import com.jidesoft.swing.ComboBoxSearchable; +import com.jidesoft.swing.JideBoxLayout; + +import javax.swing.*; +import javax.swing.JSpinner.NumberEditor; +import javax.swing.event.*; +import javax.swing.text.DefaultFormatter; +import javax.swing.text.JTextComponent; +import java.awt.*; +import java.awt.event.*; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.*; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.regex.Matcher; + +public abstract class Editor extends JPanel implements ProjectElementListener { + + private static final long serialVersionUID = 241750514033596878L; + private static final FieldUpdateListener nullListener = new FieldUpdateListener() { + @Override + public void valueChanged(JComponent source, Object value) { + } + }; + + public static final String SAVE = "Save"; + public static final String DELETE = "Delete"; + public static final String REVERT = "Revert to original"; + public static final String ALTER = "Alter"; + public static final String GO_TO_ALTERED = "Go to altered"; + + + public static final String READ_ONLY_MESSAGE = + "" + + "This element is not modifiable.
" + + "Click on the \"Alter\" button to create a writable copy." + + "
"; + + public static final String ALTERED_EXISTS_MESSAGE = + "" + + "This element is not modifiable.
" + + "A writable copy exists in this project. Click on \"Go to altered\" to open it." + + "
"; + + public static final String ALTERED_MESSAGE = + "" + + "This element is a writable copy of an element of the referenced game source.
" + + "Take care not to break existing content when modifying it." + + "
"; + + public static final String CREATED_MESSAGE = + "" + + "This element is a creation of yours.
" + + "Do as you please." + + "
"; + + + public String name = "Editor"; + public Icon icon = null; + public GameDataElement target = null; + + public JLabel message = null; + + + public static JTextField addLabelField(JPanel pane, String label, String value) { + return addTextField(pane, label, value, false, nullListener); + } + + public static void addTranslationPane(JPanel pane, final JTextComponent tfComponent, final String initialValue) { + if (Workspace.activeWorkspace.settings.translatorLanguage.getCurrentValue() != null) { + JPanel labelPane = new JPanel(); + labelPane.setLayout(new JideBoxLayout(labelPane, JideBoxLayout.LINE_AXIS, 6)); + final JLabel translateLinkLabel = new JLabel(getWeblateLabelLink(initialValue)); + labelPane.add(translateLinkLabel, JideBoxLayout.FIX); + labelPane.add(new JLabel(" "), JideBoxLayout.FIX); + final JLabel translationStatus = new JLabel("Retrieving..."); + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusUnknownIcon())); + translationStatus.setToolTipText("Connecting to weblate..."); + labelPane.add(translationStatus, JideBoxLayout.VARY); + new Thread() { + public void run() { + WeblateIntegration.WeblateTranslationUnit unit = WeblateIntegration.getTranslationUnit(initialValue); + switch (unit.status) { + case absent: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); + translationStatus.setToolTipText("This string isn't managed by weblate (yet)."); + break; + case done: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusGreenIcon())); + translationStatus.setToolTipText("This string is translated on weblate."); + break; + case fuzzy: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); + translationStatus.setToolTipText("This string is translated on weblate, but needs a review."); + break; + case notTranslated: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); + translationStatus.setToolTipText("This string isn't translated in your language on weblate yet."); + break; + case warning: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusOrangeIcon())); + translationStatus.setToolTipText("This string is translated on weblate, but triggered some weblate checks."); + break; + case error: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusRedIcon())); + translationStatus.setToolTipText("Cannot connect to weblate. Check internet connection and firewall settings."); + break; + case notAllowed: + translationStatus.setIcon(new ImageIcon(DefaultIcons.getStatusBlueIcon())); + translationStatus.setToolTipText("You have not allowed ATCS to access to internet. You can change this in the workspace settings."); + break; + } + translationStatus.setText(unit.translatedText); + } + + }.start(); + pane.add(labelPane, JideBoxLayout.FIX); + tfComponent.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); + translateLinkLabel.revalidate(); + translateLinkLabel.repaint(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); + translateLinkLabel.revalidate(); + translateLinkLabel.repaint(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + translateLinkLabel.setText(getWeblateLabelLink(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n")))); + translateLinkLabel.revalidate(); + translateLinkLabel.repaint(); + } + }); + translateLinkLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); + translateLinkLabel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + try { + Desktop.getDesktop().browse(new URI(WeblateIntegration.getWeblateLabelURI(tfComponent.getText().replaceAll("\n", Matcher.quoteReplacement("\n"))))); + } catch (IOException e1) { + e1.printStackTrace(); + } catch (URISyntaxException e1) { + e1.printStackTrace(); + } + } + } + }); + } + } + + public static JTextField addTranslatableTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + final JTextField tfField = addTextField(pane, label, initialValue, editable, listener); + addTranslationPane(pane, tfField, initialValue); + return tfField; + } + + public static String getWeblateLabelLink(String text) { + return "Translate on weblate"; + } + + public static JTextField addTextField(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + final JTextField tfField = new JTextField(initialValue); + addTextComponent(pane, label, editable, listener, tfField, false, false); + tfField.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(tfField, tfField.getText()); + } + }); + return tfField; + } + public static T addTextComponent(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T tfField, boolean specialNewLinesHandling, boolean scrollable) { + JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + tfField.setEditable(editable); + JComponent component; + if (scrollable){ + component = new JScrollPane(tfField); + }else{ + component = tfField; + } + tfPane.add(component, JideBoxLayout.VARY); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + tfField.setText(""); + listener.valueChanged(tfField, null); + } + }); + tfField.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void removeUpdate(DocumentEvent e) { + String text = tfField.getText(); + if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + listener.valueChanged(tfField, text); + } + + @Override + public void insertUpdate(DocumentEvent e) { + String text = tfField.getText(); + if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + listener.valueChanged(tfField, text); + } + + @Override + public void changedUpdate(DocumentEvent e) { + String text = tfField.getText(); + if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + listener.valueChanged(tfField, text); + } + }); + return tfField; + } + + + public static JTextArea addTranslatableTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + final JTextArea tfArea = addTextArea(pane, label, initialValue, editable, listener); + addTranslationPane(pane, tfArea, initialValue); + return tfArea; + } + + public static JTextArea addTextArea(JPanel pane, String label, String initialValue, boolean editable, final FieldUpdateListener listener) { + String text = initialValue == null ? "" : initialValue.replaceAll("\\n", "\n"); + final JTextArea tfArea = new JTextArea(text); + tfArea.setRows(2); + tfArea.setLineWrap(true); + tfArea.setWrapStyleWord(true); + + addTextComponent(pane, label, editable, listener, tfArea, true, true); + return tfArea; + } + +// public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, boolean allowNegatives, boolean editable) { +// return addIntegerField(pane, label, initialValue, allowNegatives, editable, nullListener); +// } + + public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { + return addIntegerField(pane, label, initialValue, 0, allowNegatives, editable, listener); + } + + public static > JSpinner addNumberField(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T minimum, T maximum, Number stepSize, T value, T defaultValue) { + JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + if (!(((minimum == null) || (minimum.compareTo(value) <= 0)) && + ((maximum == null) || (maximum.compareTo(value) >= 0)))) { + System.err.printf("Value for number field outside of range: %s <= %s <= %s is false%n", minimum, value, maximum); + value = defaultValue; + } + final JSpinner spinner = new JSpinner(new SpinnerNumberModel(value, minimum, maximum, stepSize)); + ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + spinner.setEnabled(editable); + ((DefaultFormatter) ((NumberEditor) spinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); + tfPane.add(spinner, JideBoxLayout.VARY); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + spinner.addChangeListener(e -> listener.valueChanged(spinner, spinner.getValue())); + nullify.addActionListener(e -> { + spinner.setValue(0); + listener.valueChanged(spinner, null); + }); + return spinner; + } + public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { + int value = initialValue != null ? initialValue : defaultValue; + int minimum = allowNegatives ? Integer.MIN_VALUE : 0; + int maximum = Integer.MAX_VALUE; + return addNumberField(pane, label, editable, listener, minimum, maximum, 1, value, defaultValue); + } + + + private static final String percent = "%"; + private static final String ratio = "x/y"; + + public static JComponent addChanceField(JPanel pane, String label, String initialValue, String defaultValue, boolean editable, final FieldUpdateListener listener) { + int defaultChance = 1; + int defaultMaxChance = 100; + if (defaultValue != null) { + if (defaultValue.contains("/")) { + int c = defaultValue.indexOf('/'); + try { + defaultChance = Integer.parseInt(defaultValue.substring(0, c)); + } catch (NumberFormatException nfe) { + } + try { + defaultMaxChance = Integer.parseInt(defaultValue.substring(c + 1)); + } catch (NumberFormatException nfe) { + } + } else { + try { + defaultChance = Integer.parseInt(defaultValue); + } catch (NumberFormatException nfe) { + } + } + } + + boolean currentFormIsRatio = true; + int chance = defaultChance; + int maxChance = defaultMaxChance; + if (initialValue != null) { + if (initialValue.contains("/")) { + int c = initialValue.indexOf('/'); + try { + chance = Integer.parseInt(initialValue.substring(0, c)); + } catch (NumberFormatException nfe) { + } + try { + maxChance = Integer.parseInt(initialValue.substring(c + 1)); + } catch (NumberFormatException nfe) { + } + } else { + try { + chance = Integer.parseInt(initialValue); + currentFormIsRatio = false; + } catch (NumberFormatException nfe) { + } + } + } + + final JPanel tfPane = new JPanel(); + tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel tfLabel = new JLabel(label); + tfPane.add(tfLabel, JideBoxLayout.FIX); + + final JComboBox entryTypeBox = new JComboBox(new String[]{percent, ratio}); + if (currentFormIsRatio) { + entryTypeBox.setSelectedItem(ratio); + } else { + entryTypeBox.setSelectedItem(percent); + } + entryTypeBox.setEnabled(editable); + tfPane.add(entryTypeBox, JideBoxLayout.FIX); + /////////////////////////////////////////////////////////////////////////////////////////////////// make sure "chance" is between 1 and 100. If lower than 1 get 1. If higher than 100, get chance/maxChance * 100... Then do the same with defaultChance, in case no value exist. + final SpinnerNumberModel percentModel = new SpinnerNumberModel(initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 / defaultMaxChance)), 1, 100, 1); + final SpinnerNumberModel ratioChanceModel = new SpinnerNumberModel(initialValue != null ? chance : defaultChance, 1, Integer.MAX_VALUE, 1); + + final JSpinner chanceSpinner = new JSpinner(currentFormIsRatio ? ratioChanceModel : percentModel); + if (!currentFormIsRatio) + ((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + chanceSpinner.setEnabled(editable); + ((DefaultFormatter) ((NumberEditor) chanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); + tfPane.add(chanceSpinner, JideBoxLayout.FLEXIBLE); + + final JLabel ratioLabel = new JLabel("/"); + tfPane.add(ratioLabel, JideBoxLayout.FIX); + + final JSpinner maxChanceSpinner = new JSpinner(new SpinnerNumberModel(initialValue != null ? maxChance : defaultMaxChance, 1, Integer.MAX_VALUE, 1)); + ((JSpinner.DefaultEditor) maxChanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + maxChanceSpinner.setEnabled(editable); + ((DefaultFormatter) ((NumberEditor) maxChanceSpinner.getEditor()).getTextField().getFormatter()).setCommitsOnValidEdit(true); + tfPane.add(maxChanceSpinner, JideBoxLayout.FLEXIBLE); + + if (!currentFormIsRatio) { + ratioLabel.setVisible(false); + maxChanceSpinner.setVisible(false); + tfPane.revalidate(); + tfPane.repaint(); + } + + final JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + tfPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(editable); + pane.add(tfPane, JideBoxLayout.FIX); + + entryTypeBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (entryTypeBox.getSelectedItem() == percent) { + int chance = ((Integer) chanceSpinner.getValue()); + int maxChance = ((Integer) maxChanceSpinner.getValue()); + chance *= 100; + chance /= maxChance; + chance = Math.max(0, Math.min(100, chance)); + chanceSpinner.setModel(percentModel); + chanceSpinner.setValue(chance); + ((JSpinner.DefaultEditor) chanceSpinner.getEditor()).getTextField().setHorizontalAlignment(JTextField.LEFT); + ratioLabel.setVisible(false); + maxChanceSpinner.setVisible(false); + tfPane.revalidate(); + tfPane.repaint(); + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); + } else if (entryTypeBox.getSelectedItem() == ratio) { + int chance = ((Integer) chanceSpinner.getValue()); + chanceSpinner.setModel(ratioChanceModel); + chanceSpinner.setValue(chance); + maxChanceSpinner.setValue(100); + ratioLabel.setVisible(true); + maxChanceSpinner.setVisible(true); + tfPane.revalidate(); + tfPane.repaint(); + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); + } + } + }); + chanceSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + if (entryTypeBox.getSelectedItem() == percent) { + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString()); + } else if (entryTypeBox.getSelectedItem() == ratio) { + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); + } + } + }); + maxChanceSpinner.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + listener.valueChanged(chanceSpinner, chanceSpinner.getValue().toString() + "/" + maxChanceSpinner.getValue().toString()); + } + }); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + chanceSpinner.setValue(1); + listener.valueChanged(chanceSpinner, null); + } + }); + return chanceSpinner; + } + +// public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable) { +// return addDoubleField(pane, label, initialValue, editable, nullListener); +// } + + public static JSpinner addDoubleField(JPanel pane, String label, Double initialValue, boolean editable, final FieldUpdateListener listener) { + double minimum = 0.0d; + double defaultValue = 0.0d; + double value = initialValue != null ? initialValue : minimum; + double maximum = Float.valueOf(Float.MAX_VALUE).doubleValue(); + return addNumberField(pane, label, editable, listener, minimum, maximum, 1.0d, value, defaultValue); + } + + public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable) { + return addIntegerBasedCheckBox(pane, label, initialValue, editable, nullListener); + } + + public static IntegerBasedCheckBox addIntegerBasedCheckBox(JPanel pane, String label, Integer initialValue, boolean editable, final FieldUpdateListener listener) { + JPanel ibcbPane = new JPanel(); + ibcbPane.setLayout(new BorderLayout()); + final IntegerBasedCheckBox ibcb = new IntegerBasedCheckBox(); + ibcb.setText(label); + ibcb.setIntegerValue(initialValue); + ibcb.setEnabled(editable); + ibcbPane.add(ibcb, BorderLayout.WEST); + ibcbPane.add(new JPanel(), BorderLayout.CENTER); + pane.add(ibcbPane, JideBoxLayout.FIX); + ibcb.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(ibcb, ibcb.getIntegerValue()); + } + }); + return ibcb; + } + + public static BooleanBasedCheckBox addBooleanBasedCheckBox(JPanel pane, String label, Boolean initialValue, boolean editable, final FieldUpdateListener listener) { + JPanel bbcbPane = new JPanel(); + bbcbPane.setLayout(new BorderLayout()); + final BooleanBasedCheckBox bbcb = new BooleanBasedCheckBox(); + bbcb.setText(label); + bbcb.setBooleanValue(initialValue); + bbcb.setEnabled(editable); + bbcbPane.add(bbcb, BorderLayout.WEST); + bbcbPane.add(new JPanel(), BorderLayout.CENTER); + pane.add(bbcbPane, JideBoxLayout.FIX); + bbcb.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(bbcb, bbcb.isSelected()); + } + }); + return bbcb; + } + + @SuppressWarnings("rawtypes") + public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable) { + return addEnumValueBox(pane, label, values, initialValue, writable, new FieldUpdateListener() { + @Override + public void valueChanged(JComponent source, Object value) { + } + }); + } + + @SuppressWarnings("rawtypes") + public static JComboBox addEnumValueBox(JPanel pane, String label, Enum[] values, Enum initialValue, boolean writable, final FieldUpdateListener listener) { + JPanel comboPane = new JPanel(); + comboPane.setLayout(new JideBoxLayout(comboPane, JideBoxLayout.LINE_AXIS, 6)); + JLabel comboLabel = new JLabel(label); + comboPane.add(comboLabel, JideBoxLayout.FIX); + @SuppressWarnings("unchecked") final JComboBox enumValuesCombo = new JComboBox(values); + enumValuesCombo.setEnabled(writable); + enumValuesCombo.setSelectedItem(initialValue); + comboPane.add(enumValuesCombo, JideBoxLayout.VARY); + enumValuesCombo.addItemListener(new ItemListener() { + @Override + public void itemStateChanged(ItemEvent e) { + if (e.getStateChange() == ItemEvent.SELECTED) { + listener.valueChanged(enumValuesCombo, e.getItem()); + } + } + }); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + comboPane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(writable); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + enumValuesCombo.setSelectedItem(null); + listener.valueChanged(enumValuesCombo, null); + } + }); + + pane.add(comboPane, JideBoxLayout.FIX); + return enumValuesCombo; + } + + + public MyComboBox addNPCBox(JPanel pane, Project proj, String label, NPC npc, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, npc) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public NPC getTypedElementAt(int index) { + return project.getNPC(index); + } + + @Override + public int getSize() { + return project.getNPCCount() + 1; + } + }; + return addGDEBox(pane, label, npc, NPC.class, comboModel, writable, listener); + } + + public MyComboBox addActorConditionBox(JPanel pane, Project proj, String label, ActorCondition acond, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, acond) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public ActorCondition getTypedElementAt(int index) { + return project.getActorCondition(index); + } + + @Override + public int getSize() { + return project.getActorConditionCount() + 1; + } + }; + return addGDEBox(pane, label, acond, ActorCondition.class, comboModel, writable, listener); + } + + public MyComboBox addItemBox(JPanel pane, Project proj, String label, Item item, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, item) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public Item getTypedElementAt(int index) { + return project.getItem(index); + } + + @Override + public int getSize() { + return project.getItemCount() + 1; + } + }; + return addGDEBox(pane, label, item, Item.class, comboModel, writable, listener); + } + + public MyComboBox addItemCategoryBox(JPanel pane, Project proj, String label, ItemCategory ic, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, ic) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public ItemCategory getTypedElementAt(int index) { + return project.getItemCategory(index); + } + + @Override + public int getSize() { + return project.getItemCategoryCount() + 1; + } + }; + return addGDEBox(pane, label, ic, ItemCategory.class, comboModel, writable, listener); + } + + public MyComboBox addQuestBox(JPanel pane, Project proj, String label, Quest quest, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, quest) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public Quest getTypedElementAt(int index) { + return project.getQuest(index); + } + + @Override + public int getSize() { + return project.getQuestCount() + 1; + } + }; + return addGDEBox(pane, label, quest, Quest.class, comboModel, writable, listener); + } + + public MyComboBox addDroplistBox(JPanel pane, Project proj, String label, Droplist droplist, boolean writable, FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, droplist) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public Droplist getTypedElementAt(int index) { + return project.getDroplist(index); + } + + @Override + public int getSize() { + return project.getDroplistCount() + 1; + } + }; + return addGDEBox(pane, label, droplist, Droplist.class, comboModel, writable, listener); + } + + public MyComboBox addDialogueBox(JPanel pane, Project proj, String label, Dialogue dialogue, boolean writable, final FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, dialogue) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public Dialogue getTypedElementAt(int index) { + return project.getDialogue(index); + } + + @Override + public int getSize() { + return project.getDialogueCount() + 1; + } + }; + return addGDEBox(pane, label, dialogue, Dialogue.class, comboModel, writable, listener); + } + + public MyComboBox addMapBox(JPanel pane, Project proj, String label, TMXMap map, boolean writable, final FieldUpdateListener listener) { + final GDEComboModel comboModel = new GDEComboModel(proj, map) { + private static final long serialVersionUID = 2638082961277241764L; + + @Override + public TMXMap getTypedElementAt(int index) { + return project.getMap(index); + } + + @Override + public int getSize() { + return project.getMapCount() + 1; + } + }; + return addGDEBox(pane, label, map, TMXMap.class, comboModel, writable, listener); + } + + @SuppressWarnings("unchecked") + public MyComboBox addGDEBox(JPanel pane, String label, GameDataElement gde, final Class dataClass, final GDEComboModel comboModel, final boolean writable, final FieldUpdateListener listener) { + JPanel gdePane = new JPanel(); + gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); + JLabel gdeLabel = new JLabel(label); + gdePane.add(gdeLabel, JideBoxLayout.FIX); + final MyComboBox gdeBox = new MyComboBox(dataClass, comboModel); + gdeBox.setRenderer(new GDERenderer(false, writable)); + new ComboBoxSearchable(gdeBox) { + @Override + protected String convertElementToString(Object object) { + if (object == null) return "none"; + else return ((GameDataElement) object).getDesc(); + } + }; + gdeBox.setEnabled(writable); + gdePane.add(gdeBox, JideBoxLayout.VARY); + final JButton goToGde = new JButton((Icon) ((gde != null) ? new ImageIcon(gde.getIcon()) : (writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null))); + goToGde.setEnabled(gde != null || writable); + goToGde.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + GameDataElement selected = ((GameDataElement) comboModel.getSelectedItem()); + if (selected != null) { + ATContentStudio.frame.openEditor(((GameDataElement) comboModel.getSelectedItem())); + ATContentStudio.frame.selectInTree((GameDataElement) comboModel.getSelectedItem()); + } else if (writable) { + JSONCreationWizard wizard = new JSONCreationWizard(((GameDataElement) target).getProject(), dataClass); + wizard.addCreationListener(new JSONCreationWizard.CreationCompletedListener() { + + @Override + public void elementCreated(JSONElement created) { + gdeBox.setSelectedItem(created); + } + }); + wizard.setVisible(true); + } + } + }); + gdePane.add(goToGde, JideBoxLayout.FIX); + gdeBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (gdeBox.getModel().getSelectedItem() == null) { + goToGde.setIcon((writable ? new ImageIcon(DefaultIcons.getCreateIcon()) : null)); + goToGde.setEnabled(writable); + } else { + goToGde.setIcon(new ImageIcon(((GameDataElement) comboModel.getSelectedItem()).getIcon())); + goToGde.setEnabled(true); + } + listener.valueChanged(gdeBox, gdeBox.getModel().getSelectedItem()); + } + }); + JButton nullify = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); + gdePane.add(nullify, JideBoxLayout.FIX); + nullify.setEnabled(writable); + nullify.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + gdeBox.setSelectedItem(null); + } + }); + pane.add(gdePane, JideBoxLayout.FIX); + + return gdeBox; + } + + public JComboBox addQuestStageBox(JPanel pane, Project proj, String label, Integer initialValue, boolean writable, final FieldUpdateListener listener, Quest quest, @SuppressWarnings("rawtypes") final JComboBox questSelectionBox) { + JPanel gdePane = new JPanel(); + gdePane.setLayout(new JideBoxLayout(gdePane, JideBoxLayout.LINE_AXIS, 6)); + JLabel gdeLabel = new JLabel(label); + gdePane.add(gdeLabel, JideBoxLayout.FIX); + + QuestStage initial = null; + if (quest != null) { + initial = quest.getStage(initialValue); + } + final QuestStageComboModel comboModel = new QuestStageComboModel(proj, initial, quest); + final JComboBox combo = new JComboBox(comboModel); + combo.setRenderer(new GDERenderer(false, writable)); + new ComboBoxSearchable(combo) { + @Override + protected String convertElementToString(Object object) { + if (object == null) return "none"; + else return ((GameDataElement) object).getDesc(); + } + }; + questSelectionBox.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + if (comboModel.selected != null) { + Editor.this.target.removeBacklink(comboModel.selected); + } + Quest newQuest = (Quest) questSelectionBox.getSelectedItem(); + comboModel.changeQuest(newQuest); + combo.revalidate(); + } + }); + combo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(combo, comboModel.selected == null ? null : comboModel.selected.progress); + } + }); + + + combo.setEnabled(writable); + gdePane.add(combo, JideBoxLayout.VARY); + + pane.add(gdePane, JideBoxLayout.FIX); + + return combo; + } + + + @SuppressWarnings({"rawtypes"}) + public JList addBacklinksList(JPanel pane, GameDataElement gde) { + return addBacklinksList(pane, gde, "Elements linking to this one"); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public JList addBacklinksList(JPanel pane, GameDataElement gde, String title) { + final JList list = new JList(new GDEBacklinksListModel(gde)); + list.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); + } + } + }); + list.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + ATContentStudio.frame.openEditor((GameDataElement) list.getSelectedValue()); + ATContentStudio.frame.selectInTree((GameDataElement) list.getSelectedValue()); + } + } + }); + list.setCellRenderer(new GDERenderer(true, false)); + CollapsiblePanel colPane = new CollapsiblePanel(title); + colPane.setLayout(new JideBoxLayout(colPane, JideBoxLayout.PAGE_AXIS)); + colPane.add(new JScrollPane(list), JideBoxLayout.FIX); + colPane.add(new JPanel(), JideBoxLayout.FIX); + if (gde.getBacklinks() == null || gde.getBacklinks().isEmpty()) { + colPane.collapse(); + } + pane.add(colPane, JideBoxLayout.FIX); + return list; + } + + public static abstract class GDEComboModel extends AbstractListModel implements ComboBoxModel { + + private static final long serialVersionUID = -5854574666510314715L; + + public Project project; + public E selected; + + public GDEComboModel(Project proj, E initial) { + this.project = proj; + this.selected = initial; + } + + @Override + public abstract int getSize(); + + @Override + public E getElementAt(int index) { + if (index == 0) { + return null; + } + return getTypedElementAt(index - 1); + } + + public abstract E getTypedElementAt(int index); + + @SuppressWarnings("unchecked") + @Override + public void setSelectedItem(Object anItem) { + selected = (E) anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + + public void itemAdded(E item, int index) { + fireIntervalAdded(this, index, index); + } + + public void itemRemoved(E item, int index) { + fireIntervalRemoved(this, index, index); + } + + } + + public static class GDERenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 6819681566800482793L; + + private boolean includeType; + private boolean writable; + + public GDERenderer(boolean includeType, boolean writable) { + super(); + this.includeType = includeType; + this.writable = writable; + } + + @SuppressWarnings("rawtypes") + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (value == null) { + label.setText("None" + (writable ? ". Click on the button to create one." : "")); + } else { + if (includeType && ((GameDataElement) value).getDataType() != null) { + if (value instanceof QuestStage) { + String text = ((GameDataElement) value).getDesc(); + if (text.length() > 60) { + text = text.substring(0, 57) + "..."; + } + label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((Quest) ((QuestStage) value).parent).id + "#" + ((QuestStage) value).progress + ":" + text); + } else { + label.setText(((GameDataElement) value).getDataType().toString() + "/" + ((GameDataElement) value).getDesc()); + } + } else { + if (value instanceof QuestStage) { + String text = ((GameDataElement) value).getDesc(); + if (text.length() > 60) { + text = text.substring(0, 57) + "..."; + } + label.setText(text); + } else { + label.setText(((GameDataElement) value).getDesc()); + } + } + if (((GameDataElement) value).getIcon() == null) { + Notification.addError("Unable to find icon for " + ((GameDataElement) value).getDesc()); + } else { + label.setIcon(new ImageIcon(((GameDataElement) value).getIcon())); + } + } + return label; + } + + } + + public static class QuestStageComboModel extends AbstractListModel implements ComboBoxModel { + + private static final long serialVersionUID = -5854574666510314715L; + + public Project project; + public Quest currentQuest; + public QuestStage selected; + + public QuestStageComboModel(Project proj, QuestStage initial, Quest quest) { + this.project = proj; + this.currentQuest = quest; + this.selected = initial; + } + + @Override + public int getSize() { + if (currentQuest == null) return 1; + return currentQuest.stages.size() + 1; + } + + @Override + public QuestStage getElementAt(int index) { + if (index == 0) { + return null; + } + return currentQuest.stages.get(index - 1); + } + + @Override + public void setSelectedItem(Object anItem) { + selected = (QuestStage) anItem; + } + + @Override + public Object getSelectedItem() { + return selected; + } + + public void itemAdded(QuestStage item, int index) { + fireIntervalAdded(this, index, index); + } + + public void itemRemoved(QuestStage item, int index) { + fireIntervalRemoved(this, index, index); + } + + public void changeQuest(Quest newQuest) { + int size = getSize(); + currentQuest = null; + selected = null; + fireIntervalRemoved(this, 1, size); + currentQuest = newQuest; + fireIntervalAdded(this, 1, getSize()); + } + + } + + + public static class GDEBacklinksListModel implements ListenerCollectionModel { + + GameDataElement source; + + public GDEBacklinksListModel(GameDataElement source) { + super(); + this.source = source; + source.addBacklinkListener(new GameDataElement.BacklinksListener() { + @Override + public void backlinkRemoved(GameDataElement gde) { + fireListChanged(); + } + + @Override + public void backlinkAdded(GameDataElement gde) { + fireListChanged(); + } + }); + } + + @Override + public Collection getElements() { + return source.getBacklinks(); + } + + List listeners = new CopyOnWriteArrayList(); + + @Override + public List getListeners() { + return listeners; + } + + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public class MyComboBox extends JComboBox implements ProjectElementListener { + + private static final long serialVersionUID = -4184228604170642567L; + + Class dataType; + + public MyComboBox(Class dataType, ComboBoxModel model) { + super(model); + this.dataType = dataType; + Editor.this.addElementListener(dataType, this); + } + + @Override + public void elementAdded(GameDataElement added, int index) { + ((GDEComboModel) getModel()).itemAdded(added, index); + } + + @Override + public void elementRemoved(GameDataElement removed, int index) { + ((GDEComboModel) getModel()).itemRemoved(removed, index); + } + + @Override + public Class getDataType() { + return dataType; + } + + } + + public abstract void targetUpdated(); + + + transient Map, List> projectElementListeners = new HashMap, List>(); + + public void addElementListener(Class interestingType, ProjectElementListener listener) { + if (projectElementListeners.get(interestingType) == null) { + projectElementListeners.put(interestingType, new ArrayList()); + target.getProject().addElementListener(interestingType, this); + } + projectElementListeners.get(interestingType).add(listener); + } + + public void removeElementListener(ProjectElementListener listener) { + if (listener == null) return; + if (projectElementListeners.get(listener.getDataType()) != null) { + projectElementListeners.get(listener.getDataType()).remove(listener); + if (projectElementListeners.get(listener.getDataType()).isEmpty()) { + target.getProject().removeElementListener(listener.getDataType(), this); + projectElementListeners.remove(listener.getDataType()); + } + } + } + + public void elementAdded(GameDataElement element, int index) { + if (projectElementListeners.get(element.getClass()) != null) { + for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { + l.elementAdded(element, index); + } + } + } + + public void elementRemoved(GameDataElement element, int index) { + if (projectElementListeners.get(element.getClass()) != null) { + for (ProjectElementListener l : projectElementListeners.get(element.getClass())) { + l.elementRemoved(element, index); + } + } + } + + public void clearElementListeners() { + for (Class type : projectElementListeners.keySet()) { + target.getProject().removeElementListener(type, this); + } + } + + public Class getDataType() { + return null; + } + + +} From e40fe058dd0b56cee73d1944cde5baf9c06d696c Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 22 Jun 2025 18:57:37 +0200 Subject: [PATCH 36/94] fix oversight, where changes would call the wrong event --- .../atcontentstudio/ui/ListenerListModel.java | 25 ++++++++++++++++--- .../atcontentstudio/ui/NotificationsPane.java | 4 +-- .../ui/OrderedListenerListModel.java | 10 ++++---- .../atcontentstudio/ui/map/TMXMapEditor.java | 6 ++--- 4 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java index 7baf9b6..a90ad3a 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java @@ -8,13 +8,24 @@ import java.util.List; public interface ListenerListModel extends ListModel { List getListeners(); - default void notifyListeners(int event, int index0, int index1) { + default void notifyListeners(ChangeType event, int index0, int index1) { notifyListeners(this, event, index0, index1); } - default void notifyListeners(Object source, int event, int index0, int index1) { + default void notifyListeners(Object source, ChangeType event, int index0, int index1) { + int eventCode = switch (event) { + case CHANGED -> ListDataEvent.CONTENTS_CHANGED; + case ADDED -> ListDataEvent.INTERVAL_ADDED; + case REMOVED -> ListDataEvent.INTERVAL_REMOVED; + }; + for (ListDataListener l : getListeners()) { - l.intervalRemoved(new ListDataEvent(source, event, index0, index1)); + ListDataEvent e = new ListDataEvent(source, eventCode, index0, index1); + switch (event) { + case CHANGED -> l.contentsChanged(e); + case ADDED -> l.intervalAdded(e); + case REMOVED -> l.intervalRemoved(e); + } } } @@ -27,6 +38,12 @@ public interface ListenerListModel extends ListModel { } default void fireListChanged() { - notifyListeners(ListDataEvent.CONTENTS_CHANGED, 0, getSize() - 1); + notifyListeners(this, ChangeType.CHANGED, 0, getSize() - 1); + } + + enum ChangeType { + CHANGED, + ADDED, + REMOVED, } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java index e995d3c..3606b76 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java @@ -74,13 +74,13 @@ public class NotificationsPane extends JList { @Override public void onNewNotification(Notification n) { - notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_ADDED, Notification.notifs.size() - 1, Notification.notifs.size() - 1); + notifyListeners(NotificationsPane.this, ChangeType.ADDED, Notification.notifs.size() - 1, Notification.notifs.size() - 1); NotificationsPane.this.ensureIndexIsVisible(Notification.notifs.indexOf(n)); } @Override public void onListCleared(int i) { - notifyListeners(NotificationsPane.this, ListDataEvent.INTERVAL_REMOVED, 0, i); + notifyListeners(NotificationsPane.this, ChangeType.REMOVED, 0, i); } private List listeners = new CopyOnWriteArrayList(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java index 5e7a0d2..65c8e3e 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java @@ -44,7 +44,7 @@ public abstract class OrderedListenerListModel implements ListenerCollecti } getItems().add(item); int index = getItems().indexOf(item); - notifyListeners(ListDataEvent.INTERVAL_ADDED, index, index); + notifyListeners(ChangeType.ADDED, index, index); } public void removeObject(E item) { @@ -57,7 +57,7 @@ public abstract class OrderedListenerListModel implements ListenerCollecti if (getSize() == 0) { setItems(null); } - notifyListeners(ListDataEvent.INTERVAL_REMOVED, index, index); + notifyListeners(this, ChangeType.REMOVED, index, index); } @@ -74,7 +74,7 @@ public abstract class OrderedListenerListModel implements ListenerCollecti E exchanged = getElementAt(index + direction); setElementAt(index, exchanged); setElementAt(index + direction, item); - notifyListeners(ListDataEvent.CONTENTS_CHANGED, index + direction, index); + notifyListeners(this, ChangeType.CHANGED, index + direction, index); } public void objectChanged(E item) { @@ -83,10 +83,10 @@ public abstract class OrderedListenerListModel implements ListenerCollecti public void itemChanged(E item) { int index = getItems().indexOf(item); - notifyListeners(ListDataEvent.CONTENTS_CHANGED, index, index); + notifyListeners(this, ChangeType.CHANGED, index, index); } - private List listeners = new CopyOnWriteArrayList(); + private final List listeners = new CopyOnWriteArrayList(); public List getListeners() { return listeners; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index a774e5b..825aaf6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -1020,20 +1020,20 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe public void objectChanged(tiled.core.MapLayer layer) { int index = map.tmxMap.getLayerIndex(layer); - notifyListeners(ListDataEvent.CONTENTS_CHANGED, index, index); + notifyListeners(ChangeType.CHANGED, index, index); } public void addObject(tiled.core.MapLayer layer) { map.addLayer(layer); int index = map.tmxMap.getLayerIndex(layer); - notifyListeners(ListDataEvent.INTERVAL_ADDED, index, index); + notifyListeners(ChangeType.ADDED, index, index); } public void removeObject(tiled.core.MapLayer layer) { int index = map.tmxMap.getLayerIndex(layer); map.removeLayer(layer); - notifyListeners(ListDataEvent.INTERVAL_REMOVED, index, index); + notifyListeners(ChangeType.REMOVED, index, index); } List listeners = new CopyOnWriteArrayList(); From 1c7de2b97f5069f039bd67a9fd123646a62538ea Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 22 Jun 2025 18:57:44 +0200 Subject: [PATCH 37/94] misc --- src/com/gpl/rpg/atcontentstudio/ui/Editor.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index 4175412..68e609b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -19,6 +19,7 @@ import javax.swing.text.DefaultFormatter; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.*; +import java.io.Console; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; From 1e25eabb507d3d3c03ba71a843234da2b87e2f56 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 22 Jun 2025 19:13:58 +0200 Subject: [PATCH 38/94] fix deprecated warnings --- .../ui/gamedataeditors/ItemEditor.java | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index a0be7a5..d23a8b5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -659,32 +659,32 @@ public class ItemEditor extends JSONElementEditor { hitSourceConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + listener.valueChanged(hitSourceConditionClear, hitSourceConditionClear.isSelected()); } }); hitSourceConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + listener.valueChanged(hitSourceConditionApply, hitSourceConditionApply.isSelected()); } }); hitSourceConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + listener.valueChanged(hitSourceConditionImmunity, hitSourceConditionImmunity.isSelected()); } }); hitSourceConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + listener.valueChanged(hitSourceConditionTimed, hitSourceConditionTimed.isSelected()); } }); hitSourceConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + listener.valueChanged(hitSourceConditionForever, hitSourceConditionForever.isSelected()); } }); @@ -755,32 +755,32 @@ public class ItemEditor extends JSONElementEditor { hitTargetConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + listener.valueChanged(hitTargetConditionClear, hitTargetConditionClear.isSelected()); } }); hitTargetConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + listener.valueChanged(hitTargetConditionApply, hitTargetConditionApply.isSelected()); } }); hitTargetConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + listener.valueChanged(hitTargetConditionImmunity, hitTargetConditionImmunity.isSelected()); } }); hitTargetConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + listener.valueChanged(hitTargetConditionTimed, hitTargetConditionTimed.isSelected()); } }); hitTargetConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + listener.valueChanged(hitTargetConditionForever, hitTargetConditionForever.isSelected()); } }); @@ -851,32 +851,32 @@ public class ItemEditor extends JSONElementEditor { killSourceConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionClear, new Boolean(killSourceConditionClear.isSelected())); + listener.valueChanged(killSourceConditionClear, killSourceConditionClear.isSelected()); } }); killSourceConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionApply, new Boolean(killSourceConditionApply.isSelected())); + listener.valueChanged(killSourceConditionApply, killSourceConditionApply.isSelected()); } }); killSourceConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionImmunity, new Boolean(killSourceConditionImmunity.isSelected())); + listener.valueChanged(killSourceConditionImmunity, killSourceConditionImmunity.isSelected()); } }); killSourceConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionTimed, new Boolean(killSourceConditionTimed.isSelected())); + listener.valueChanged(killSourceConditionTimed, killSourceConditionTimed.isSelected()); } }); killSourceConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionForever, new Boolean(killSourceConditionForever.isSelected())); + listener.valueChanged(killSourceConditionForever, killSourceConditionForever.isSelected()); } }); @@ -935,13 +935,13 @@ public class ItemEditor extends JSONElementEditor { equipConditionWithMagnitude.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(equipConditionWithMagnitude, new Boolean(equipConditionWithMagnitude.isSelected())); + listener.valueChanged(equipConditionWithMagnitude, equipConditionWithMagnitude.isSelected()); } }); equipConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(equipConditionImmunity, new Boolean(equipConditionImmunity.isSelected())); + listener.valueChanged(equipConditionImmunity, equipConditionImmunity.isSelected()); } }); @@ -995,32 +995,32 @@ public class ItemEditor extends JSONElementEditor { hitReceivedSourceConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); + listener.valueChanged(hitReceivedSourceConditionClear, hitReceivedSourceConditionClear.isSelected()); } }); hitReceivedSourceConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); + listener.valueChanged(hitReceivedSourceConditionApply, hitReceivedSourceConditionApply.isSelected()); } }); hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); + listener.valueChanged(hitReceivedSourceConditionImmunity, hitReceivedSourceConditionImmunity.isSelected()); } }); hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); + listener.valueChanged(hitReceivedSourceConditionTimed, hitReceivedSourceConditionTimed.isSelected()); } }); hitReceivedSourceConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); + listener.valueChanged(hitReceivedSourceConditionForever, hitReceivedSourceConditionForever.isSelected()); } }); @@ -1091,32 +1091,32 @@ public class ItemEditor extends JSONElementEditor { hitReceivedTargetConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); + listener.valueChanged(hitReceivedTargetConditionClear, hitReceivedTargetConditionClear.isSelected()); } }); hitReceivedTargetConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); + listener.valueChanged(hitReceivedTargetConditionApply, hitReceivedTargetConditionApply.isSelected()); } }); hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); + listener.valueChanged(hitReceivedTargetConditionImmunity, hitReceivedTargetConditionImmunity.isSelected()); } }); hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); + listener.valueChanged(hitReceivedTargetConditionTimed, hitReceivedTargetConditionTimed.isSelected()); } }); hitReceivedTargetConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); + listener.valueChanged(hitReceivedTargetConditionForever, hitReceivedTargetConditionForever.isSelected()); } }); From edc4634cbeb5eb678578131d8207b5b2d67517b5 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Sun, 22 Jun 2025 19:48:59 +0200 Subject: [PATCH 39/94] extract some CollapsibleItemLists (in QUEST & NPC) --- .../ui/gamedataeditors/NPCEditor.java | 341 ++++++------------ .../ui/gamedataeditors/QuestEditor.java | 110 ++---- 2 files changed, 130 insertions(+), 321 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 7dc86bb..16a603d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -8,6 +8,9 @@ import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; +import com.gpl.rpg.atcontentstudio.utils.BasicLambda; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithReturn; import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; @@ -248,107 +251,54 @@ public class NPCEditor extends JSONElementEditor { hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); - CollapsiblePanel hitSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - hitSourceConditionsPane.setLayout(new JideBoxLayout(hitSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + String titleSource = "Actor Conditions applied to the source: "; hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); - hitSourceConditionsList = new JList(hitSourceConditionsListModel); - hitSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitSourceConditionsPane.add(new JScrollPane(hitSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectSourceCondition = (Common.TimedConditionEffect) hitSourceConditionsList.getSelectedValue(); - updateHitSourceTimedConditionEditorPane(hitSourceTimedConditionsEditorPane, selectedHitEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitSourceConditionsListModel.addItem(condition); - hitSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectSourceCondition != null) { - hitSourceConditionsListModel.removeItem(selectedHitEffectSourceCondition); - selectedHitEffectSourceCondition = null; - hitSourceConditionsList.clearSelection(); - listener.valueChanged(hitSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); + TimedConditionsCellRenderer cellRendererSource = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetSource = (value)->selectedHitEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetSource = ()->selectedHitEffectSourceCondition ; + BasicLambda selectedResetSource = ()->selectedHitEffectSourceCondition = null; + BasicLambdaWithArg updatePaneSource = (editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener); - listButtonsPane.add(createHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitSourceConditionsPane.add(hitSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + var resultSource = UiUtils.getCollapsibleItemList(listener, + hitSourceConditionsListModel, + selectedResetSource, + selectedSetSource, + selectedGetSource, + (x) -> {}, + updatePaneSource, + npc.writable, + Common.TimedConditionEffect::new, + cellRendererSource, + titleSource, + (x) -> null); + hitSourceConditionsList = resultSource.list; + CollapsiblePanel hitSourceConditionsPane = resultSource.collapsiblePanel; if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { hitSourceConditionsPane.collapse(); } hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); - hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); - hitTargetConditionsList = new JList(hitTargetConditionsListModel); - hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); - updateHitTargetTimedConditionEditorPane(hitTargetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitTargetConditionsListModel.addItem(condition); - hitTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectTargetCondition != null) { - hitTargetConditionsListModel.removeItem(selectedHitEffectTargetCondition); - selectedHitEffectTargetCondition = null; - hitTargetConditionsList.clearSelection(); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsPane.add(hitTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); + String titleTarget = "Actor Conditions applied to the target: "; + hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); + TimedConditionsCellRenderer cellRendererTarget = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetTarget = (value)->selectedHitEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetTarget = ()->selectedHitEffectTargetCondition ; + BasicLambda selectedResetTarget = ()->selectedHitEffectTargetCondition = null; + BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener); + var resultTarget = UiUtils.getCollapsibleItemList(listener, + hitTargetConditionsListModel, + selectedResetTarget, + selectedSetTarget, + selectedGetTarget, + (x) -> {}, + updatePaneTarget, + npc.writable, + Common.TimedConditionEffect::new, + cellRendererTarget, + titleTarget, + (x) -> null); + hitTargetConditionsList = resultTarget.list; + CollapsiblePanel hitTargetConditionsPane = resultTarget.collapsiblePanel; if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { hitTargetConditionsPane.collapse(); } @@ -370,107 +320,53 @@ public class NPCEditor extends JSONElementEditor { hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, npc.writable, listener); hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, npc.writable, listener); - CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to this NPC: "); - hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + String titleReceivedSource = "Actor Conditions applied to this NPC: "; hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); - hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsListModel); - hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); - updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedSourceConditionsListModel.addItem(condition); - hitReceivedSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectSourceCondition != null) { - hitReceivedSourceConditionsListModel.removeItem(selectedHitReceivedEffectSourceCondition); - selectedHitReceivedEffectSourceCondition = null; - hitReceivedSourceConditionsList.clearSelection(); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + TimedConditionsCellRenderer cellRendererReceivedSource = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetReceivedSource = (value)->selectedHitReceivedEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetReceivedSource = ()->selectedHitReceivedEffectSourceCondition ; + BasicLambda selectedResetReceivedSource = ()->selectedHitReceivedEffectSourceCondition = null; + BasicLambdaWithArg updatePaneReceivedSource = (editorPane) -> updateHitReceivedSourceTimedConditionEditorPane(editorPane, selectedHitReceivedEffectSourceCondition, listener); + var resultReceivedSource = UiUtils.getCollapsibleItemList(listener, + hitReceivedSourceConditionsListModel, + selectedResetReceivedSource, + selectedSetReceivedSource, + selectedGetReceivedSource, + (x) -> {}, + updatePaneReceivedSource, + npc.writable, + Common.TimedConditionEffect::new, + cellRendererReceivedSource, + titleReceivedSource, + (x) -> null); + hitReceivedSourceConditionsList = resultReceivedSource.list; + CollapsiblePanel hitReceivedSourceConditionsPane = resultReceivedSource.collapsiblePanel; if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_source == null || npc.hit_received_effect.conditions_source.isEmpty()) { hitReceivedSourceConditionsPane.collapse(); } hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); - hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); - hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsListModel); - hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); - updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedTargetConditionsListModel.addItem(condition); - hitReceivedTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectTargetCondition != null) { - hitReceivedTargetConditionsListModel.removeItem(selectedHitReceivedEffectTargetCondition); - selectedHitReceivedEffectTargetCondition = null; - hitReceivedTargetConditionsList.clearSelection(); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); - hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); + String titleReceivedTarget = "Actor Conditions applied to the attacker: "; + hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); + TimedConditionsCellRenderer cellRendererReceivedTarget = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetReceivedTarget = (value)->selectedHitReceivedEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition ; + BasicLambda selectedResetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition = null; + BasicLambdaWithArg updatePaneReceivedTarget = (editorPane) -> updateHitReceivedTargetTimedConditionEditorPane(editorPane, selectedHitReceivedEffectTargetCondition, listener); + var resultReceivedTarget = UiUtils.getCollapsibleItemList(listener, + hitReceivedTargetConditionsListModel, + selectedResetReceivedTarget, + selectedSetReceivedTarget, + selectedGetReceivedTarget, + (x) -> {}, + updatePaneReceivedTarget, + npc.writable, + Common.TimedConditionEffect::new, + cellRendererReceivedTarget, + titleReceivedTarget, + (x) -> null); + hitReceivedTargetConditionsList = resultReceivedTarget.list; + CollapsiblePanel hitReceivedTargetConditionsPane = resultReceivedTarget.collapsiblePanel; if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_target == null || npc.hit_received_effect.conditions_target.isEmpty()) { hitReceivedTargetConditionsPane.collapse(); } @@ -488,54 +384,27 @@ public class NPCEditor extends JSONElementEditor { deathEffectAPMin = addIntegerField(deathEffectPane, "Killer AP bonus min: ", deathEffect.ap_boost_min, true, npc.writable, listener); deathEffectAPMax = addIntegerField(deathEffectPane, "Killer AP bonus max: ", deathEffect.ap_boost_max, true, npc.writable, listener); - CollapsiblePanel deathSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the killer: "); - deathSourceConditionsPane.setLayout(new JideBoxLayout(deathSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); + String titleDeathSource = "Actor Conditions applied to the killer: "; deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); - deathSourceConditionsList = new JList(deathSourceConditionsListModel); - deathSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - deathSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - deathSourceConditionsPane.add(new JScrollPane(deathSourceConditionsList), JideBoxLayout.FIX); - final JPanel deathSourceTimedConditionsEditorPane = new JPanel(); - final JButton createDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteDeathSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - deathSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedDeathEffectSourceCondition = (Common.TimedConditionEffect) deathSourceConditionsList.getSelectedValue(); - updateDeathSourceTimedConditionEditorPane(deathSourceTimedConditionsEditorPane, selectedDeathEffectSourceCondition, listener); - } - }); - if (npc.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createDeathSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - deathSourceConditionsListModel.addItem(condition); - deathSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteDeathSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedDeathEffectSourceCondition != null) { - deathSourceConditionsListModel.removeItem(selectedDeathEffectSourceCondition); - selectedDeathEffectSourceCondition = null; - deathSourceConditionsList.clearSelection(); - listener.valueChanged(deathSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createDeathSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteDeathSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - deathSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - deathSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(deathSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - deathSourceConditionsPane.add(deathSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + TimedConditionsCellRenderer cellRendererDeathSource = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetDeathSource = (value)->selectedDeathEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetDeathSource = ()->selectedDeathEffectSourceCondition ; + BasicLambda selectedResetDeathSource = ()->selectedDeathEffectSourceCondition = null; + BasicLambdaWithArg updatePaneDeathSource = (editorPane) -> updateDeathSourceTimedConditionEditorPane(editorPane, selectedDeathEffectSourceCondition, listener); + var resultDeathSource = UiUtils.getCollapsibleItemList(listener, + deathSourceConditionsListModel, + selectedResetDeathSource, + selectedSetDeathSource, + selectedGetDeathSource, + (x) -> {}, + updatePaneDeathSource, + npc.writable, + Common.TimedConditionEffect::new, + cellRendererDeathSource, + titleDeathSource, + (x) -> null); + deathSourceConditionsList = resultDeathSource.list; + CollapsiblePanel deathSourceConditionsPane = resultDeathSource.collapsiblePanel; if (npc.death_effect == null || npc.death_effect.conditions_source == null || npc.death_effect.conditions_source.isEmpty()) { deathSourceConditionsPane.collapse(); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java index 5f43fb8..9a352a0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java @@ -6,6 +6,10 @@ import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.utils.BasicLambda; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithReturn; +import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; @@ -57,96 +61,32 @@ public class QuestEditor extends JSONElementEditor { nameField = addTranslatableTextField(pane, "Quest Name: ", quest.name, quest.writable, listener); visibleBox = addIntegerBasedCheckBox(pane, "Visible in quest log", quest.visible_in_log, quest.writable, listener); - CollapsiblePanel stagesPane = new CollapsiblePanel("Quest stages: "); - stagesPane.setLayout(new JideBoxLayout(stagesPane, JideBoxLayout.PAGE_AXIS)); + String title = "Quest stages: "; + StagesCellRenderer cellRenderer = new StagesCellRenderer(); stagesListModel = new StagesListModel(quest); - stagesList = new JList(stagesListModel); - stagesList.setCellRenderer(new StagesCellRenderer()); - stagesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - stagesPane.add(new JScrollPane(stagesList), JideBoxLayout.FIX); - final JPanel stagesEditorPane = new JPanel(); - final JButton createStage = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteStage = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - final JButton moveStageUp = new JButton(new ImageIcon(DefaultIcons.getArrowUpIcon())); - final JButton moveStageDown = new JButton(new ImageIcon(DefaultIcons.getArrowDownIcon())); - deleteStage.setEnabled(false); - moveStageUp.setEnabled(false); - moveStageDown.setEnabled(false); - stagesList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedStage = (QuestStage) stagesList.getSelectedValue(); - if (selectedStage != null) { - deleteStage.setEnabled(true); - moveStageUp.setEnabled(stagesList.getSelectedIndex() > 0); - moveStageDown.setEnabled(stagesList.getSelectedIndex() < (stagesListModel.getSize() - 1)); - } else { - deleteStage.setEnabled(false); - moveStageUp.setEnabled(false); - moveStageDown.setEnabled(false); - } - updateStageEditorPane(stagesEditorPane, selectedStage, listener); - } - }); - if (quest.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createStage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - QuestStage stage = new QuestStage(quest); - stagesListModel.addItem(stage); - stagesList.setSelectedValue(stage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteStage.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.removeItem(selectedStage); - selectedStage = null; - stagesList.clearSelection(); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveStageUp.addActionListener(new ActionListener() { + BasicLambdaWithArg selectedSet = (value)->selectedStage = value; + BasicLambdaWithReturn selectedGet = ()->selectedStage ; + BasicLambda selectedReset = ()->selectedStage = null; + BasicLambdaWithArg updatePane = (editorPane) -> updateStageEditorPane(editorPane, selectedStage, listener); - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.moveUp(selectedStage); - stagesList.setSelectedValue(selectedStage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - moveStageDown.addActionListener(new ActionListener() { + var result = UiUtils.getCollapsibleItemList(listener, + stagesListModel, + selectedReset, + selectedSet, + selectedGet, + (x) -> {}, + updatePane, + quest.writable, + () -> new QuestStage(quest), + cellRenderer, + title, + (x) -> null); + stagesList = result.list; - @Override - public void actionPerformed(ActionEvent e) { - if (selectedStage != null) { - stagesListModel.moveDown(selectedStage); - stagesList.setSelectedValue(selectedStage, true); - listener.valueChanged(new JLabel(), null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createStage, JideBoxLayout.FIX); - listButtonsPane.add(deleteStage, JideBoxLayout.FIX); - listButtonsPane.add(moveStageUp, JideBoxLayout.FIX); - listButtonsPane.add(moveStageDown, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - stagesPane.add(listButtonsPane, JideBoxLayout.FIX); - } if (quest.stages == null || quest.stages.isEmpty()) { - stagesPane.collapse(); + result.collapsiblePanel.collapse(); } - stagesEditorPane.setLayout(new JideBoxLayout(stagesEditorPane, JideBoxLayout.PAGE_AXIS)); - stagesPane.add(stagesEditorPane, JideBoxLayout.FIX); - pane.add(stagesPane, JideBoxLayout.FIX); - + pane.add(result.collapsiblePanel, JideBoxLayout.FIX); } public void updateStageEditorPane(JPanel pane, QuestStage selectedStage, FieldUpdateListener listener) { From 0a18309bfef9d50ef3eedb15fcc8a34c093b3fd7 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 12:36:54 +0200 Subject: [PATCH 40/94] remove some leftover code --- .../gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index d23a8b5..bad3fa5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -284,9 +284,6 @@ public class ItemEditor extends JSONElementEditor { hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); - final JPanel sourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); BasicLambdaWithReturn getSelected = () -> hitSourceConditionsList.getSelectedValue(); BasicLambda resetSelected = () -> { From 5ce84dc1b1615efa37c2d271df059a6a7d46a544 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 13:02:03 +0200 Subject: [PATCH 41/94] extract some CollapsibleItemLists (in ItemEditor) --- .../ui/gamedataeditors/ItemEditor.java | 220 +++++------------- 1 file changed, 64 insertions(+), 156 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index bad3fa5..c8d3a1a 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -210,63 +210,33 @@ public class ItemEditor extends JSONElementEditor { equipIncUseCost = addIntegerField(equipEffectPane, "Increase item use cost: ", equipEffect.increase_use_item_cost, true, item.writable, listener); equipIncReequipCost = addIntegerField(equipEffectPane, "Increase reequip cost: ", equipEffect.increase_reequip_cost, true, item.writable, listener); equipIncAttackCost = addIntegerField(equipEffectPane, "Increase attack cost: ", equipEffect.increase_attack_cost, true, item.writable, listener); - CollapsiblePanel equipConditionsPane = new CollapsiblePanel("Actor Conditions applied when equipped: "); - equipConditionsPane.setLayout(new JideBoxLayout(equipConditionsPane, JideBoxLayout.PAGE_AXIS)); - equipConditionsModel = new ConditionsListModel(equipEffect); - equipConditionsList = new JList(equipConditionsModel); - equipConditionsList.setCellRenderer(new ConditionsCellRenderer()); - equipConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - equipConditionsPane.add(new JScrollPane(equipConditionsList), JideBoxLayout.FIX); - final JPanel equipConditionsEditorPane = new JPanel(); - final JButton createEquipCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteEquipCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - equipConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedEquipEffectCondition = (Common.ConditionEffect) equipConditionsList.getSelectedValue(); - if (selectedEquipEffectCondition == null) { - deleteEquipCondition.setEnabled(false); - } else { - deleteEquipCondition.setEnabled(true); - } - updateEquipConditionEditorPane(equipConditionsEditorPane, selectedEquipEffectCondition, listener); - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createEquipCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.ConditionEffect condition = new Common.ConditionEffect(); - equipConditionsModel.addItem(condition); - equipConditionsList.setSelectedValue(condition, true); - listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteEquipCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedEquipEffectCondition != null) { - equipConditionsModel.removeItem(selectedEquipEffectCondition); - selectedEquipEffectCondition = null; - equipConditionsList.clearSelection(); - listener.valueChanged(equipConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createEquipCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteEquipCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - equipConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - equipConditionsEditorPane.setLayout(new JideBoxLayout(equipConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - equipConditionsPane.add(equipConditionsEditorPane, JideBoxLayout.FIX); + String titleEquipConditions = "Actor Conditions applied when equipped: "; + equipConditionsModel = new ConditionsListModel(equipEffect); + ConditionsCellRenderer cellRendererEquipConditions = new ConditionsCellRenderer(); + BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; + BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; + BasicLambda selectedResetEquipConditions = ()->selectedEquipEffectCondition = null; + BasicLambdaWithArg updatePaneEquipConditions = (editorPane) -> updateEquipConditionEditorPane(editorPane, selectedEquipEffectCondition, listener); + var resultEquipConditions = UiUtils.getCollapsibleItemList(listener, + equipConditionsModel, + selectedResetEquipConditions, + selectedSetEquipConditions, + selectedGetEquipConditions, + (x) -> {}, + updatePaneEquipConditions, + item.writable, + Common.ConditionEffect::new, + cellRendererEquipConditions, + titleEquipConditions, + (x) -> null); + equipConditionsList = resultEquipConditions.list; + CollapsiblePanel equipConditionsPane = resultEquipConditions.collapsiblePanel; if (item.equip_effect == null || item.equip_effect.conditions == null || item.equip_effect.conditions.isEmpty()) { equipConditionsPane.collapse(); } equipEffectPane.add(equipConditionsPane, JideBoxLayout.FIX); + pane.add(equipEffectPane, JideBoxLayout.FIX); if (item.equip_effect == null) { equipEffectPane.collapse(); @@ -317,59 +287,27 @@ public class ItemEditor extends JSONElementEditor { hitSourceConditionsPane.collapse(); } hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the target: "); - hitTargetConditionsPane.setLayout(new JideBoxLayout(hitTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); + String titleHitTargetConditions = "Actor Conditions applied to the target: "; hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); - hitTargetConditionsList = new JList(hitTargetConditionsModel); - hitTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitTargetConditionsPane.add(new JScrollPane(hitTargetConditionsList), JideBoxLayout.FIX); - final JPanel targetTimedConditionsEditorPane = new JPanel(); - final JButton createHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitEffectTargetCondition = (Common.TimedConditionEffect) hitTargetConditionsList.getSelectedValue(); - updateHitTargetTimedConditionEditorPane(targetTimedConditionsEditorPane, selectedHitEffectTargetCondition, listener); - if (selectedHitEffectTargetCondition == null) { - deleteHitTargetCondition.setEnabled(false); - } else { - deleteHitTargetCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitTargetConditionsModel.addItem(condition); - hitTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitEffectTargetCondition != null) { - hitTargetConditionsModel.removeItem(selectedHitEffectTargetCondition); - selectedHitEffectTargetCondition = null; - hitTargetConditionsList.clearSelection(); - listener.valueChanged(hitTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - - listButtonsPane.add(createHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - targetTimedConditionsEditorPane.setLayout(new JideBoxLayout(targetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitTargetConditionsPane.add(targetTimedConditionsEditorPane, JideBoxLayout.FIX); + ConditionsCellRenderer cellRendererHitTargetConditions = new ConditionsCellRenderer(); + BasicLambdaWithArg selectedSetHitTargetConditions = (value)->selectedHitEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetHitTargetConditions = ()->selectedHitEffectTargetCondition ; + BasicLambda selectedResetHitTargetConditions = ()->selectedHitEffectTargetCondition = null; + BasicLambdaWithArg updatePaneHitTargetConditions = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener); + var resultHitTargetConditions = UiUtils.getCollapsibleItemList(listener, + hitTargetConditionsModel, + selectedResetHitTargetConditions, + selectedSetHitTargetConditions, + selectedGetHitTargetConditions, + (x) -> {}, + updatePaneHitTargetConditions, + item.writable, + Common.TimedConditionEffect::new, + cellRendererHitTargetConditions, + titleHitTargetConditions, + (x) -> null); + hitTargetConditionsList = resultHitTargetConditions.list; + CollapsiblePanel hitTargetConditionsPane = resultHitTargetConditions.collapsiblePanel; if (item.hit_effect == null || item.hit_effect.conditions_target == null || item.hit_effect.conditions_target.isEmpty()) { hitTargetConditionsPane.collapse(); } @@ -391,63 +329,33 @@ public class ItemEditor extends JSONElementEditor { killHPMax = addIntegerField(killEffectPane, "HP bonus max: ", killEffect.hp_boost_max, true, item.writable, listener); killAPMin = addIntegerField(killEffectPane, "AP bonus min: ", killEffect.ap_boost_min, true, item.writable, listener); killAPMax = addIntegerField(killEffectPane, "AP bonus max: ", killEffect.ap_boost_max, true, item.writable, listener); - final CollapsiblePanel killSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the source: "); - killSourceConditionsPane.setLayout(new JideBoxLayout(killSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); - killSourceConditionsList = new JList(killSourceConditionsModel); - killSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - killSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - killSourceConditionsPane.add(new JScrollPane(killSourceConditionsList), JideBoxLayout.FIX); - final JPanel killSourceTimedConditionsEditorPane = new JPanel(); - final JButton createKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteKillSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - killSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedKillEffectCondition = (Common.TimedConditionEffect) killSourceConditionsList.getSelectedValue(); - updateKillSourceTimedConditionEditorPane(killSourceTimedConditionsEditorPane, selectedKillEffectCondition, listener); - if (selectedKillEffectCondition == null) { - deleteKillSourceCondition.setEnabled(false); - } else { - deleteKillSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createKillSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - killSourceConditionsModel.addItem(condition); - killSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteKillSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedKillEffectCondition != null) { - killSourceConditionsModel.removeItem(selectedKillEffectCondition); - selectedKillEffectCondition = null; - killSourceConditionsList.clearSelection(); - listener.valueChanged(killSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createKillSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteKillSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - killSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - killSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(killSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - killSourceConditionsPane.add(killSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + String titleKillSourceConditions = "Actor Conditions applied to the source: "; + killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); + TimedConditionsCellRenderer cellRendererKillSourceConditions = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetKillSourceConditions = (value)->selectedKillEffectCondition = value; + BasicLambdaWithReturn selectedGetKillSourceConditions = ()->selectedKillEffectCondition ; + BasicLambda selectedResetKillSourceConditions = ()->selectedKillEffectCondition = null; + BasicLambdaWithArg updatePaneKillSourceConditions = (editorPane) -> updateKillSourceTimedConditionEditorPane(editorPane, selectedKillEffectCondition, listener); + var resultKillSourceConditions = UiUtils.getCollapsibleItemList(listener, + killSourceConditionsModel, + selectedResetKillSourceConditions, + selectedSetKillSourceConditions, + selectedGetKillSourceConditions, + (x) -> {}, + updatePaneKillSourceConditions, + item.writable, + Common.TimedConditionEffect::new, + cellRendererKillSourceConditions, + titleKillSourceConditions, + (x) -> null); + killSourceConditionsList = resultKillSourceConditions.list; + CollapsiblePanel killSourceConditionsPane = resultKillSourceConditions.collapsiblePanel; if (item.kill_effect == null || item.kill_effect.conditions_source == null || item.kill_effect.conditions_source.isEmpty()) { killSourceConditionsPane.collapse(); } killEffectPane.add(killSourceConditionsPane, JideBoxLayout.FIX); + if (item.kill_effect == null) { killEffectPane.collapse(); } From 967bbf918be5f79603c38be86e1629fb8892a485 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 13:21:07 +0200 Subject: [PATCH 42/94] extract some more CollapsibleItemLists (in ItemEditor) --- .../ui/gamedataeditors/ItemEditor.java | 147 +++++------------- 1 file changed, 43 insertions(+), 104 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index c8d3a1a..ab16e96 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -377,120 +377,59 @@ public class ItemEditor extends JSONElementEditor { hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, item.writable, listener); hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, item.writable, listener); hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, item.writable, listener); - final CollapsiblePanel hitReceivedSourceConditionsPane = new CollapsiblePanel("Actor Conditions applied to the player: "); - hitReceivedSourceConditionsPane.setLayout(new JideBoxLayout(hitReceivedSourceConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(hitReceivedEffect); - hitReceivedSourceConditionsList = new JList(hitReceivedSourceConditionsModel); - hitReceivedSourceConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedSourceConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedSourceConditionsPane.add(new JScrollPane(hitReceivedSourceConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedSourceTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedSourceCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedSourceConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectSourceCondition = (Common.TimedConditionEffect) hitReceivedSourceConditionsList.getSelectedValue(); - updateHitReceivedSourceTimedConditionEditorPane(hitReceivedSourceTimedConditionsEditorPane, selectedHitReceivedEffectSourceCondition, listener); - if (selectedHitReceivedEffectSourceCondition == null) { - deleteHitReceivedSourceCondition.setEnabled(false); - } else { - deleteHitReceivedSourceCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedSourceConditionsModel.addItem(condition); - hitReceivedSourceConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedSourceCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectSourceCondition != null) { - hitReceivedSourceConditionsModel.removeItem(selectedHitReceivedEffectSourceCondition); - selectedHitReceivedEffectSourceCondition = null; - hitReceivedSourceConditionsList.clearSelection(); - listener.valueChanged(hitReceivedSourceConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedSourceCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedSourceConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedSourceTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedSourceConditionsPane.add(hitReceivedSourceTimedConditionsEditorPane, JideBoxLayout.FIX); + String titleHitReceivedSourceConditions = "Actor Conditions applied to the player: "; + hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); + TimedConditionsCellRenderer cellRendererHitReceivedSourceConditions = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetHitReceivedSourceConditions = (value)->selectedHitReceivedEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition ; + BasicLambda selectedResetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition = null; + BasicLambdaWithArg updatePaneHitReceivedSourceConditions = (editorPane) -> updateHitReceivedSourceTimedConditionEditorPane(editorPane, selectedHitReceivedEffectSourceCondition, listener); + var resultHitReceivedSourceConditions = UiUtils.getCollapsibleItemList(listener, + hitReceivedSourceConditionsModel, + selectedResetHitReceivedSourceConditions, + selectedSetHitReceivedSourceConditions, + selectedGetHitReceivedSourceConditions, + (x) -> {}, + updatePaneHitReceivedSourceConditions, + item.writable, + Common.TimedConditionEffect::new, + cellRendererHitReceivedSourceConditions, + titleHitReceivedSourceConditions, + (x) -> null); + hitReceivedSourceConditionsList = resultHitReceivedSourceConditions.list; + CollapsiblePanel hitReceivedSourceConditionsPane = resultHitReceivedSourceConditions.collapsiblePanel; if (item.hit_received_effect == null || item.hit_received_effect.conditions_source == null || item.hit_received_effect.conditions_source.isEmpty()) { hitReceivedSourceConditionsPane.collapse(); } hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - final CollapsiblePanel hitReceivedTargetConditionsPane = new CollapsiblePanel("Actor Conditions applied to the attacker: "); - hitReceivedTargetConditionsPane.setLayout(new JideBoxLayout(hitReceivedTargetConditionsPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); - hitReceivedTargetConditionsList = new JList(hitReceivedTargetConditionsModel); - hitReceivedTargetConditionsList.setCellRenderer(new TimedConditionsCellRenderer()); - hitReceivedTargetConditionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hitReceivedTargetConditionsPane.add(new JScrollPane(hitReceivedTargetConditionsList), JideBoxLayout.FIX); - final JPanel hitReceivedTargetTimedConditionsEditorPane = new JPanel(); - final JButton createHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getCreateIcon())); - final JButton deleteHitReceivedTargetCondition = new JButton(new ImageIcon(DefaultIcons.getNullifyIcon())); - hitReceivedTargetConditionsList.addListSelectionListener(new ListSelectionListener() { - @Override - public void valueChanged(ListSelectionEvent e) { - selectedHitReceivedEffectTargetCondition = (Common.TimedConditionEffect) hitReceivedTargetConditionsList.getSelectedValue(); - updateHitReceivedTargetTimedConditionEditorPane(hitReceivedTargetTimedConditionsEditorPane, selectedHitReceivedEffectTargetCondition, listener); - if (selectedHitReceivedEffectTargetCondition == null) { - deleteHitReceivedTargetCondition.setEnabled(false); - } else { - deleteHitReceivedTargetCondition.setEnabled(true); - } - } - }); - if (item.writable) { - JPanel listButtonsPane = new JPanel(); - listButtonsPane.setLayout(new JideBoxLayout(listButtonsPane, JideBoxLayout.LINE_AXIS, 6)); - createHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - Common.TimedConditionEffect condition = new Common.TimedConditionEffect(); - hitReceivedTargetConditionsModel.addItem(condition); - hitReceivedTargetConditionsList.setSelectedValue(condition, true); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - }); - deleteHitReceivedTargetCondition.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - if (selectedHitReceivedEffectTargetCondition != null) { - hitReceivedTargetConditionsModel.removeItem(selectedHitReceivedEffectTargetCondition); - selectedHitReceivedEffectTargetCondition = null; - hitReceivedTargetConditionsList.clearSelection(); - listener.valueChanged(hitReceivedTargetConditionsList, null); //Item changed, but we took care of it, just do the usual notification and JSON update stuff. - } - } - }); - listButtonsPane.add(createHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(deleteHitReceivedTargetCondition, JideBoxLayout.FIX); - listButtonsPane.add(new JPanel(), JideBoxLayout.VARY); - hitReceivedTargetConditionsPane.add(listButtonsPane, JideBoxLayout.FIX); - } - hitReceivedTargetTimedConditionsEditorPane.setLayout(new JideBoxLayout(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.PAGE_AXIS)); - hitReceivedTargetConditionsPane.add(hitReceivedTargetTimedConditionsEditorPane, JideBoxLayout.FIX); + String titleHitReceivedTargetConditions = "Actor Conditions applied to the attacker: "; + hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); + TimedConditionsCellRenderer cellRendererHitReceivedTargetConditions = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetHitReceivedTargetConditions = (value)->selectedHitReceivedEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition ; + BasicLambda selectedResetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition = null; + BasicLambdaWithArg updatePaneHitReceivedTargetConditions = (editorPane) -> updateHitReceivedTargetTimedConditionEditorPane(editorPane, selectedHitReceivedEffectTargetCondition, listener); + var resultHitReceivedTargetConditions = UiUtils.getCollapsibleItemList(listener, + hitReceivedTargetConditionsModel, + selectedResetHitReceivedTargetConditions, + selectedSetHitReceivedTargetConditions, + selectedGetHitReceivedTargetConditions, + (x) -> {}, + updatePaneHitReceivedTargetConditions, + item.writable, + Common.TimedConditionEffect::new, + cellRendererHitReceivedTargetConditions, + titleHitReceivedTargetConditions, + (x) -> null); + hitReceivedTargetConditionsList = resultHitReceivedTargetConditions.list; + CollapsiblePanel hitReceivedTargetConditionsPane = resultHitReceivedTargetConditions.collapsiblePanel; if (item.hit_received_effect == null || item.hit_received_effect.conditions_target == null || item.hit_received_effect.conditions_target.isEmpty()) { hitReceivedTargetConditionsPane.collapse(); } hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); + if (item.hit_received_effect == null) { hitReceivedEffectPane.collapse(); } From e9fecee876bb0157b40e33d1cd1dee433cfe510b Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 14:03:13 +0200 Subject: [PATCH 43/94] extract some code into updateConditionEffect (ITEM & NPC) --- .../gpl/rpg/atcontentstudio/ui/Editor.java | 17 +++++ .../ui/gamedataeditors/ItemEditor.java | 72 ++----------------- .../ui/gamedataeditors/NPCEditor.java | 24 +------ 3 files changed, 25 insertions(+), 88 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index 68e609b..01fb226 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -1106,4 +1106,21 @@ public abstract class Editor extends JPanel implements ProjectElementListener { } + protected > void updateConditionEffect(ActorCondition value, + GameDataElement backlink, + E selectedHitEffectTargetCondition, + T hitTargetConditionsModel) { + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition.removeBacklink(backlink); + } + selectedHitEffectTargetCondition.condition = value; + if (selectedHitEffectTargetCondition.condition != null) { + selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; + selectedHitEffectTargetCondition.condition.addBacklink(backlink); + } else { + selectedHitEffectTargetCondition.condition_id = null; + } + hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + } + } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index ab16e96..277af68 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -1312,17 +1312,7 @@ public class ItemEditor extends JSONElementEditor { } else if (source == equipConditionsList) { updateEquip = true; } else if (source == equipConditionBox) { - if (selectedEquipEffectCondition.condition != null) { - selectedEquipEffectCondition.condition.removeBacklink(item); - } - selectedEquipEffectCondition.condition = (ActorCondition) value; - if (selectedEquipEffectCondition.condition != null) { - selectedEquipEffectCondition.condition_id = selectedEquipEffectCondition.condition.id; - selectedEquipEffectCondition.condition.addBacklink(item); - } else { - selectedEquipEffectCondition.condition_id = null; - } - equipConditionsModel.itemChanged(selectedEquipEffectCondition); + updateConditionEffect((ActorCondition) value, item, selectedEquipEffectCondition, equipConditionsModel); } else if (source == equipConditionMagnitude) { selectedEquipEffectCondition.magnitude = (Integer) value; equipConditionsModel.itemChanged(selectedEquipEffectCondition); @@ -1353,17 +1343,7 @@ public class ItemEditor extends JSONElementEditor { } else if (source == hitSourceConditionsList) { updateHit = true; } else if (source == hitSourceConditionBox) { - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.removeBacklink(item); - } - selectedHitEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; - selectedHitEffectSourceCondition.condition.addBacklink(item); - } else { - selectedHitEffectSourceCondition.condition_id = null; - } - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); + updateConditionEffect((ActorCondition)value, item, selectedHitEffectSourceCondition, hitSourceConditionsModel); updateHit = true; } else if (source == hitSourceConditionClear && (Boolean) value) { selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; @@ -1417,17 +1397,7 @@ public class ItemEditor extends JSONElementEditor { } else if (source == hitTargetConditionsList) { updateHit = true; } else if (source == hitTargetConditionBox) { - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition.removeBacklink(item); - } - selectedHitEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; - selectedHitEffectTargetCondition.condition.addBacklink(item); - } else { - selectedHitEffectTargetCondition.condition_id = null; - } - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); + updateConditionEffect((ActorCondition)value, item, selectedHitEffectTargetCondition, hitTargetConditionsModel); updateHit = true; } else if (source == hitTargetConditionClear && (Boolean) value) { selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; @@ -1497,17 +1467,7 @@ public class ItemEditor extends JSONElementEditor { } else if (source == killSourceConditionsList) { updateKill = true; } else if (source == killSourceConditionBox) { - if (selectedKillEffectCondition.condition != null) { - selectedKillEffectCondition.condition.removeBacklink(item); - } - selectedKillEffectCondition.condition = (ActorCondition) value; - if (selectedKillEffectCondition.condition != null) { - selectedKillEffectCondition.condition_id = selectedKillEffectCondition.condition.id; - selectedKillEffectCondition.condition.addBacklink(item); - } else { - selectedKillEffectCondition.condition_id = null; - } - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); + updateConditionEffect((ActorCondition) value, item, selectedKillEffectCondition, killSourceConditionsModel); updateKill = true; } else if (source == killSourceConditionClear && (Boolean) value) { selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; @@ -1593,17 +1553,7 @@ public class ItemEditor extends JSONElementEditor { } else if (source == hitReceivedSourceConditionsList) { updateHitReceived = true; } else if (source == hitReceivedSourceConditionBox) { - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.removeBacklink(item); - } - selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; - selectedHitReceivedEffectSourceCondition.condition.addBacklink(item); - } else { - selectedHitReceivedEffectSourceCondition.condition_id = null; - } - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); + updateConditionEffect((ActorCondition) value, item, selectedHitReceivedEffectSourceCondition, hitReceivedSourceConditionsModel); updateHitReceived = true; } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; @@ -1657,17 +1607,7 @@ public class ItemEditor extends JSONElementEditor { } else if (source == hitReceivedTargetConditionsList) { updateHitReceived = true; } else if (source == hitReceivedTargetConditionBox) { - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition.removeBacklink(item); - } - selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; - selectedHitReceivedEffectTargetCondition.condition.addBacklink(item); - } else { - selectedHitReceivedEffectTargetCondition.condition_id = null; - } - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateConditionEffect((ActorCondition) value, item, selectedHitReceivedEffectTargetCondition, hitReceivedTargetConditionsModel); updateHitReceived = true; } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 16a603d..23274ce 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -1134,17 +1134,7 @@ public class NPCEditor extends JSONElementEditor { } else if (source == hitTargetConditionsList) { updateHit = true; } else if (source == hitTargetConditionBox) { - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition.removeBacklink(npc); - } - selectedHitEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitEffectTargetCondition.condition != null) { - selectedHitEffectTargetCondition.condition_id = selectedHitEffectTargetCondition.condition.id; - selectedHitEffectTargetCondition.condition.addBacklink(npc); - } else { - selectedHitEffectTargetCondition.condition_id = null; - } - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateConditionEffect((ActorCondition) value, npc, selectedHitEffectTargetCondition, hitTargetConditionsListModel); } else if (source == hitTargetConditionClear && (Boolean) value) { selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; selectedHitEffectTargetCondition.duration = null; @@ -1282,17 +1272,7 @@ public class NPCEditor extends JSONElementEditor { } else if (source == hitReceivedTargetConditionsList) { updateHitReceived = true; } else if (source == hitReceivedTargetConditionBox) { - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition.removeBacklink(npc); - } - selectedHitReceivedEffectTargetCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectTargetCondition.condition != null) { - selectedHitReceivedEffectTargetCondition.condition_id = selectedHitReceivedEffectTargetCondition.condition.id; - selectedHitReceivedEffectTargetCondition.condition.addBacklink(npc); - } else { - selectedHitReceivedEffectTargetCondition.condition_id = null; - } - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); + updateConditionEffect((ActorCondition) value, npc, selectedHitReceivedEffectTargetCondition, hitReceivedTargetConditionsListModel); } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; selectedHitReceivedEffectTargetCondition.duration = null; From 517a798b6f7b2d2902ab0c2922627c75970eb8fd Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 14:31:06 +0200 Subject: [PATCH 44/94] extract BasicEffect and rename TimedConditionEffect to TimedActorConditionEffect --- .../model/gamedata/Common.java | 52 +- .../atcontentstudio/model/gamedata/Item.java | 28 +- .../atcontentstudio/model/gamedata/NPC.java | 1162 ++++++++--------- .../gpl/rpg/atcontentstudio/ui/Editor.java | 9 +- .../ui/gamedataeditors/ItemEditor.java | 106 +- .../ui/gamedataeditors/NPCEditor.java | 84 +- .../atcontentstudio/ui/tools/GDEVisitor.java | 10 +- 7 files changed, 727 insertions(+), 724 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 0c58eea..50acb0a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -9,22 +9,22 @@ import java.util.Map; public final class Common { - public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { + public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { if (conditions != null) { - for (ConditionEffect ce : conditions) { + for (ActorConditionEffect ce : conditions) { if (ce.condition_id != null) ce.condition = proj.getActorCondition(ce.condition_id); if (ce.condition != null) ce.condition.addBacklink(backlink); } } } - public static class TimedConditionEffect extends ConditionEffect { + public static class TimedActorConditionEffect extends ActorConditionEffect { //Available from parsed state public Integer duration = null; public Double chance = null; - public TimedConditionEffect createClone() { - TimedConditionEffect cclone = new TimedConditionEffect(); + public TimedActorConditionEffect createClone() { + TimedActorConditionEffect cclone = new TimedActorConditionEffect(); cclone.magnitude = this.magnitude; cclone.condition_id = this.condition_id; cclone.condition = this.condition; @@ -34,7 +34,7 @@ public final class Common { } } - public static class ConditionEffect { + public static class ActorConditionEffect { //Available from parsed state public Integer magnitude = null; public String condition_id = null; @@ -44,13 +44,13 @@ public final class Common { } @SuppressWarnings("rawtypes") - public static ArrayList parseTimedConditionEffects(List conditionsSourceJson) { - ArrayList conditions_source; + public static ArrayList parseTimedConditionEffects(List conditionsSourceJson) { + ArrayList conditions_source; if (conditionsSourceJson != null && !conditionsSourceJson.isEmpty()) { conditions_source = new ArrayList<>(); for (Object conditionJsonObj : conditionsSourceJson) { Map conditionJson = (Map) conditionJsonObj; - TimedConditionEffect condition = new TimedConditionEffect(); + TimedActorConditionEffect condition = new TimedActorConditionEffect(); readConditionEffect(condition, conditionJson); condition.duration = JSONElement.getInteger((Number) conditionJson.get("duration")); if (conditionJson.get("chance") != null) @@ -64,7 +64,7 @@ public final class Common { } @SuppressWarnings("rawtypes") - private static void readConditionEffect(ConditionEffect condition, Map conditionJson) { + private static void readConditionEffect(ActorConditionEffect condition, Map conditionJson) { condition.condition_id = (String) conditionJson.get("condition"); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); } @@ -119,19 +119,21 @@ public final class Common { hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); } - - public static class DeathEffect { - //Available from parsed state + public static class BasicEffect { public Integer hp_boost_min = null; public Integer hp_boost_max = null; public Integer ap_boost_min = null; public Integer ap_boost_max = null; - public List conditions_source = null; + } + + public static class DeathEffect extends BasicEffect { + //Available from parsed state + public List conditions_source = null; } public static class HitEffect extends DeathEffect { //Available from parsed state - public List conditions_target = null; + public List conditions_target = null; } public static class HitReceivedEffect extends Common.HitEffect { @@ -144,14 +146,11 @@ public final class Common { public static void copyDeathEffectValues(Common.DeathEffect target, Common.DeathEffect source, GameDataElement backlink) { - target.ap_boost_max = source.ap_boost_max; - target.ap_boost_min = source.ap_boost_min; - target.hp_boost_max = source.hp_boost_max; - target.hp_boost_min = source.hp_boost_min; + copyEffectValues(target, source); if (source.conditions_source != null) { target.conditions_source = new ArrayList<>(); - for (Common.TimedConditionEffect c : source.conditions_source) { - Common.TimedConditionEffect cclone = c.createClone(); + for (TimedActorConditionEffect c : source.conditions_source) { + TimedActorConditionEffect cclone = c.createClone(); if (cclone.condition != null) { cclone.condition.addBacklink(backlink); } @@ -160,12 +159,19 @@ public final class Common { } } + private static void copyEffectValues(BasicEffect target, BasicEffect source) { + target.ap_boost_max = source.ap_boost_max; + target.ap_boost_min = source.ap_boost_min; + target.hp_boost_max = source.hp_boost_max; + target.hp_boost_min = source.hp_boost_min; + } + public static void copyHitEffectValues(Common.HitEffect target, Common.HitEffect source, GameDataElement backlink) { copyDeathEffectValues(target, source, backlink); if (source.conditions_target != null) { target.conditions_target = new ArrayList<>(); - for (Common.TimedConditionEffect c : source.conditions_target) { - Common.TimedConditionEffect cclone = c.createClone(); + for (TimedActorConditionEffect c : source.conditions_target) { + TimedActorConditionEffect cclone = c.createClone(); if (cclone.condition != null) { cclone.condition.addBacklink(backlink); } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 1daaeda..d4c17f3 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -49,7 +49,7 @@ public class Item extends JSONElement { public Integer damage_boost_max = null; public Integer max_hp_boost = null; public Integer max_ap_boost = null; - public List conditions = null; + public List conditions = null; public Integer increase_move_cost = null; public Integer increase_use_item_cost = null; public Integer increase_reequip_cost = null; @@ -174,7 +174,7 @@ public class Item extends JSONElement { this.equip_effect.conditions = new ArrayList<>(); for (Object conditionJsonObj : conditionsJson) { Map conditionJson = (Map) conditionJsonObj; - ConditionEffect condition = new ConditionEffect(); + ActorConditionEffect condition = new ActorConditionEffect(); condition.condition_id = (String) conditionJson.get("condition"); condition.magnitude = JSONElement.getInteger((Number) conditionJson.get("magnitude")); this.equip_effect.conditions.add(condition); @@ -286,8 +286,8 @@ public class Item extends JSONElement { clone.equip_effect.max_hp_boost = this.equip_effect.max_hp_boost; if (this.equip_effect.conditions != null) { clone.equip_effect.conditions = new ArrayList<>(); - for (ConditionEffect c : this.equip_effect.conditions) { - ConditionEffect cclone = new ConditionEffect(); + for (ActorConditionEffect c : this.equip_effect.conditions) { + ActorConditionEffect cclone = new ActorConditionEffect(); cclone.magnitude = c.magnitude; cclone.condition_id = c.condition_id; cclone.condition = c.condition; @@ -321,7 +321,7 @@ public class Item extends JSONElement { if (newOne != null) newOne.addBacklink(this); } else { if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (ConditionEffect c : this.equip_effect.conditions) { + for (ActorConditionEffect c : this.equip_effect.conditions) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -330,7 +330,7 @@ public class Item extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect c : this.hit_effect.conditions_source) { + for (TimedActorConditionEffect c : this.hit_effect.conditions_source) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -339,7 +339,7 @@ public class Item extends JSONElement { } } if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect c : this.hit_effect.conditions_target) { + for (TimedActorConditionEffect c : this.hit_effect.conditions_target) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -349,7 +349,7 @@ public class Item extends JSONElement { } if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (TimedConditionEffect c : this.kill_effect.conditions_source) { + for (TimedActorConditionEffect c : this.kill_effect.conditions_source) { if (c.condition == oldOne) { oldOne.removeBacklink(this); c.condition = (ActorCondition) newOne; @@ -417,7 +417,7 @@ public class Item extends JSONElement { if (this.equip_effect.conditions != null) { List conditionsJson = new ArrayList(); equipEffectJson.put("addedConditions", conditionsJson); - for (ConditionEffect condition : this.equip_effect.conditions) { + for (ActorConditionEffect condition : this.equip_effect.conditions) { Map conditionJson = new LinkedHashMap(); conditionsJson.add(conditionJson); if (condition.condition != null) { @@ -451,7 +451,7 @@ public class Item extends JSONElement { if (this.hit_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_source) { + for (TimedActorConditionEffect condition : this.hit_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -468,7 +468,7 @@ public class Item extends JSONElement { if (this.hit_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_target) { + for (TimedActorConditionEffect condition : this.hit_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -529,7 +529,7 @@ public class Item extends JSONElement { if (this.hit_received_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { + for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { @@ -546,7 +546,7 @@ public class Item extends JSONElement { if (this.hit_received_effect.conditions_target != null) { List conditionsTargetJson = new ArrayList(); hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { + for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); if (condition.condition != null) { @@ -587,7 +587,7 @@ public class Item extends JSONElement { if (this.kill_effect.conditions_source != null) { List conditionsSourceJson = new ArrayList(); killEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.kill_effect.conditions_source) { + for (TimedActorConditionEffect condition : this.kill_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); if (condition.condition != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 505c2d9..db1b6dc 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -1,581 +1,581 @@ -package com.gpl.rpg.atcontentstudio.model.gamedata; - -import com.gpl.rpg.atcontentstudio.Notification; -import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.GameSource; -import com.gpl.rpg.atcontentstudio.model.Project; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; - -import java.awt.*; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; - -public class NPC extends JSONElement { - - private static final long serialVersionUID = 1093728879485491933L; - - //Available from init state - //public String id = null; inherited. - public String name = null; - public String icon_id = null; - - //Available from parsed state - public Integer max_hp = null; - public Integer max_ap = null; - public Integer move_cost = null; - public Integer unique = null; - public MonsterClass monster_class = null; - public MovementType movement_type = null; - public Integer attack_damage_max = null; - public Integer attack_damage_min = null; - public String spawngroup_id = null; - public String faction_id = null; - public String dialogue_id = null; - public String droplist_id = null; - public Integer attack_cost = null; - public Integer attack_chance = null; - public Integer critical_skill = null; - public Double critical_multiplier = null; - public Integer block_chance = null; - public Integer damage_resistance = null; - public HitEffect hit_effect = null; - public HitReceivedEffect hit_received_effect = null; - public DeathEffect death_effect = null; - - //Available from linked state - public Dialogue dialogue = null; - public Droplist droplist = null; - - public enum MonsterClass { - humanoid, - insect, - demon, - construct, - animal, - giant, - undead, - reptile, - ghost - } - - public enum MovementType { - none, - helpOthers, - protectSpawn, - wholeMap - } - - @Override - public String getDesc() { - return (needsSaving() ? "*" : "") + name + " (" + id + ")"; - } - - public static String getStaticDesc() { - return "NPCs"; - } - - - @SuppressWarnings("rawtypes") - public static void fromJson(File jsonFile, GameDataCategory category) { - JSONParser parser = new JSONParser(); - FileReader reader = null; - try { - reader = new FileReader(jsonFile); - List npcs = (List) parser.parse(reader); - for (Object obj : npcs) { - Map npcJson = (Map) obj; - NPC npc = fromJson(npcJson); - npc.jsonFile = jsonFile; - npc.parent = category; - if (npc.getDataType() == GameSource.Type.created || npc.getDataType() == GameSource.Type.altered) { - npc.writable = true; - } - category.add(npc); - } - } catch (FileNotFoundException e) { - Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); - e.printStackTrace(); - } catch (ParseException e) { - Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); - e.printStackTrace(); - } finally { - if (reader != null) - try { - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @SuppressWarnings("rawtypes") - public static NPC fromJson(String jsonString) throws ParseException { - Map npcJson = (Map) new JSONParser().parse(jsonString); - NPC npc = fromJson(npcJson); - npc.parse(npcJson); - return npc; - } - - @SuppressWarnings("rawtypes") - public static NPC fromJson(Map npcJson) { - NPC npc = new NPC(); - npc.icon_id = (String) npcJson.get("iconID"); - npc.id = (String) npcJson.get("id"); - npc.name = (String) npcJson.get("name"); - return npc; - } - - - @SuppressWarnings("rawtypes") - @Override - public void parse(Map npcJson) { - - this.max_hp = JSONElement.getInteger((Number) npcJson.get("maxHP")); - this.max_ap = JSONElement.getInteger((Number) npcJson.get("maxAP")); - this.move_cost = JSONElement.getInteger((Number) npcJson.get("moveCost")); - this.unique = JSONElement.getInteger((Number) npcJson.get("unique")); - if (npcJson.get("monsterClass") != null) - this.monster_class = MonsterClass.valueOf((String) npcJson.get("monsterClass")); - if (npcJson.get("movementAggressionType") != null) - this.movement_type = MovementType.valueOf((String) npcJson.get("movementAggressionType")); - if (npcJson.get("attackDamage") != null) { - this.attack_damage_min = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("min"))); - this.attack_damage_max = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("max"))); - } - this.spawngroup_id = (String) npcJson.get("spawnGroup"); - this.faction_id = (String) npcJson.get("faction"); - this.dialogue_id = (String) npcJson.get("phraseID"); - this.droplist_id = (String) npcJson.get("droplistID"); - this.attack_cost = JSONElement.getInteger((Number) npcJson.get("attackCost")); - this.attack_chance = JSONElement.getInteger((Number) npcJson.get("attackChance")); - this.critical_skill = JSONElement.getInteger((Number) npcJson.get("criticalSkill")); - //TODO correct game data, to unify format. -// this.critical_multiplier = JSONElement.getDouble((Number) npcJson.get("criticalMultiplier")); - if (npcJson.get("criticalMultiplier") != null) - this.critical_multiplier = JSONElement.getDouble(Double.parseDouble(npcJson.get("criticalMultiplier").toString())); - - this.block_chance = JSONElement.getInteger((Number) npcJson.get("blockChance")); - this.damage_resistance = JSONElement.getInteger((Number) npcJson.get("damageResistance")); - - Map hitEffect = (Map) npcJson.get("hitEffect"); - if (hitEffect != null) { - this.hit_effect = new HitEffect(); - if (hitEffect.get("increaseCurrentHP") != null) { - this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("max"))); - this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("min"))); - } - if (hitEffect.get("increaseCurrentAP") != null) { - this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("max"))); - this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("min"))); - } - List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); - this.hit_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); - List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); - this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); - } - - Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); - if (hitReceivedEffect != null) { - this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); - } - - Map deathEffect = (Map) npcJson.get("deathEffect"); - if (deathEffect != null) { - this.death_effect = new HitEffect(); - if (deathEffect.get("increaseCurrentHP") != null) { - this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("max"))); - this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("min"))); - } - if (deathEffect.get("increaseCurrentAP") != null) { - this.death_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("max"))); - this.death_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("min"))); - } - List conditionsSourceJson = (List) deathEffect.get("conditionsSource"); - this.death_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); - } - - } - - @Override - public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); - Project proj = getProject(); - if (proj == null) { - Notification.addError("Error linking item " + id + ". No parent project found."); - return; - } - if (this.icon_id != null) { - String spritesheetId = this.icon_id.split(":")[0]; - proj.getSpritesheet(spritesheetId).addBacklink(this); - } - - if (this.dialogue_id != null) this.dialogue = proj.getDialogue(this.dialogue_id); - if (this.dialogue != null) this.dialogue.addBacklink(this); - - if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id); - if (this.droplist != null) this.droplist.addBacklink(this); - - if (this.hit_effect != null) { - linkConditions(this.hit_effect.conditions_source, proj, this); - linkConditions(this.hit_effect.conditions_target, proj, this); - } - if (this.hit_received_effect != null) { - linkConditions(this.hit_received_effect.conditions_source, proj, this); - linkConditions(this.hit_received_effect.conditions_target, proj, this); - } - if (this.death_effect != null) { - linkConditions(this.death_effect.conditions_source, proj, this); - } - this.state = State.linked; - } - - @Override - public Image getIcon() { - return getProject().getIcon(icon_id); - } - - public Image getImage() { - return getProject().getImage(icon_id); - } - - @Override - public GameDataElement clone() { - NPC clone = new NPC(); - clone.jsonFile = this.jsonFile; - clone.state = this.state; - clone.id = this.id; - clone.name = this.name; - clone.icon_id = this.icon_id; - clone.attack_chance = this.attack_chance; - clone.attack_cost = this.attack_cost; - clone.attack_damage_min = this.attack_damage_min; - clone.attack_damage_max = this.attack_damage_max; - clone.block_chance = this.block_chance; - clone.critical_multiplier = this.critical_multiplier; - clone.critical_skill = this.critical_skill; - clone.damage_resistance = this.damage_resistance; - clone.dialogue = this.dialogue; - if (clone.dialogue != null) { - clone.dialogue.addBacklink(clone); - } - clone.dialogue_id = this.dialogue_id; - clone.droplist = this.droplist; - if (clone.droplist != null) { - clone.droplist.addBacklink(clone); - } - clone.droplist_id = this.droplist_id; - clone.faction_id = this.faction_id; - if (this.hit_effect != null) { - clone.hit_effect = new HitEffect(); - copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); - } - if (this.hit_received_effect != null) { - clone.hit_received_effect = new HitReceivedEffect(); - copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); - } - if (this.death_effect != null) { - clone.death_effect = new DeathEffect(); - copyDeathEffectValues(clone.death_effect, this.death_effect, clone); - } - clone.max_ap = this.max_ap; - clone.max_hp = this.max_hp; - clone.monster_class = this.monster_class; - clone.move_cost = this.move_cost; - clone.movement_type = this.movement_type; - clone.spawngroup_id = this.spawngroup_id; - clone.unique = this.unique; - return clone; - } - - @Override - public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { - if (dialogue == oldOne) { - oldOne.removeBacklink(this); - this.dialogue = (Dialogue) newOne; - if (newOne != null) newOne.addBacklink(this); - } else { - if (this.droplist == oldOne) { - oldOne.removeBacklink(this); - this.droplist = (Droplist) newOne; - if (newOne != null) newOne.addBacklink(this); - } else { - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedConditionEffect tce : this.hit_effect.conditions_source) { - if (tce.condition == oldOne) { - oldOne.removeBacklink(this); - tce.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedConditionEffect tce : this.hit_effect.conditions_target) { - if (tce.condition == oldOne) { - oldOne.removeBacklink(this); - tce.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - } - } - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public Map toJson() { - Map npcJson = new LinkedHashMap(); - npcJson.put("id", this.id); - if (this.name != null) npcJson.put("name", this.name); - if (this.icon_id != null) npcJson.put("iconID", this.icon_id); - if (this.max_hp != null) npcJson.put("maxHP", this.max_hp); - if (this.max_ap != null) npcJson.put("maxAP", this.max_ap); - if (this.move_cost != null) npcJson.put("moveCost", this.move_cost); - if (this.unique != null) npcJson.put("unique", this.unique); - if (this.monster_class != null) npcJson.put("monsterClass", this.monster_class.toString()); - if (this.movement_type != null) npcJson.put("movementAggressionType", this.movement_type.toString()); - if (this.attack_damage_min != null || this.attack_damage_max != null) { - Map adJson = new LinkedHashMap(); - npcJson.put("attackDamage", adJson); - if (this.attack_damage_min != null) adJson.put("min", this.attack_damage_min); - else adJson.put("min", 0); - if (this.attack_damage_max != null) adJson.put("max", this.attack_damage_max); - else adJson.put("max", 0); - } - if (this.spawngroup_id != null) npcJson.put("spawnGroup", this.spawngroup_id); - if (this.faction_id != null) npcJson.put("faction", this.faction_id); - if (this.dialogue != null) { - npcJson.put("phraseID", this.dialogue.id); - } else if (this.dialogue_id != null) { - npcJson.put("phraseID", this.dialogue_id); - } - if (this.droplist != null) { - npcJson.put("droplistID", this.droplist.id); - } else if (this.droplist_id != null) { - npcJson.put("droplistID", this.droplist_id); - } - if (this.attack_cost != null) npcJson.put("attackCost", this.attack_cost); - if (this.attack_chance != null) npcJson.put("attackChance", this.attack_chance); - if (this.critical_skill != null) npcJson.put("criticalSkill", this.critical_skill); - if (this.critical_multiplier != null) npcJson.put("criticalMultiplier", this.critical_multiplier); - if (this.block_chance != null) npcJson.put("blockChance", this.block_chance); - if (this.damage_resistance != null) npcJson.put("damageResistance", this.damage_resistance); - if (this.hit_effect != null) { - Map hitEffectJson = new LinkedHashMap(); - npcJson.put("hitEffect", hitEffectJson); - if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.hit_received_effect != null) { - Map hitReceivedEffectJson = new LinkedHashMap(); - npcJson.put("hitReceivedEffect", hitReceivedEffectJson); - if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min != null) - hpJson.put("min", this.hit_received_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max != null) - hpJson.put("max", this.hit_received_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min != null) - apJson.put("min", this.hit_received_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max != null) - apJson.put("max", this.hit_received_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min_target != null) - hpJson.put("min", this.hit_received_effect.hp_boost_min_target); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max_target != null) - hpJson.put("max", this.hit_received_effect.hp_boost_max_target); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min_target != null) - apJson.put("min", this.hit_received_effect.ap_boost_min_target); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max_target != null) - apJson.put("max", this.hit_received_effect.ap_boost_max_target); - else apJson.put("max", 0); - } - if (this.hit_received_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_received_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedConditionEffect condition : this.hit_received_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.death_effect != null) { - Map deathEffectJson = new LinkedHashMap(); - npcJson.put("deathEffect", deathEffectJson); - if (this.death_effect.hp_boost_min != null || this.death_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - deathEffectJson.put("increaseCurrentHP", hpJson); - if (this.death_effect.hp_boost_min != null) hpJson.put("min", this.death_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.death_effect.hp_boost_max != null) hpJson.put("max", this.death_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.death_effect.ap_boost_min != null || this.death_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - deathEffectJson.put("increaseCurrentAP", apJson); - if (this.death_effect.ap_boost_min != null) apJson.put("min", this.death_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.death_effect.ap_boost_max != null) apJson.put("max", this.death_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.death_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - deathEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedConditionEffect condition : this.death_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - return npcJson; - } - - - @Override - public String getProjectFilename() { - return "monsterlist_" + getProject().name + ".json"; - } - - public int getMonsterExperience() { - double EXP_FACTOR_DAMAGERESISTANCE = 9; - double EXP_FACTOR_SCALING = 0.7; - - double attacksPerTurn = Math.floor((double) (max_ap != null ? max_ap : 10.0) / (double) (attack_cost != null ? attack_cost : 10.0)); - double avgDamagePotential = 0; - if (attack_damage_min != null || attack_damage_max != null) { - avgDamagePotential = ((double) (attack_damage_min != null ? attack_damage_min : 0) + (double) (attack_damage_max != null ? attack_damage_max : 0)) / 2.0; - } - double avgCrit = 0; - if (critical_skill != null && critical_multiplier != null) { - avgCrit = (double) (critical_skill / 100.0) * critical_multiplier; - } - double avgAttackHP = attacksPerTurn * ((double) (attack_chance != null ? attack_chance : 0) / 100.0) * avgDamagePotential * (1 + avgCrit); - double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double) (block_chance != null ? block_chance : 0) / 100.0))) + (EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0)); - double attackConditionBonus = 0; - if (hit_effect != null && hit_effect.conditions_target != null && hit_effect.conditions_target.size() > 0) { - attackConditionBonus = 50; - } - double experience = (((avgAttackHP * 3) + avgDefenseHP) * EXP_FACTOR_SCALING) + attackConditionBonus; - - return new Double(Math.ceil(experience)).intValue(); - } - - -} +package com.gpl.rpg.atcontentstudio.model.gamedata; + +import com.gpl.rpg.atcontentstudio.Notification; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; +import com.gpl.rpg.atcontentstudio.model.GameSource; +import com.gpl.rpg.atcontentstudio.model.Project; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + +import java.awt.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; + +public class NPC extends JSONElement { + + private static final long serialVersionUID = 1093728879485491933L; + + //Available from init state + //public String id = null; inherited. + public String name = null; + public String icon_id = null; + + //Available from parsed state + public Integer max_hp = null; + public Integer max_ap = null; + public Integer move_cost = null; + public Integer unique = null; + public MonsterClass monster_class = null; + public MovementType movement_type = null; + public Integer attack_damage_max = null; + public Integer attack_damage_min = null; + public String spawngroup_id = null; + public String faction_id = null; + public String dialogue_id = null; + public String droplist_id = null; + public Integer attack_cost = null; + public Integer attack_chance = null; + public Integer critical_skill = null; + public Double critical_multiplier = null; + public Integer block_chance = null; + public Integer damage_resistance = null; + public HitEffect hit_effect = null; + public HitReceivedEffect hit_received_effect = null; + public DeathEffect death_effect = null; + + //Available from linked state + public Dialogue dialogue = null; + public Droplist droplist = null; + + public enum MonsterClass { + humanoid, + insect, + demon, + construct, + animal, + giant, + undead, + reptile, + ghost + } + + public enum MovementType { + none, + helpOthers, + protectSpawn, + wholeMap + } + + @Override + public String getDesc() { + return (needsSaving() ? "*" : "") + name + " (" + id + ")"; + } + + public static String getStaticDesc() { + return "NPCs"; + } + + + @SuppressWarnings("rawtypes") + public static void fromJson(File jsonFile, GameDataCategory category) { + JSONParser parser = new JSONParser(); + FileReader reader = null; + try { + reader = new FileReader(jsonFile); + List npcs = (List) parser.parse(reader); + for (Object obj : npcs) { + Map npcJson = (Map) obj; + NPC npc = fromJson(npcJson); + npc.jsonFile = jsonFile; + npc.parent = category; + if (npc.getDataType() == GameSource.Type.created || npc.getDataType() == GameSource.Type.altered) { + npc.writable = true; + } + category.add(npc); + } + } catch (FileNotFoundException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (IOException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } catch (ParseException e) { + Notification.addError("Error while parsing JSON file " + jsonFile.getAbsolutePath() + ": " + e.getMessage()); + e.printStackTrace(); + } finally { + if (reader != null) + try { + reader.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + @SuppressWarnings("rawtypes") + public static NPC fromJson(String jsonString) throws ParseException { + Map npcJson = (Map) new JSONParser().parse(jsonString); + NPC npc = fromJson(npcJson); + npc.parse(npcJson); + return npc; + } + + @SuppressWarnings("rawtypes") + public static NPC fromJson(Map npcJson) { + NPC npc = new NPC(); + npc.icon_id = (String) npcJson.get("iconID"); + npc.id = (String) npcJson.get("id"); + npc.name = (String) npcJson.get("name"); + return npc; + } + + + @SuppressWarnings("rawtypes") + @Override + public void parse(Map npcJson) { + + this.max_hp = JSONElement.getInteger((Number) npcJson.get("maxHP")); + this.max_ap = JSONElement.getInteger((Number) npcJson.get("maxAP")); + this.move_cost = JSONElement.getInteger((Number) npcJson.get("moveCost")); + this.unique = JSONElement.getInteger((Number) npcJson.get("unique")); + if (npcJson.get("monsterClass") != null) + this.monster_class = MonsterClass.valueOf((String) npcJson.get("monsterClass")); + if (npcJson.get("movementAggressionType") != null) + this.movement_type = MovementType.valueOf((String) npcJson.get("movementAggressionType")); + if (npcJson.get("attackDamage") != null) { + this.attack_damage_min = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("min"))); + this.attack_damage_max = JSONElement.getInteger((Number) (((Map) npcJson.get("attackDamage")).get("max"))); + } + this.spawngroup_id = (String) npcJson.get("spawnGroup"); + this.faction_id = (String) npcJson.get("faction"); + this.dialogue_id = (String) npcJson.get("phraseID"); + this.droplist_id = (String) npcJson.get("droplistID"); + this.attack_cost = JSONElement.getInteger((Number) npcJson.get("attackCost")); + this.attack_chance = JSONElement.getInteger((Number) npcJson.get("attackChance")); + this.critical_skill = JSONElement.getInteger((Number) npcJson.get("criticalSkill")); + //TODO correct game data, to unify format. +// this.critical_multiplier = JSONElement.getDouble((Number) npcJson.get("criticalMultiplier")); + if (npcJson.get("criticalMultiplier") != null) + this.critical_multiplier = JSONElement.getDouble(Double.parseDouble(npcJson.get("criticalMultiplier").toString())); + + this.block_chance = JSONElement.getInteger((Number) npcJson.get("blockChance")); + this.damage_resistance = JSONElement.getInteger((Number) npcJson.get("damageResistance")); + + Map hitEffect = (Map) npcJson.get("hitEffect"); + if (hitEffect != null) { + this.hit_effect = new HitEffect(); + if (hitEffect.get("increaseCurrentHP") != null) { + this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("max"))); + this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("min"))); + } + if (hitEffect.get("increaseCurrentAP") != null) { + this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("max"))); + this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("min"))); + } + List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); + this.hit_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); + List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); + this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); + } + + Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); + if (hitReceivedEffect != null) { + this.hit_received_effect = parseHitReceivedEffect(hitReceivedEffect); + } + + Map deathEffect = (Map) npcJson.get("deathEffect"); + if (deathEffect != null) { + this.death_effect = new HitEffect(); + if (deathEffect.get("increaseCurrentHP") != null) { + this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("max"))); + this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("min"))); + } + if (deathEffect.get("increaseCurrentAP") != null) { + this.death_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("max"))); + this.death_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("min"))); + } + List conditionsSourceJson = (List) deathEffect.get("conditionsSource"); + this.death_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); + } + + } + + @Override + public void link() { + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); + Project proj = getProject(); + if (proj == null) { + Notification.addError("Error linking item " + id + ". No parent project found."); + return; + } + if (this.icon_id != null) { + String spritesheetId = this.icon_id.split(":")[0]; + proj.getSpritesheet(spritesheetId).addBacklink(this); + } + + if (this.dialogue_id != null) this.dialogue = proj.getDialogue(this.dialogue_id); + if (this.dialogue != null) this.dialogue.addBacklink(this); + + if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id); + if (this.droplist != null) this.droplist.addBacklink(this); + + if (this.hit_effect != null) { + linkConditions(this.hit_effect.conditions_source, proj, this); + linkConditions(this.hit_effect.conditions_target, proj, this); + } + if (this.hit_received_effect != null) { + linkConditions(this.hit_received_effect.conditions_source, proj, this); + linkConditions(this.hit_received_effect.conditions_target, proj, this); + } + if (this.death_effect != null) { + linkConditions(this.death_effect.conditions_source, proj, this); + } + this.state = State.linked; + } + + @Override + public Image getIcon() { + return getProject().getIcon(icon_id); + } + + public Image getImage() { + return getProject().getImage(icon_id); + } + + @Override + public GameDataElement clone() { + NPC clone = new NPC(); + clone.jsonFile = this.jsonFile; + clone.state = this.state; + clone.id = this.id; + clone.name = this.name; + clone.icon_id = this.icon_id; + clone.attack_chance = this.attack_chance; + clone.attack_cost = this.attack_cost; + clone.attack_damage_min = this.attack_damage_min; + clone.attack_damage_max = this.attack_damage_max; + clone.block_chance = this.block_chance; + clone.critical_multiplier = this.critical_multiplier; + clone.critical_skill = this.critical_skill; + clone.damage_resistance = this.damage_resistance; + clone.dialogue = this.dialogue; + if (clone.dialogue != null) { + clone.dialogue.addBacklink(clone); + } + clone.dialogue_id = this.dialogue_id; + clone.droplist = this.droplist; + if (clone.droplist != null) { + clone.droplist.addBacklink(clone); + } + clone.droplist_id = this.droplist_id; + clone.faction_id = this.faction_id; + if (this.hit_effect != null) { + clone.hit_effect = new HitEffect(); + copyHitEffectValues(clone.hit_effect, this.hit_effect, clone); + } + if (this.hit_received_effect != null) { + clone.hit_received_effect = new HitReceivedEffect(); + copyHitReceivedEffectValues(clone.hit_received_effect, this.hit_received_effect, clone); + } + if (this.death_effect != null) { + clone.death_effect = new DeathEffect(); + copyDeathEffectValues(clone.death_effect, this.death_effect, clone); + } + clone.max_ap = this.max_ap; + clone.max_hp = this.max_hp; + clone.monster_class = this.monster_class; + clone.move_cost = this.move_cost; + clone.movement_type = this.movement_type; + clone.spawngroup_id = this.spawngroup_id; + clone.unique = this.unique; + return clone; + } + + @Override + public void elementChanged(GameDataElement oldOne, GameDataElement newOne) { + if (dialogue == oldOne) { + oldOne.removeBacklink(this); + this.dialogue = (Dialogue) newOne; + if (newOne != null) newOne.addBacklink(this); + } else { + if (this.droplist == oldOne) { + oldOne.removeBacklink(this); + this.droplist = (Droplist) newOne; + if (newOne != null) newOne.addBacklink(this); + } else { + if (this.hit_effect != null && this.hit_effect.conditions_source != null) { + for (TimedActorConditionEffect tce : this.hit_effect.conditions_source) { + if (tce.condition == oldOne) { + oldOne.removeBacklink(this); + tce.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + if (this.hit_effect != null && this.hit_effect.conditions_target != null) { + for (TimedActorConditionEffect tce : this.hit_effect.conditions_target) { + if (tce.condition == oldOne) { + oldOne.removeBacklink(this); + tce.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(this); + } + } + } + } + } + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public Map toJson() { + Map npcJson = new LinkedHashMap(); + npcJson.put("id", this.id); + if (this.name != null) npcJson.put("name", this.name); + if (this.icon_id != null) npcJson.put("iconID", this.icon_id); + if (this.max_hp != null) npcJson.put("maxHP", this.max_hp); + if (this.max_ap != null) npcJson.put("maxAP", this.max_ap); + if (this.move_cost != null) npcJson.put("moveCost", this.move_cost); + if (this.unique != null) npcJson.put("unique", this.unique); + if (this.monster_class != null) npcJson.put("monsterClass", this.monster_class.toString()); + if (this.movement_type != null) npcJson.put("movementAggressionType", this.movement_type.toString()); + if (this.attack_damage_min != null || this.attack_damage_max != null) { + Map adJson = new LinkedHashMap(); + npcJson.put("attackDamage", adJson); + if (this.attack_damage_min != null) adJson.put("min", this.attack_damage_min); + else adJson.put("min", 0); + if (this.attack_damage_max != null) adJson.put("max", this.attack_damage_max); + else adJson.put("max", 0); + } + if (this.spawngroup_id != null) npcJson.put("spawnGroup", this.spawngroup_id); + if (this.faction_id != null) npcJson.put("faction", this.faction_id); + if (this.dialogue != null) { + npcJson.put("phraseID", this.dialogue.id); + } else if (this.dialogue_id != null) { + npcJson.put("phraseID", this.dialogue_id); + } + if (this.droplist != null) { + npcJson.put("droplistID", this.droplist.id); + } else if (this.droplist_id != null) { + npcJson.put("droplistID", this.droplist_id); + } + if (this.attack_cost != null) npcJson.put("attackCost", this.attack_cost); + if (this.attack_chance != null) npcJson.put("attackChance", this.attack_chance); + if (this.critical_skill != null) npcJson.put("criticalSkill", this.critical_skill); + if (this.critical_multiplier != null) npcJson.put("criticalMultiplier", this.critical_multiplier); + if (this.block_chance != null) npcJson.put("blockChance", this.block_chance); + if (this.damage_resistance != null) npcJson.put("damageResistance", this.damage_resistance); + if (this.hit_effect != null) { + Map hitEffectJson = new LinkedHashMap(); + npcJson.put("hitEffect", hitEffectJson); + if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedActorConditionEffect condition : this.hit_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitEffectJson.put("conditionsTarget", conditionsTargetJson); + for (TimedActorConditionEffect condition : this.hit_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.hit_received_effect != null) { + Map hitReceivedEffectJson = new LinkedHashMap(); + npcJson.put("hitReceivedEffect", hitReceivedEffectJson); + if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min != null) + hpJson.put("min", this.hit_received_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max != null) + hpJson.put("max", this.hit_received_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min != null) + apJson.put("min", this.hit_received_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max != null) + apJson.put("max", this.hit_received_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { + Map hpJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); + if (this.hit_received_effect.hp_boost_min_target != null) + hpJson.put("min", this.hit_received_effect.hp_boost_min_target); + else hpJson.put("min", 0); + if (this.hit_received_effect.hp_boost_max_target != null) + hpJson.put("max", this.hit_received_effect.hp_boost_max_target); + else hpJson.put("max", 0); + } + if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { + Map apJson = new LinkedHashMap(); + hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); + if (this.hit_received_effect.ap_boost_min_target != null) + apJson.put("min", this.hit_received_effect.ap_boost_min_target); + else apJson.put("min", 0); + if (this.hit_received_effect.ap_boost_max_target != null) + apJson.put("max", this.hit_received_effect.ap_boost_max_target); + else apJson.put("max", 0); + } + if (this.hit_received_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + if (this.hit_received_effect.conditions_target != null) { + List conditionsTargetJson = new ArrayList(); + hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); + for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_target) { + Map conditionJson = new LinkedHashMap(); + conditionsTargetJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + if (this.death_effect != null) { + Map deathEffectJson = new LinkedHashMap(); + npcJson.put("deathEffect", deathEffectJson); + if (this.death_effect.hp_boost_min != null || this.death_effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + deathEffectJson.put("increaseCurrentHP", hpJson); + if (this.death_effect.hp_boost_min != null) hpJson.put("min", this.death_effect.hp_boost_min); + else hpJson.put("min", 0); + if (this.death_effect.hp_boost_max != null) hpJson.put("max", this.death_effect.hp_boost_max); + else hpJson.put("max", 0); + } + if (this.death_effect.ap_boost_min != null || this.death_effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + deathEffectJson.put("increaseCurrentAP", apJson); + if (this.death_effect.ap_boost_min != null) apJson.put("min", this.death_effect.ap_boost_min); + else apJson.put("min", 0); + if (this.death_effect.ap_boost_max != null) apJson.put("max", this.death_effect.ap_boost_max); + else apJson.put("max", 0); + } + if (this.death_effect.conditions_source != null) { + List conditionsSourceJson = new ArrayList(); + deathEffectJson.put("conditionsSource", conditionsSourceJson); + for (TimedActorConditionEffect condition : this.death_effect.conditions_source) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + if (condition.condition != null) { + conditionJson.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + conditionJson.put("condition", condition.condition_id); + } + if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + if (condition.duration != null) conditionJson.put("duration", condition.duration); + if (condition.chance != null) + conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + } + return npcJson; + } + + + @Override + public String getProjectFilename() { + return "monsterlist_" + getProject().name + ".json"; + } + + public int getMonsterExperience() { + double EXP_FACTOR_DAMAGERESISTANCE = 9; + double EXP_FACTOR_SCALING = 0.7; + + double attacksPerTurn = Math.floor((double) (max_ap != null ? max_ap : 10.0) / (double) (attack_cost != null ? attack_cost : 10.0)); + double avgDamagePotential = 0; + if (attack_damage_min != null || attack_damage_max != null) { + avgDamagePotential = ((double) (attack_damage_min != null ? attack_damage_min : 0) + (double) (attack_damage_max != null ? attack_damage_max : 0)) / 2.0; + } + double avgCrit = 0; + if (critical_skill != null && critical_multiplier != null) { + avgCrit = (double) (critical_skill / 100.0) * critical_multiplier; + } + double avgAttackHP = attacksPerTurn * ((double) (attack_chance != null ? attack_chance : 0) / 100.0) * avgDamagePotential * (1 + avgCrit); + double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double) (block_chance != null ? block_chance : 0) / 100.0))) + (EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0)); + double attackConditionBonus = 0; + if (hit_effect != null && hit_effect.conditions_target != null && hit_effect.conditions_target.size() > 0) { + attackConditionBonus = 50; + } + double experience = (((avgAttackHP * 3) + avgDefenseHP) * EXP_FACTOR_SCALING) + attackConditionBonus; + + return new Double(Math.ceil(experience)).intValue(); + } + + +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index 01fb226..b971732 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -19,7 +19,6 @@ import javax.swing.text.DefaultFormatter; import javax.swing.text.JTextComponent; import java.awt.*; import java.awt.event.*; -import java.io.Console; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; @@ -1106,10 +1105,10 @@ public abstract class Editor extends JPanel implements ProjectElementListener { } - protected > void updateConditionEffect(ActorCondition value, - GameDataElement backlink, - E selectedHitEffectTargetCondition, - T hitTargetConditionsModel) { + protected > void updateConditionEffect(ActorCondition value, + GameDataElement backlink, + E selectedHitEffectTargetCondition, + T hitTargetConditionsModel) { if (selectedHitEffectTargetCondition.condition != null) { selectedHitEffectTargetCondition.condition.removeBacklink(backlink); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 277af68..2c0f18f 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -14,8 +14,6 @@ import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -33,12 +31,12 @@ public class ItemEditor extends JSONElementEditor { private static final String useLabel = "Effect on use: "; - private Common.ConditionEffect selectedEquipEffectCondition; - private Common.TimedConditionEffect selectedHitEffectSourceCondition; - private Common.TimedConditionEffect selectedHitEffectTargetCondition; - private Common.TimedConditionEffect selectedKillEffectCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; + private Common.ActorConditionEffect selectedEquipEffectCondition; + private Common.TimedActorConditionEffect selectedHitEffectSourceCondition; + private Common.TimedActorConditionEffect selectedHitEffectTargetCondition; + private Common.TimedActorConditionEffect selectedKillEffectCondition; + private Common.TimedActorConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedActorConditionEffect selectedHitReceivedEffectTargetCondition; private JButton itemIcon; @@ -84,7 +82,7 @@ public class ItemEditor extends JSONElementEditor { private JSpinner hitAPMax; private SourceTimedConditionsListModel hitSourceConditionsModel; @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; + private JList hitSourceConditionsList; private MyComboBox hitSourceConditionBox; private JSpinner hitSourceConditionChance; private JRadioButton hitSourceConditionClear; @@ -214,8 +212,8 @@ public class ItemEditor extends JSONElementEditor { String titleEquipConditions = "Actor Conditions applied when equipped: "; equipConditionsModel = new ConditionsListModel(equipEffect); ConditionsCellRenderer cellRendererEquipConditions = new ConditionsCellRenderer(); - BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; - BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; + BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; + BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; BasicLambda selectedResetEquipConditions = ()->selectedEquipEffectCondition = null; BasicLambdaWithArg updatePaneEquipConditions = (editorPane) -> updateEquipConditionEditorPane(editorPane, selectedEquipEffectCondition, listener); var resultEquipConditions = UiUtils.getCollapsibleItemList(listener, @@ -226,7 +224,7 @@ public class ItemEditor extends JSONElementEditor { (x) -> {}, updatePaneEquipConditions, item.writable, - Common.ConditionEffect::new, + Common.ActorConditionEffect::new, cellRendererEquipConditions, titleEquipConditions, (x) -> null); @@ -255,11 +253,11 @@ public class ItemEditor extends JSONElementEditor { hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); - BasicLambdaWithReturn getSelected = () -> hitSourceConditionsList.getSelectedValue(); + BasicLambdaWithReturn getSelected = () -> hitSourceConditionsList.getSelectedValue(); BasicLambda resetSelected = () -> { selectedHitEffectSourceCondition = null; }; - BasicLambdaWithArg setSelected = (selectedItem) -> { + BasicLambdaWithArg setSelected = (selectedItem) -> { selectedHitEffectSourceCondition = selectedItem; }; BasicLambdaWithArg valueChanged = (selectedReply) -> { @@ -276,7 +274,7 @@ public class ItemEditor extends JSONElementEditor { valueChanged, updateEditorPane, item.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRenderer, title, (x) -> null @@ -290,8 +288,8 @@ public class ItemEditor extends JSONElementEditor { String titleHitTargetConditions = "Actor Conditions applied to the target: "; hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); ConditionsCellRenderer cellRendererHitTargetConditions = new ConditionsCellRenderer(); - BasicLambdaWithArg selectedSetHitTargetConditions = (value)->selectedHitEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetHitTargetConditions = ()->selectedHitEffectTargetCondition ; + BasicLambdaWithArg selectedSetHitTargetConditions = (value)->selectedHitEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetHitTargetConditions = ()->selectedHitEffectTargetCondition ; BasicLambda selectedResetHitTargetConditions = ()->selectedHitEffectTargetCondition = null; BasicLambdaWithArg updatePaneHitTargetConditions = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener); var resultHitTargetConditions = UiUtils.getCollapsibleItemList(listener, @@ -302,7 +300,7 @@ public class ItemEditor extends JSONElementEditor { (x) -> {}, updatePaneHitTargetConditions, item.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererHitTargetConditions, titleHitTargetConditions, (x) -> null); @@ -333,8 +331,8 @@ public class ItemEditor extends JSONElementEditor { String titleKillSourceConditions = "Actor Conditions applied to the source: "; killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); TimedConditionsCellRenderer cellRendererKillSourceConditions = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetKillSourceConditions = (value)->selectedKillEffectCondition = value; - BasicLambdaWithReturn selectedGetKillSourceConditions = ()->selectedKillEffectCondition ; + BasicLambdaWithArg selectedSetKillSourceConditions = (value)->selectedKillEffectCondition = value; + BasicLambdaWithReturn selectedGetKillSourceConditions = ()->selectedKillEffectCondition ; BasicLambda selectedResetKillSourceConditions = ()->selectedKillEffectCondition = null; BasicLambdaWithArg updatePaneKillSourceConditions = (editorPane) -> updateKillSourceTimedConditionEditorPane(editorPane, selectedKillEffectCondition, listener); var resultKillSourceConditions = UiUtils.getCollapsibleItemList(listener, @@ -345,7 +343,7 @@ public class ItemEditor extends JSONElementEditor { (x) -> {}, updatePaneKillSourceConditions, item.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererKillSourceConditions, titleKillSourceConditions, (x) -> null); @@ -373,16 +371,17 @@ public class ItemEditor extends JSONElementEditor { hitReceivedHPMax = addIntegerField(hitReceivedEffectPane, "Player HP bonus max: ", hitReceivedEffect.hp_boost_max, true, item.writable, listener); hitReceivedAPMin = addIntegerField(hitReceivedEffectPane, "Player AP bonus min: ", hitReceivedEffect.ap_boost_min, true, item.writable, listener); hitReceivedAPMax = addIntegerField(hitReceivedEffectPane, "Player AP bonus max: ", hitReceivedEffect.ap_boost_max, true, item.writable, listener); - hitReceivedHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, item.writable, listener); - hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, item.writable, listener); - hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, item.writable, listener); - hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, item.writable, listener); + String roleHitReceivedTarget = "Attacker"; + hitReceivedHPMinTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " HP bonus min: ", hitReceivedEffect.target.hp_boost_min, true, item.writable, listener); + hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " HP bonus max: ", hitReceivedEffect.target.hp_boost_max, true, item.writable, listener); + hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " AP bonus min: ", hitReceivedEffect.target.ap_boost_min, true, item.writable, listener); + hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " AP bonus max: ", hitReceivedEffect.target.ap_boost_max, true, item.writable, listener); String titleHitReceivedSourceConditions = "Actor Conditions applied to the player: "; hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); TimedConditionsCellRenderer cellRendererHitReceivedSourceConditions = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetHitReceivedSourceConditions = (value)->selectedHitReceivedEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition ; + BasicLambdaWithArg selectedSetHitReceivedSourceConditions = (value)->selectedHitReceivedEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition ; BasicLambda selectedResetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition = null; BasicLambdaWithArg updatePaneHitReceivedSourceConditions = (editorPane) -> updateHitReceivedSourceTimedConditionEditorPane(editorPane, selectedHitReceivedEffectSourceCondition, listener); var resultHitReceivedSourceConditions = UiUtils.getCollapsibleItemList(listener, @@ -393,7 +392,7 @@ public class ItemEditor extends JSONElementEditor { (x) -> {}, updatePaneHitReceivedSourceConditions, item.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererHitReceivedSourceConditions, titleHitReceivedSourceConditions, (x) -> null); @@ -407,8 +406,8 @@ public class ItemEditor extends JSONElementEditor { String titleHitReceivedTargetConditions = "Actor Conditions applied to the attacker: "; hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); TimedConditionsCellRenderer cellRendererHitReceivedTargetConditions = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetHitReceivedTargetConditions = (value)->selectedHitReceivedEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition ; + BasicLambdaWithArg selectedSetHitReceivedTargetConditions = (value)->selectedHitReceivedEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition ; BasicLambda selectedResetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition = null; BasicLambdaWithArg updatePaneHitReceivedTargetConditions = (editorPane) -> updateHitReceivedTargetTimedConditionEditorPane(editorPane, selectedHitReceivedEffectTargetCondition, listener); var resultHitReceivedTargetConditions = UiUtils.getCollapsibleItemList(listener, @@ -419,7 +418,7 @@ public class ItemEditor extends JSONElementEditor { (x) -> {}, updatePaneHitReceivedTargetConditions, item.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererHitReceivedTargetConditions, titleHitReceivedTargetConditions, (x) -> null); @@ -458,7 +457,7 @@ public class ItemEditor extends JSONElementEditor { } - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitSourceConditionBox != null) { removeElementListener(hitSourceConditionBox); @@ -536,7 +535,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -554,7 +553,7 @@ public class ItemEditor extends JSONElementEditor { hitSourceConditionForever.setEnabled(!clear); } - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitTargetConditionBox != null) { removeElementListener(hitTargetConditionBox); @@ -632,7 +631,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -650,7 +649,7 @@ public class ItemEditor extends JSONElementEditor { hitTargetConditionForever.setEnabled(!clear); } - public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (killSourceConditionBox != null) { removeElementListener(killSourceConditionBox); @@ -728,7 +727,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateKillSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateKillSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -746,7 +745,7 @@ public class ItemEditor extends JSONElementEditor { killSourceConditionForever.setEnabled(!clear); } - public void updateEquipConditionEditorPane(JPanel pane, Common.ConditionEffect condition, final FieldUpdateListener listener) { + public void updateEquipConditionEditorPane(JPanel pane, Common.ActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (equipConditionBox != null) { removeElementListener(equipConditionBox); @@ -794,7 +793,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedSourceConditionBox != null) { removeElementListener(hitReceivedSourceConditionBox); @@ -872,7 +871,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -890,7 +889,7 @@ public class ItemEditor extends JSONElementEditor { hitReceivedSourceConditionForever.setEnabled(!clear); } - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedTargetConditionBox != null) { removeElementListener(hitReceivedTargetConditionBox); @@ -968,7 +967,7 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -987,34 +986,34 @@ public class ItemEditor extends JSONElementEditor { } - public static class SourceTimedConditionsListModel extends OrderedListenerListModel { + public static class SourceTimedConditionsListModel extends OrderedListenerListModel { public SourceTimedConditionsListModel(Common.DeathEffect effect) { super(effect); } @Override - protected List getItems() { + protected List getItems() { return source.conditions_source; } @Override - protected void setItems(List items) { + protected void setItems(List items) { source.conditions_source = items; } } - public static class TargetTimedConditionsListModel extends OrderedListenerListModel { + public static class TargetTimedConditionsListModel extends OrderedListenerListModel { public TargetTimedConditionsListModel(Common.HitEffect effect) { super(effect); } @Override - protected List getItems() { + protected List getItems() { return source.conditions_target; } @Override - protected void setItems(List items) { + protected void setItems(List items) { source.conditions_target = items; } } @@ -1027,7 +1026,7 @@ public class ItemEditor extends JSONElementEditor { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JLabel) { JLabel label = ((JLabel) c); - Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; + Common.TimedActorConditionEffect effect = (Common.TimedActorConditionEffect) value; if (effect.condition != null) { @@ -1053,18 +1052,18 @@ public class ItemEditor extends JSONElementEditor { } } - public static class ConditionsListModel extends OrderedListenerListModel { + public static class ConditionsListModel extends OrderedListenerListModel { public ConditionsListModel(Item.EquipEffect equipEffect) { super(equipEffect); } @Override - protected List getItems() { + protected List getItems() { return source.conditions; } @Override - protected void setItems(List conditions) { + protected void setItems(List conditions) { source.conditions = conditions; } } @@ -1077,7 +1076,7 @@ public class ItemEditor extends JSONElementEditor { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JLabel) { JLabel label = ((JLabel) c); - Common.ConditionEffect effect = (Common.ConditionEffect) value; + Common.ActorConditionEffect effect = (Common.ActorConditionEffect) value; if (effect.condition != null) { if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { @@ -1703,6 +1702,7 @@ public class ItemEditor extends JSONElementEditor { } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 23274ce..6583a04 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -15,8 +15,6 @@ import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -31,11 +29,11 @@ public class NPCEditor extends JSONElementEditor { private static final String json_view_id = "JSON"; private static final String dialogue_tree_id = "Dialogue Tree"; - private Common.TimedConditionEffect selectedHitEffectSourceCondition; - private Common.TimedConditionEffect selectedHitEffectTargetCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedConditionEffect selectedHitReceivedEffectTargetCondition; - private Common.TimedConditionEffect selectedDeathEffectSourceCondition; + private Common.TimedActorConditionEffect selectedHitEffectSourceCondition; + private Common.TimedActorConditionEffect selectedHitEffectTargetCondition; + private Common.TimedActorConditionEffect selectedHitReceivedEffectSourceCondition; + private Common.TimedActorConditionEffect selectedHitReceivedEffectTargetCondition; + private Common.TimedActorConditionEffect selectedDeathEffectSourceCondition; private JButton npcIcon; private JTextField idField; @@ -254,8 +252,8 @@ public class NPCEditor extends JSONElementEditor { String titleSource = "Actor Conditions applied to the source: "; hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); TimedConditionsCellRenderer cellRendererSource = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetSource = (value)->selectedHitEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetSource = ()->selectedHitEffectSourceCondition ; + BasicLambdaWithArg selectedSetSource = (value)->selectedHitEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetSource = ()->selectedHitEffectSourceCondition ; BasicLambda selectedResetSource = ()->selectedHitEffectSourceCondition = null; BasicLambdaWithArg updatePaneSource = (editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener); @@ -267,7 +265,7 @@ public class NPCEditor extends JSONElementEditor { (x) -> {}, updatePaneSource, npc.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererSource, titleSource, (x) -> null); @@ -281,8 +279,8 @@ public class NPCEditor extends JSONElementEditor { String titleTarget = "Actor Conditions applied to the target: "; hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); TimedConditionsCellRenderer cellRendererTarget = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetTarget = (value)->selectedHitEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetTarget = ()->selectedHitEffectTargetCondition ; + BasicLambdaWithArg selectedSetTarget = (value)->selectedHitEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetTarget = ()->selectedHitEffectTargetCondition ; BasicLambda selectedResetTarget = ()->selectedHitEffectTargetCondition = null; BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener); var resultTarget = UiUtils.getCollapsibleItemList(listener, @@ -293,7 +291,7 @@ public class NPCEditor extends JSONElementEditor { (x) -> {}, updatePaneTarget, npc.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererTarget, titleTarget, (x) -> null); @@ -315,16 +313,16 @@ public class NPCEditor extends JSONElementEditor { hitReceivedEffectHPMax = addIntegerField(hitReceivedEffectPane, "NPC HP bonus max: ", hitReceivedEffect.hp_boost_max, true, npc.writable, listener); hitReceivedEffectAPMin = addIntegerField(hitReceivedEffectPane, "NPC AP bonus min: ", hitReceivedEffect.ap_boost_min, true, npc.writable, listener); hitReceivedEffectAPMax = addIntegerField(hitReceivedEffectPane, "NPC AP bonus max: ", hitReceivedEffect.ap_boost_max, true, npc.writable, listener); - hitReceivedEffectHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.hp_boost_min_target, true, npc.writable, listener); - hitReceivedEffectHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.hp_boost_max_target, true, npc.writable, listener); - hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.ap_boost_min_target, true, npc.writable, listener); - hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.ap_boost_max_target, true, npc.writable, listener); + hitReceivedEffectHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.target.hp_boost_min, true, npc.writable, listener); + hitReceivedEffectHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.target.hp_boost_max, true, npc.writable, listener); + hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.target.ap_boost_min, true, npc.writable, listener); + hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.target.ap_boost_max, true, npc.writable, listener); String titleReceivedSource = "Actor Conditions applied to this NPC: "; hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); TimedConditionsCellRenderer cellRendererReceivedSource = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetReceivedSource = (value)->selectedHitReceivedEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetReceivedSource = ()->selectedHitReceivedEffectSourceCondition ; + BasicLambdaWithArg selectedSetReceivedSource = (value)->selectedHitReceivedEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetReceivedSource = ()->selectedHitReceivedEffectSourceCondition ; BasicLambda selectedResetReceivedSource = ()->selectedHitReceivedEffectSourceCondition = null; BasicLambdaWithArg updatePaneReceivedSource = (editorPane) -> updateHitReceivedSourceTimedConditionEditorPane(editorPane, selectedHitReceivedEffectSourceCondition, listener); var resultReceivedSource = UiUtils.getCollapsibleItemList(listener, @@ -335,7 +333,7 @@ public class NPCEditor extends JSONElementEditor { (x) -> {}, updatePaneReceivedSource, npc.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererReceivedSource, titleReceivedSource, (x) -> null); @@ -349,8 +347,8 @@ public class NPCEditor extends JSONElementEditor { String titleReceivedTarget = "Actor Conditions applied to the attacker: "; hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); TimedConditionsCellRenderer cellRendererReceivedTarget = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetReceivedTarget = (value)->selectedHitReceivedEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition ; + BasicLambdaWithArg selectedSetReceivedTarget = (value)->selectedHitReceivedEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition ; BasicLambda selectedResetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition = null; BasicLambdaWithArg updatePaneReceivedTarget = (editorPane) -> updateHitReceivedTargetTimedConditionEditorPane(editorPane, selectedHitReceivedEffectTargetCondition, listener); var resultReceivedTarget = UiUtils.getCollapsibleItemList(listener, @@ -361,7 +359,7 @@ public class NPCEditor extends JSONElementEditor { (x) -> {}, updatePaneReceivedTarget, npc.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererReceivedTarget, titleReceivedTarget, (x) -> null); @@ -387,8 +385,8 @@ public class NPCEditor extends JSONElementEditor { String titleDeathSource = "Actor Conditions applied to the killer: "; deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); TimedConditionsCellRenderer cellRendererDeathSource = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetDeathSource = (value)->selectedDeathEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetDeathSource = ()->selectedDeathEffectSourceCondition ; + BasicLambdaWithArg selectedSetDeathSource = (value)->selectedDeathEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetDeathSource = ()->selectedDeathEffectSourceCondition ; BasicLambda selectedResetDeathSource = ()->selectedDeathEffectSourceCondition = null; BasicLambdaWithArg updatePaneDeathSource = (editorPane) -> updateDeathSourceTimedConditionEditorPane(editorPane, selectedDeathEffectSourceCondition, listener); var resultDeathSource = UiUtils.getCollapsibleItemList(listener, @@ -399,7 +397,7 @@ public class NPCEditor extends JSONElementEditor { (x) -> {}, updatePaneDeathSource, npc.writable, - Common.TimedConditionEffect::new, + Common.TimedActorConditionEffect::new, cellRendererDeathSource, titleDeathSource, (x) -> null); @@ -415,7 +413,7 @@ public class NPCEditor extends JSONElementEditor { pane.add(combatTraitPane, JideBoxLayout.FIX); } - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitSourceConditionBox != null) { removeElementListener(hitSourceConditionBox); @@ -487,7 +485,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -506,7 +504,7 @@ public class NPCEditor extends JSONElementEditor { } - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitTargetConditionBox != null) { removeElementListener(hitTargetConditionBox); @@ -577,7 +575,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -596,7 +594,7 @@ public class NPCEditor extends JSONElementEditor { } - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedSourceConditionBox != null) { removeElementListener(hitReceivedSourceConditionBox); @@ -668,7 +666,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -687,7 +685,7 @@ public class NPCEditor extends JSONElementEditor { } - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (hitReceivedTargetConditionBox != null) { removeElementListener(hitReceivedTargetConditionBox); @@ -758,7 +756,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -776,7 +774,7 @@ public class NPCEditor extends JSONElementEditor { hitReceivedTargetConditionForever.setEnabled(!clear); } - public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedConditionEffect condition, final FieldUpdateListener listener) { + public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (deathSourceConditionBox != null) { removeElementListener(deathSourceConditionBox); @@ -848,7 +846,7 @@ public class NPCEditor extends JSONElementEditor { pane.repaint(); } - public void updateDeathSourceTimedConditionWidgets(Common.TimedConditionEffect condition) { + public void updateDeathSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); @@ -866,34 +864,34 @@ public class NPCEditor extends JSONElementEditor { deathSourceConditionForever.setEnabled(!clear); } - public static class TargetTimedConditionsListModel extends OrderedListenerListModel { + public static class TargetTimedConditionsListModel extends OrderedListenerListModel { public TargetTimedConditionsListModel(Common.HitEffect effect) { super(effect); } @Override - protected List getItems() { + protected List getItems() { return source.conditions_target; } @Override - protected void setItems(List items) { + protected void setItems(List items) { source.conditions_target = items; } } - public static class SourceTimedConditionsListModel extends OrderedListenerListModel { + public static class SourceTimedConditionsListModel extends OrderedListenerListModel { public SourceTimedConditionsListModel(Common.DeathEffect effect) { super(effect); } @Override - protected List getItems() { + protected List getItems() { return source.conditions_source; } @Override - protected void setItems(List items) { + protected void setItems(List items) { source.conditions_source = items; } } @@ -906,7 +904,7 @@ public class NPCEditor extends JSONElementEditor { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (c instanceof JLabel) { JLabel label = ((JLabel) c); - Common.TimedConditionEffect effect = (Common.TimedConditionEffect) value; + Common.TimedActorConditionEffect effect = (Common.TimedActorConditionEffect) value; if (effect.condition != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java index e8d7e76..39c32ea 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/GDEVisitor.java @@ -96,18 +96,18 @@ public class GDEVisitor { if (element.icon_id != null) visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); if (element.equip_effect != null && element.equip_effect.conditions != null) { - for (Common.ConditionEffect condEffect : element.equip_effect.conditions) { + for (Common.ActorConditionEffect condEffect : element.equip_effect.conditions) { visit(condEffect.condition, visited, includeSource); } } if (element.hit_effect != null) { if (element.hit_effect.conditions_source != null) { - for (Common.ConditionEffect condEffect : element.hit_effect.conditions_source) { + for (Common.ActorConditionEffect condEffect : element.hit_effect.conditions_source) { visit(condEffect.condition, visited, includeSource); } } if (element.hit_effect.conditions_target != null) { - for (Common.ConditionEffect condEffect : element.hit_effect.conditions_target) { + for (Common.ActorConditionEffect condEffect : element.hit_effect.conditions_target) { visit(condEffect.condition, visited, includeSource); } } @@ -130,12 +130,12 @@ public class GDEVisitor { visit(element.getProject().getSpritesheet(element.icon_id.split(":")[0]), visited, includeSource); if (element.hit_effect != null) { if (element.hit_effect.conditions_source != null) { - for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_source) { + for (Common.TimedActorConditionEffect condEffect : element.hit_effect.conditions_source) { visit(condEffect.condition, visited, includeSource); } } if (element.hit_effect.conditions_target != null) { - for (Common.TimedConditionEffect condEffect : element.hit_effect.conditions_target) { + for (Common.TimedActorConditionEffect condEffect : element.hit_effect.conditions_target) { visit(condEffect.condition, visited, includeSource); } } From b2c05037e54f1b48a2f0038dd4c3a2c45d796ca7 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 14:31:50 +0200 Subject: [PATCH 45/94] use BasicEffect for HitReceivedEffect values to reuse logic --- .../model/gamedata/Common.java | 18 ++++++----------- .../atcontentstudio/model/gamedata/Item.java | 20 +++++++++---------- .../atcontentstudio/model/gamedata/NPC.java | 20 +++++++++---------- .../ui/gamedataeditors/ItemEditor.java | 16 +++++++-------- .../ui/gamedataeditors/NPCEditor.java | 16 +++++++-------- 5 files changed, 42 insertions(+), 48 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 50acb0a..0b1909a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -88,12 +88,12 @@ public final class Common { HitReceivedEffect hit_received_effect = new Common.HitReceivedEffect(); readHitEffect(hitReceivedEffect, hit_received_effect); if (hitReceivedEffect.get("increaseAttackerCurrentHP") != null) { - hit_received_effect.hp_boost_max_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max"))); - hit_received_effect.hp_boost_min_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min"))); + hit_received_effect.target.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("max"))); + hit_received_effect.target.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentHP")).get("min"))); } if (hitReceivedEffect.get("increaseAttackerCurrentAP") != null) { - hit_received_effect.ap_boost_max_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max"))); - hit_received_effect.ap_boost_min_target = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min"))); + hit_received_effect.target.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("max"))); + hit_received_effect.target.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitReceivedEffect.get("increaseAttackerCurrentAP")).get("min"))); } return hit_received_effect; } @@ -138,10 +138,7 @@ public final class Common { public static class HitReceivedEffect extends Common.HitEffect { //Available from parsed state - public Integer hp_boost_min_target = null; - public Integer hp_boost_max_target = null; - public Integer ap_boost_min_target = null; - public Integer ap_boost_max_target = null; + public BasicEffect target = new BasicEffect(); } @@ -182,10 +179,7 @@ public final class Common { public static void copyHitReceivedEffectValues(Common.HitReceivedEffect target, Common.HitReceivedEffect source, GameDataElement backlink) { copyHitEffectValues(target, source, backlink); - target.ap_boost_max_target = source.ap_boost_max_target; - target.ap_boost_min_target = source.ap_boost_min_target; - target.hp_boost_max_target = source.hp_boost_max_target; - target.hp_boost_min_target = source.hp_boost_min_target; + copyEffectValues(target.target, source.target); } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index d4c17f3..c5accbf 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -506,24 +506,24 @@ public class Item extends JSONElement { apJson.put("max", this.hit_received_effect.ap_boost_max); else apJson.put("max", 0); } - if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { + if (this.hit_received_effect.target.hp_boost_min != null || this.hit_received_effect.target.hp_boost_max != null) { Map hpJson = new LinkedHashMap(); hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min_target != null) - hpJson.put("min", this.hit_received_effect.hp_boost_min_target); + if (this.hit_received_effect.target.hp_boost_min != null) + hpJson.put("min", this.hit_received_effect.target.hp_boost_min); else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max_target != null) - hpJson.put("max", this.hit_received_effect.hp_boost_max_target); + if (this.hit_received_effect.target.hp_boost_max != null) + hpJson.put("max", this.hit_received_effect.target.hp_boost_max); else hpJson.put("max", 0); } - if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { + if (this.hit_received_effect.target.ap_boost_min != null || this.hit_received_effect.target.ap_boost_max != null) { Map apJson = new LinkedHashMap(); hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min_target != null) - apJson.put("min", this.hit_received_effect.ap_boost_min_target); + if (this.hit_received_effect.target.ap_boost_min != null) + apJson.put("min", this.hit_received_effect.target.ap_boost_min); else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max_target != null) - apJson.put("max", this.hit_received_effect.ap_boost_max_target); + if (this.hit_received_effect.target.ap_boost_max != null) + apJson.put("max", this.hit_received_effect.target.ap_boost_max); else apJson.put("max", 0); } if (this.hit_received_effect.conditions_source != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index db1b6dc..e128f82 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -452,24 +452,24 @@ public class NPC extends JSONElement { apJson.put("max", this.hit_received_effect.ap_boost_max); else apJson.put("max", 0); } - if (this.hit_received_effect.hp_boost_min_target != null || this.hit_received_effect.hp_boost_max_target != null) { + if (this.hit_received_effect.target.hp_boost_min != null || this.hit_received_effect.target.hp_boost_max != null) { Map hpJson = new LinkedHashMap(); hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min_target != null) - hpJson.put("min", this.hit_received_effect.hp_boost_min_target); + if (this.hit_received_effect.target.hp_boost_min != null) + hpJson.put("min", this.hit_received_effect.target.hp_boost_min); else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max_target != null) - hpJson.put("max", this.hit_received_effect.hp_boost_max_target); + if (this.hit_received_effect.target.hp_boost_max != null) + hpJson.put("max", this.hit_received_effect.target.hp_boost_max); else hpJson.put("max", 0); } - if (this.hit_received_effect.ap_boost_min_target != null || this.hit_received_effect.ap_boost_max_target != null) { + if (this.hit_received_effect.target.ap_boost_min != null || this.hit_received_effect.target.ap_boost_max != null) { Map apJson = new LinkedHashMap(); hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min_target != null) - apJson.put("min", this.hit_received_effect.ap_boost_min_target); + if (this.hit_received_effect.target.ap_boost_min != null) + apJson.put("min", this.hit_received_effect.target.ap_boost_min); else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max_target != null) - apJson.put("max", this.hit_received_effect.ap_boost_max_target); + if (this.hit_received_effect.target.ap_boost_max != null) + apJson.put("max", this.hit_received_effect.target.ap_boost_max); else apJson.put("max", 0); } if (this.hit_received_effect.conditions_source != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 2c0f18f..7845d7e 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -1139,10 +1139,10 @@ public class ItemEditor extends JSONElementEditor { if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; if (effect.hp_boost_max != null) return false; - if (effect.ap_boost_min_target != null) return false; - if (effect.ap_boost_max_target != null) return false; - if (effect.hp_boost_min_target != null) return false; - if (effect.hp_boost_max_target != null) return false; + if (effect.target.ap_boost_min != null) return false; + if (effect.target.ap_boost_max != null) return false; + if (effect.target.hp_boost_min != null) return false; + if (effect.target.hp_boost_max != null) return false; if (effect.conditions_source != null) return false; if (effect.conditions_target != null) return false; return true; @@ -1534,19 +1534,19 @@ public class ItemEditor extends JSONElementEditor { updatePrice = true; updateHitReceived = true; } else if (source == hitReceivedHPMinTarget) { - hitReceivedEffect.hp_boost_min_target = (Integer) value; + hitReceivedEffect.target.hp_boost_min = (Integer) value; updatePrice = true; updateHitReceived = true; } else if (source == hitReceivedHPMaxTarget) { - hitReceivedEffect.hp_boost_max_target = (Integer) value; + hitReceivedEffect.target.hp_boost_max = (Integer) value; updatePrice = true; updateHitReceived = true; } else if (source == hitReceivedAPMinTarget) { - hitReceivedEffect.ap_boost_min_target = (Integer) value; + hitReceivedEffect.target.ap_boost_min = (Integer) value; updatePrice = true; updateHitReceived = true; } else if (source == hitReceivedAPMaxTarget) { - hitReceivedEffect.ap_boost_max_target = (Integer) value; + hitReceivedEffect.target.ap_boost_max = (Integer) value; updatePrice = true; updateHitReceived = true; } else if (source == hitReceivedSourceConditionsList) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 6583a04..6e251b1 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -945,10 +945,10 @@ public class NPCEditor extends JSONElementEditor { if (effect.ap_boost_max != null) return false; if (effect.hp_boost_min != null) return false; if (effect.hp_boost_max != null) return false; - if (effect.ap_boost_min_target != null) return false; - if (effect.ap_boost_max_target != null) return false; - if (effect.hp_boost_min_target != null) return false; - if (effect.hp_boost_max_target != null) return false; + if (effect.target.ap_boost_min != null) return false; + if (effect.target.ap_boost_max != null) return false; + if (effect.target.hp_boost_min != null) return false; + if (effect.target.hp_boost_max != null) return false; if (effect.conditions_source != null) return false; if (effect.conditions_target != null) return false; return true; @@ -1194,16 +1194,16 @@ public class NPCEditor extends JSONElementEditor { hitReceivedEffect.ap_boost_max = (Integer) value; updateHitReceived = true; } else if (source == hitReceivedEffectHPMinTarget) { - hitReceivedEffect.hp_boost_min_target = (Integer) value; + hitReceivedEffect.target.hp_boost_min = (Integer) value; updateHitReceived = true; } else if (source == hitReceivedEffectHPMaxTarget) { - hitReceivedEffect.hp_boost_max_target = (Integer) value; + hitReceivedEffect.target.hp_boost_max = (Integer) value; updateHitReceived = true; } else if (source == hitReceivedEffectAPMinTarget) { - hitReceivedEffect.ap_boost_min_target = (Integer) value; + hitReceivedEffect.target.ap_boost_min = (Integer) value; updateHitReceived = true; } else if (source == hitReceivedEffectAPMaxTarget) { - hitReceivedEffect.ap_boost_max_target = (Integer) value; + hitReceivedEffect.target.ap_boost_max = (Integer) value; updateHitReceived = true; } else if (source == hitReceivedSourceConditionsList) { updateHitReceived = true; From a7f214a1cb3aa68a6d962b217fdd33c3ca4caf68 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 14:35:27 +0200 Subject: [PATCH 46/94] extract TimedConditionsCellRenderer into CommonEditor --- .../ui/gamedataeditors/CommonEditor.java | 46 +++++++++++++++++++ .../ui/gamedataeditors/ItemEditor.java | 42 ++--------------- .../ui/gamedataeditors/NPCEditor.java | 44 ++---------------- 3 files changed, 55 insertions(+), 77 deletions(-) create mode 100644 src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java new file mode 100644 index 0000000..e968f9d --- /dev/null +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -0,0 +1,46 @@ +package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; + +import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; +import com.gpl.rpg.atcontentstudio.model.gamedata.Common; +import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; +import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; + +import javax.swing.*; +import java.awt.*; + +public class CommonEditor { + + public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Common.TimedActorConditionEffect effect = (Common.TimedActorConditionEffect) value; + + if (effect.condition != null) { + + boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); + boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); + boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; + + if (clear) { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance + "% chances to clear actor condition " + effect.condition.getDesc()); + } else if (immunity) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText(effect.chance + "% chances to give immunity to " + effect.condition.getDesc() + (forever ? " forever" : " for " + effect.duration + " rounds")); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText(effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } +} diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 7845d7e..2e2cfd6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -263,7 +263,7 @@ public class ItemEditor extends JSONElementEditor { BasicLambdaWithArg valueChanged = (selectedReply) -> { }; BasicLambdaWithArg updateEditorPane = (editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener); - TimedConditionsCellRenderer cellRenderer = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRenderer = new CommonEditor.TimedConditionsCellRenderer(); String title = "Actor Conditions applied to the source: "; var collapsibleItemList = UiUtils.getCollapsibleItemList( listener, @@ -330,7 +330,7 @@ public class ItemEditor extends JSONElementEditor { String titleKillSourceConditions = "Actor Conditions applied to the source: "; killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); - TimedConditionsCellRenderer cellRendererKillSourceConditions = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererKillSourceConditions = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetKillSourceConditions = (value)->selectedKillEffectCondition = value; BasicLambdaWithReturn selectedGetKillSourceConditions = ()->selectedKillEffectCondition ; BasicLambda selectedResetKillSourceConditions = ()->selectedKillEffectCondition = null; @@ -379,7 +379,7 @@ public class ItemEditor extends JSONElementEditor { String titleHitReceivedSourceConditions = "Actor Conditions applied to the player: "; hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); - TimedConditionsCellRenderer cellRendererHitReceivedSourceConditions = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererHitReceivedSourceConditions = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetHitReceivedSourceConditions = (value)->selectedHitReceivedEffectSourceCondition = value; BasicLambdaWithReturn selectedGetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition ; BasicLambda selectedResetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition = null; @@ -405,7 +405,7 @@ public class ItemEditor extends JSONElementEditor { String titleHitReceivedTargetConditions = "Actor Conditions applied to the attacker: "; hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); - TimedConditionsCellRenderer cellRendererHitReceivedTargetConditions = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererHitReceivedTargetConditions = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetHitReceivedTargetConditions = (value)->selectedHitReceivedEffectTargetCondition = value; BasicLambdaWithReturn selectedGetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition ; BasicLambda selectedResetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition = null; @@ -1018,40 +1018,6 @@ public class ItemEditor extends JSONElementEditor { } } - public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel) c); - Common.TimedActorConditionEffect effect = (Common.TimedActorConditionEffect) value; - - if (effect.condition != null) { - - boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); - boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); - boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; - - if (clear) { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance + "% chances to clear actor condition " + effect.condition.getDesc()); - } else if (immunity) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText(effect.chance + "% chances to give immunity to " + effect.condition.getDesc() + (forever ? " forever" : " for " + effect.duration + " rounds")); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - public static class ConditionsListModel extends OrderedListenerListModel { public ConditionsListModel(Item.EquipEffect equipEffect) { super(equipEffect); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 6e251b1..32dada8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -251,7 +251,7 @@ public class NPCEditor extends JSONElementEditor { String titleSource = "Actor Conditions applied to the source: "; hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); - TimedConditionsCellRenderer cellRendererSource = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetSource = (value)->selectedHitEffectSourceCondition = value; BasicLambdaWithReturn selectedGetSource = ()->selectedHitEffectSourceCondition ; BasicLambda selectedResetSource = ()->selectedHitEffectSourceCondition = null; @@ -278,7 +278,7 @@ public class NPCEditor extends JSONElementEditor { String titleTarget = "Actor Conditions applied to the target: "; hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); - TimedConditionsCellRenderer cellRendererTarget = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetTarget = (value)->selectedHitEffectTargetCondition = value; BasicLambdaWithReturn selectedGetTarget = ()->selectedHitEffectTargetCondition ; BasicLambda selectedResetTarget = ()->selectedHitEffectTargetCondition = null; @@ -320,7 +320,7 @@ public class NPCEditor extends JSONElementEditor { String titleReceivedSource = "Actor Conditions applied to this NPC: "; hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); - TimedConditionsCellRenderer cellRendererReceivedSource = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererReceivedSource = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetReceivedSource = (value)->selectedHitReceivedEffectSourceCondition = value; BasicLambdaWithReturn selectedGetReceivedSource = ()->selectedHitReceivedEffectSourceCondition ; BasicLambda selectedResetReceivedSource = ()->selectedHitReceivedEffectSourceCondition = null; @@ -346,7 +346,7 @@ public class NPCEditor extends JSONElementEditor { String titleReceivedTarget = "Actor Conditions applied to the attacker: "; hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); - TimedConditionsCellRenderer cellRendererReceivedTarget = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererReceivedTarget = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetReceivedTarget = (value)->selectedHitReceivedEffectTargetCondition = value; BasicLambdaWithReturn selectedGetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition ; BasicLambda selectedResetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition = null; @@ -384,7 +384,7 @@ public class NPCEditor extends JSONElementEditor { String titleDeathSource = "Actor Conditions applied to the killer: "; deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); - TimedConditionsCellRenderer cellRendererDeathSource = new TimedConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererDeathSource = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetDeathSource = (value)->selectedDeathEffectSourceCondition = value; BasicLambdaWithReturn selectedGetDeathSource = ()->selectedDeathEffectSourceCondition ; BasicLambda selectedResetDeathSource = ()->selectedDeathEffectSourceCondition = null; @@ -896,40 +896,6 @@ public class NPCEditor extends JSONElementEditor { } } - public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel) c); - Common.TimedActorConditionEffect effect = (Common.TimedActorConditionEffect) value; - - if (effect.condition != null) { - - boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); - boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); - boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; - - if (clear) { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance + "% chances to clear actor condition " + effect.condition.getDesc()); - } else if (immunity) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText(effect.chance + "% chances to give immunity to " + effect.condition.getDesc() + (forever ? " forever" : " for " + effect.duration + " rounds")); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } - public static boolean isNull(Common.HitEffect effect) { if (effect.ap_boost_min != null) return false; if (effect.ap_boost_max != null) return false; From 1ca2b9068eb3eb4c1936eb61810f8b92f4f4928d Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 15:09:41 +0200 Subject: [PATCH 47/94] extract isImmunity & isClear & isInfinite --- .../gpl/rpg/atcontentstudio/model/gamedata/Common.java | 9 +++++++++ .../atcontentstudio/ui/gamedataeditors/CommonEditor.java | 6 +++--- .../atcontentstudio/ui/gamedataeditors/ItemEditor.java | 7 +++---- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 0b1909a..37d6fa2 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -32,6 +32,15 @@ public final class Common { cclone.duration = this.duration; return cclone; } + public boolean isInfinite(){ + return duration != null && duration == ActorCondition.DURATION_FOREVER; + } + public boolean isImmunity(){ + return (magnitude == null || magnitude == ActorCondition.MAGNITUDE_CLEAR) && (duration != null && duration > ActorCondition.DURATION_NONE); + } + public boolean isClear(){ + return (magnitude == null || magnitude == ActorCondition.MAGNITUDE_CLEAR) && (duration == null || duration == ActorCondition.DURATION_NONE); + } } public static class ActorConditionEffect { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index e968f9d..00bd0b2 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -22,9 +22,9 @@ public class CommonEditor { if (effect.condition != null) { - boolean immunity = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration != null && effect.duration > ActorCondition.DURATION_NONE); - boolean clear = (effect.magnitude == null || effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (effect.duration == null || effect.duration == ActorCondition.DURATION_NONE); - boolean forever = effect.duration != null && effect.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = effect.isImmunity(); + boolean clear = effect.isClear(); + boolean forever = effect.isInfinite(); if (clear) { label.setIcon(new ImageIcon(effect.condition.getIcon())); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 2e2cfd6..6f956c6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -632,10 +632,9 @@ public class ItemEditor extends JSONElementEditor { } public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitTargetConditionClear.setSelected(clear); hitTargetConditionApply.setSelected(!clear && !immunity); From 93f0a902baddf962a96bb3de2fdd9e5ccc70f124 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 15:09:52 +0200 Subject: [PATCH 48/94] extract linkEffects --- .../atcontentstudio/model/gamedata/Common.java | 13 +++++++++++++ .../rpg/atcontentstudio/model/gamedata/Item.java | 16 +++------------- .../rpg/atcontentstudio/model/gamedata/NPC.java | 14 +++----------- 3 files changed, 19 insertions(+), 24 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 37d6fa2..db511b1 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -17,6 +17,19 @@ public final class Common { } } } + public static void linkEffects(HitEffect effect, Project proj, GameDataElement backlink){ + linkEffects((DeathEffect) effect, proj, backlink); + if (effect != null) + { + linkConditions(effect.conditions_target, proj, backlink); + } + } + public static void linkEffects(DeathEffect effect, Project proj, GameDataElement backlink){ + if (effect != null) + { + linkConditions(effect.conditions_source, proj, backlink); + } + } public static class TimedActorConditionEffect extends ActorConditionEffect { //Available from parsed state diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index c5accbf..58ee109 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -226,19 +226,9 @@ public class Item extends JSONElement { linkConditions(this.equip_effect.conditions, proj, this); } - if (this.hit_effect != null) { - linkConditions(this.hit_effect.conditions_source, proj, this); - linkConditions(this.hit_effect.conditions_target, proj, this); - } - - if (this.hit_received_effect != null) { - linkConditions(this.hit_received_effect.conditions_source, proj, this); - linkConditions(this.hit_received_effect.conditions_target, proj, this); - } - - if (this.kill_effect != null) { - linkConditions(this.kill_effect.conditions_source, proj, this); - } + linkEffects(this.hit_effect, proj, this); + linkEffects(this.hit_received_effect, proj, this); + linkEffects(this.kill_effect, proj, this); this.state = State.linked; } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index e128f82..71e7fb5 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -230,17 +230,9 @@ public class NPC extends JSONElement { if (this.droplist_id != null) this.droplist = proj.getDroplist(this.droplist_id); if (this.droplist != null) this.droplist.addBacklink(this); - if (this.hit_effect != null) { - linkConditions(this.hit_effect.conditions_source, proj, this); - linkConditions(this.hit_effect.conditions_target, proj, this); - } - if (this.hit_received_effect != null) { - linkConditions(this.hit_received_effect.conditions_source, proj, this); - linkConditions(this.hit_received_effect.conditions_target, proj, this); - } - if (this.death_effect != null) { - linkConditions(this.death_effect.conditions_source, proj, this); - } + linkEffects(this.hit_effect, proj, this); + linkEffects(this.hit_received_effect, proj, this); + linkEffects(this.death_effect, proj, this); this.state = State.linked; } From 7018703ba6f078f0d43841af4da96fae0fc8b739 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 15:15:16 +0200 Subject: [PATCH 49/94] extract linkIcon --- src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java | 7 ++++++- src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java | 6 ++---- src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java | 6 +----- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index db511b1..42081a0 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -30,7 +30,12 @@ public final class Common { linkConditions(effect.conditions_source, proj, backlink); } } - + public static void linkIcon(Project proj, String iconId, GameDataElement backlink) { + if (iconId != null) { + String spritesheetId = iconId.split(":")[0]; + proj.getSpritesheet(spritesheetId).addBacklink(backlink); + } + } public static class TimedActorConditionEffect extends ActorConditionEffect { //Available from parsed state public Integer duration = null; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 58ee109..34525ab 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -216,10 +216,7 @@ public class Item extends JSONElement { return; } - if (this.icon_id != null) { - String spritesheetId = this.icon_id.split(":")[0]; - proj.getSpritesheet(spritesheetId).addBacklink(this); - } + linkIcon(proj, this.icon_id, this); if (this.category_id != null) this.category = proj.getItemCategory(this.category_id); if (this.category != null) this.category.addBacklink(this); if (this.equip_effect != null && this.equip_effect.conditions != null) { @@ -232,6 +229,7 @@ public class Item extends JSONElement { this.state = State.linked; } + @Override public Image getIcon() { return getProject().getIcon(icon_id); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 71e7fb5..f63598b 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -219,11 +219,7 @@ public class NPC extends JSONElement { Notification.addError("Error linking item " + id + ". No parent project found."); return; } - if (this.icon_id != null) { - String spritesheetId = this.icon_id.split(":")[0]; - proj.getSpritesheet(spritesheetId).addBacklink(this); - } - + linkIcon(proj, this.icon_id, this); if (this.dialogue_id != null) this.dialogue = proj.getDialogue(this.dialogue_id); if (this.dialogue != null) this.dialogue.addBacklink(this); From e91f77097526d58e70240b67b57a28752261df17 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 16:08:21 +0200 Subject: [PATCH 50/94] extract some toJson stuff to reduce duplication --- .../model/gamedata/Common.java | 102 +++++++++++ .../atcontentstudio/model/gamedata/Item.java | 159 +++--------------- 2 files changed, 121 insertions(+), 140 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 42081a0..1488bee 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -4,11 +4,13 @@ import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class Common { + //region link common stuff public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { if (conditions != null) { for (ActorConditionEffect ce : conditions) { @@ -36,6 +38,106 @@ public final class Common { proj.getSpritesheet(spritesheetId).addBacklink(backlink); } } + //endregion + + //region write common stuff + + public static void writeHitReceivedEffectToMap(Map parent, HitReceivedEffect effect) { + if(effect != null){ + writeHitEffectToMap(parent, effect); + writeBasicEffectObjectToMap(effect.target, parent, "increaseAttackerCurrentHP", "increaseAttackerCurrentAP"); + } + } + public static void writeHitReceivedEffectToMap(Map parent, HitReceivedEffect effect, String key) { + if (effect != null) { + Map effectJson = new LinkedHashMap(); + parent.put(key, effectJson); + writeHitReceivedEffectToMap(effectJson, effect); + } + } + public static void writeHitEffectToMap(Map parent, HitEffect effect) { + if(effect != null){ + writeDeathEffectToMap(parent, effect); + writeTimedActorConditionEffectObjectToMap(effect.conditions_target, parent, "conditionsTarget"); + } + } + public static void writeHitEffectToMap(Map parent, HitEffect effect, String key) { + if (effect != null) { + Map effectJson = new LinkedHashMap(); + parent.put(key, effectJson); + writeHitEffectToMap(effectJson, effect); + } + } + public static void writeDeathEffectToMap(Map parent, DeathEffect effect) { + writeBasicEffectObjectToMap(effect, parent, "increaseCurrentHP", "increaseCurrentAP"); + writeTimedActorConditionEffectObjectToMap(effect.conditions_source, parent, "conditionsSource"); + } + public static void writeDeathEffectToMap(Map parent, DeathEffect effect, String key) { + if (effect != null) { + Map effectJson = new LinkedHashMap(); + parent.put(key, effectJson); + writeDeathEffectToMap(effectJson, effect); + } + } + + public static void writeBasicEffectObjectToMap(BasicEffect effect, Map parent, String keyHP, String keyAP) { + if (effect.hp_boost_min != null || effect.hp_boost_max != null) { + Map hpJson = new LinkedHashMap(); + parent.put(keyHP, hpJson); + if (effect.hp_boost_min != null) + hpJson.put("min", effect.hp_boost_min); + else hpJson.put("min", 0); + if (effect.hp_boost_max != null) + hpJson.put("max", effect.hp_boost_max); + else hpJson.put("max", 0); + } + + if (effect.ap_boost_min != null || effect.ap_boost_max != null) { + Map apJson = new LinkedHashMap(); + parent.put(keyAP, apJson); + if (effect.ap_boost_min != null) + apJson.put("min", effect.ap_boost_min); + else apJson.put("min", 0); + if (effect.ap_boost_max != null) + apJson.put("max", effect.ap_boost_max); + else apJson.put("max", 0); + } + } + + public static void writeTimedActorConditionEffectObjectToMap(List list, Map parent, String key) { + if (list != null) { + List conditionsSourceJson = new ArrayList(); + parent.put(key, conditionsSourceJson); + for (TimedActorConditionEffect condition : list) { + Map conditionJson = new LinkedHashMap(); + conditionsSourceJson.add(conditionJson); + writeTimedConditionEffectToMap(condition, conditionJson); + } + } + + } + + public static void writeConditionEffectToMap(ActorConditionEffect condition, Map parent) { + if (condition.condition != null) { + parent.put("condition", condition.condition.id); + } else if (condition.condition_id != null) { + parent.put("condition", condition.condition_id); + } + if (condition.magnitude != null) { + parent.put("magnitude", condition.magnitude); + } + } + + public static void writeTimedConditionEffectToMap(TimedActorConditionEffect condition, Map parent) { + writeConditionEffectToMap(condition, parent); + if (condition.duration != null) { + parent.put("duration", condition.duration); + } + if (condition.chance != null) { + parent.put("chance", JSONElement.printJsonChance(condition.chance)); + } + } + //endregion public static class TimedActorConditionEffect extends ActorConditionEffect { //Available from parsed state public Integer duration = null; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 34525ab..22d3f1d 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -408,12 +408,7 @@ public class Item extends JSONElement { for (ActorConditionEffect condition : this.equip_effect.conditions) { Map conditionJson = new LinkedHashMap(); conditionsJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); + writeConditionEffectToMap(condition, conditionJson); } } } @@ -442,15 +437,7 @@ public class Item extends JSONElement { for (TimedActorConditionEffect condition : this.hit_effect.conditions_source) { Map conditionJson = new LinkedHashMap(); conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + writeTimedConditionEffectToMap(condition, conditionJson); } } if (this.hit_effect.conditions_target != null) { @@ -459,140 +446,32 @@ public class Item extends JSONElement { for (TimedActorConditionEffect condition : this.hit_effect.conditions_target) { Map conditionJson = new LinkedHashMap(); conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); + writeTimedConditionEffectToMap(condition, conditionJson); } } } - if (this.hit_received_effect != null) { - Map hitReceivedEffectJson = new LinkedHashMap(); - itemJson.put("hitReceivedEffect", hitReceivedEffectJson); - if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min != null) - hpJson.put("min", this.hit_received_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max != null) - hpJson.put("max", this.hit_received_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min != null) - apJson.put("min", this.hit_received_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max != null) - apJson.put("max", this.hit_received_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.target.hp_boost_min != null || this.hit_received_effect.target.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.target.hp_boost_min != null) - hpJson.put("min", this.hit_received_effect.target.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.target.hp_boost_max != null) - hpJson.put("max", this.hit_received_effect.target.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.target.ap_boost_min != null || this.hit_received_effect.target.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.target.ap_boost_min != null) - apJson.put("min", this.hit_received_effect.target.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.target.ap_boost_max != null) - apJson.put("max", this.hit_received_effect.target.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_received_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } + writeHitReceivedEffectToMap(itemJson, this.hit_received_effect, "hitReceivedEffect"); + String key; + if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { + key = "killEffect"; + } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { + key = "useEffect"; + } else { + try { + throw new IllegalArgumentException("Could not create JSON-Map for Item: Failed to determine if the items should be used or equipped."); + } catch (RuntimeException e) { + e.printStackTrace(); } + key = null; } - if (this.kill_effect != null) { - Map killEffectJson = new LinkedHashMap(); - if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { - itemJson.put("killEffect", killEffectJson); - } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { - itemJson.put("useEffect", killEffectJson); - } - if (this.kill_effect.hp_boost_min != null || this.kill_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - killEffectJson.put("increaseCurrentHP", hpJson); - if (this.kill_effect.hp_boost_min != null) hpJson.put("min", this.kill_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.kill_effect.hp_boost_max != null) hpJson.put("max", this.kill_effect.hp_boost_max); - else hpJson.put("min", 0); - } - if (this.kill_effect.ap_boost_min != null || this.kill_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - killEffectJson.put("increaseCurrentAP", apJson); - if (this.kill_effect.ap_boost_min != null) apJson.put("min", this.kill_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.kill_effect.ap_boost_max != null) apJson.put("max", this.kill_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.kill_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - killEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedActorConditionEffect condition : this.kill_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } + if (key != null) { + writeDeathEffectToMap(itemJson, this.kill_effect, key); } + return itemJson; } + @Override public String getProjectFilename() { return "itemlist_" + getProject().name + ".json"; From f04f062723c37f16c1340b0e8b952bfb47d3c696 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 16:24:47 +0200 Subject: [PATCH 51/94] extract some more toJson stuff to reduce duplication --- .../model/gamedata/Common.java | 45 +++-- .../atcontentstudio/model/gamedata/Item.java | 55 +----- .../atcontentstudio/model/gamedata/NPC.java | 183 +----------------- 3 files changed, 35 insertions(+), 248 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 1488bee..b8ee41e 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -41,7 +41,30 @@ public final class Common { //endregion //region write common stuff + public static void writeMinMaxToMap(Map parent, Integer min, Integer max, int defaultValue) { + if (min != null || max != null) { + if (min != null) + parent.put("min", min); + else parent.put("min", defaultValue); + if (max != null) + parent.put("max", max); + else parent.put("max", defaultValue); + } + } + public static void writeMinMaxToMap(Map parent, String key, Integer min, Integer max, int defaultValue) { + if (min != null || max != null) { + Map minMaxMap = new LinkedHashMap(); + parent.put(key, minMaxMap); + writeMinMaxToMap(parent, min, max, defaultValue); + } + } + public static void writeDescriptionToMap(Map parent, String description) { + if (description != null) parent.put("description", description); + } + public static void writeIconToMap(Map parent, String icon_id) { + if (icon_id != null) parent.put("iconID", icon_id); + } public static void writeHitReceivedEffectToMap(Map parent, HitReceivedEffect effect) { if(effect != null){ writeHitEffectToMap(parent, effect); @@ -81,27 +104,9 @@ public final class Common { } public static void writeBasicEffectObjectToMap(BasicEffect effect, Map parent, String keyHP, String keyAP) { - if (effect.hp_boost_min != null || effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - parent.put(keyHP, hpJson); - if (effect.hp_boost_min != null) - hpJson.put("min", effect.hp_boost_min); - else hpJson.put("min", 0); - if (effect.hp_boost_max != null) - hpJson.put("max", effect.hp_boost_max); - else hpJson.put("max", 0); - } + writeMinMaxToMap(parent, keyHP, effect.hp_boost_min, effect.hp_boost_max, 0); - if (effect.ap_boost_min != null || effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - parent.put(keyAP, apJson); - if (effect.ap_boost_min != null) - apJson.put("min", effect.ap_boost_min); - else apJson.put("min", 0); - if (effect.ap_boost_max != null) - apJson.put("max", effect.ap_boost_max); - else apJson.put("max", 0); - } + writeMinMaxToMap(parent, keyAP, effect.ap_boost_min, effect.ap_boost_max, 0); } public static void writeTimedActorConditionEffectObjectToMap(List list, Map parent, String key) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 22d3f1d..5f44f59 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -353,7 +353,7 @@ public class Item extends JSONElement { public Map toJson() { Map itemJson = new LinkedHashMap(); itemJson.put("id", this.id); - if (this.icon_id != null) itemJson.put("iconID", this.icon_id); + writeIconToMap(itemJson, this.icon_id); if (this.name != null) itemJson.put("name", this.name); if (this.display_type != null) itemJson.put("displaytype", this.display_type.toString()); @@ -364,20 +364,11 @@ public class Item extends JSONElement { } else if (this.category_id != null) { itemJson.put("category", this.category_id); } - if (this.description != null) itemJson.put("description", this.description); + writeDescriptionToMap(itemJson, this.description); if (this.equip_effect != null) { Map equipEffectJson = new LinkedHashMap(); itemJson.put("equipEffect", equipEffectJson); - if (this.equip_effect.damage_boost_min != null || this.equip_effect.damage_boost_max != null) { - Map damageJson = new LinkedHashMap(); - equipEffectJson.put("increaseAttackDamage", damageJson); - if (this.equip_effect.damage_boost_min != null) - damageJson.put("min", this.equip_effect.damage_boost_min); - else damageJson.put("min", 0); - if (this.equip_effect.damage_boost_max != null) - damageJson.put("max", this.equip_effect.damage_boost_max); - else damageJson.put("max", 0); - } + writeMinMaxToMap(equipEffectJson, "increaseAttackDamage", this.equip_effect.damage_boost_min, this.equip_effect.damage_boost_max, 0); if (this.equip_effect.max_hp_boost != null) equipEffectJson.put("increaseMaxHP", this.equip_effect.max_hp_boost); if (this.equip_effect.max_ap_boost != null) @@ -412,45 +403,9 @@ public class Item extends JSONElement { } } } - if (this.hit_effect != null) { - Map hitEffectJson = new LinkedHashMap(); - itemJson.put("hitEffect", hitEffectJson); - if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedActorConditionEffect condition : this.hit_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - writeTimedConditionEffectToMap(condition, conditionJson); - } - } - if (this.hit_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedActorConditionEffect condition : this.hit_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - writeTimedConditionEffectToMap(condition, conditionJson); - } - } - } + writeHitEffectToMap(itemJson, this.hit_effect, "hitEffect"); writeHitReceivedEffectToMap(itemJson, this.hit_received_effect, "hitReceivedEffect"); + String key; if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { key = "killEffect"; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index f63598b..4d9e424 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -330,21 +330,14 @@ public class NPC extends JSONElement { Map npcJson = new LinkedHashMap(); npcJson.put("id", this.id); if (this.name != null) npcJson.put("name", this.name); - if (this.icon_id != null) npcJson.put("iconID", this.icon_id); + writeIconToMap(npcJson, this.icon_id); if (this.max_hp != null) npcJson.put("maxHP", this.max_hp); if (this.max_ap != null) npcJson.put("maxAP", this.max_ap); if (this.move_cost != null) npcJson.put("moveCost", this.move_cost); if (this.unique != null) npcJson.put("unique", this.unique); if (this.monster_class != null) npcJson.put("monsterClass", this.monster_class.toString()); if (this.movement_type != null) npcJson.put("movementAggressionType", this.movement_type.toString()); - if (this.attack_damage_min != null || this.attack_damage_max != null) { - Map adJson = new LinkedHashMap(); - npcJson.put("attackDamage", adJson); - if (this.attack_damage_min != null) adJson.put("min", this.attack_damage_min); - else adJson.put("min", 0); - if (this.attack_damage_max != null) adJson.put("max", this.attack_damage_max); - else adJson.put("max", 0); - } + writeMinMaxToMap(npcJson, "attackDamage", this.attack_damage_min, attack_damage_max, 0); if (this.spawngroup_id != null) npcJson.put("spawnGroup", this.spawngroup_id); if (this.faction_id != null) npcJson.put("faction", this.faction_id); if (this.dialogue != null) { @@ -363,175 +356,9 @@ public class NPC extends JSONElement { if (this.critical_multiplier != null) npcJson.put("criticalMultiplier", this.critical_multiplier); if (this.block_chance != null) npcJson.put("blockChance", this.block_chance); if (this.damage_resistance != null) npcJson.put("damageResistance", this.damage_resistance); - if (this.hit_effect != null) { - Map hitEffectJson = new LinkedHashMap(); - npcJson.put("hitEffect", hitEffectJson); - if (this.hit_effect.hp_boost_min != null || this.hit_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_effect.hp_boost_min != null) hpJson.put("min", this.hit_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_effect.hp_boost_max != null) hpJson.put("max", this.hit_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_effect.ap_boost_min != null || this.hit_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_effect.ap_boost_min != null) apJson.put("min", this.hit_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_effect.ap_boost_max != null) apJson.put("max", this.hit_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedActorConditionEffect condition : this.hit_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedActorConditionEffect condition : this.hit_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.hit_received_effect != null) { - Map hitReceivedEffectJson = new LinkedHashMap(); - npcJson.put("hitReceivedEffect", hitReceivedEffectJson); - if (this.hit_received_effect.hp_boost_min != null || this.hit_received_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentHP", hpJson); - if (this.hit_received_effect.hp_boost_min != null) - hpJson.put("min", this.hit_received_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.hp_boost_max != null) - hpJson.put("max", this.hit_received_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.ap_boost_min != null || this.hit_received_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseCurrentAP", apJson); - if (this.hit_received_effect.ap_boost_min != null) - apJson.put("min", this.hit_received_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.ap_boost_max != null) - apJson.put("max", this.hit_received_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.target.hp_boost_min != null || this.hit_received_effect.target.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentHP", hpJson); - if (this.hit_received_effect.target.hp_boost_min != null) - hpJson.put("min", this.hit_received_effect.target.hp_boost_min); - else hpJson.put("min", 0); - if (this.hit_received_effect.target.hp_boost_max != null) - hpJson.put("max", this.hit_received_effect.target.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.hit_received_effect.target.ap_boost_min != null || this.hit_received_effect.target.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - hitReceivedEffectJson.put("increaseAttackerCurrentAP", apJson); - if (this.hit_received_effect.target.ap_boost_min != null) - apJson.put("min", this.hit_received_effect.target.ap_boost_min); - else apJson.put("min", 0); - if (this.hit_received_effect.target.ap_boost_max != null) - apJson.put("max", this.hit_received_effect.target.ap_boost_max); - else apJson.put("max", 0); - } - if (this.hit_received_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - if (this.hit_received_effect.conditions_target != null) { - List conditionsTargetJson = new ArrayList(); - hitReceivedEffectJson.put("conditionsTarget", conditionsTargetJson); - for (TimedActorConditionEffect condition : this.hit_received_effect.conditions_target) { - Map conditionJson = new LinkedHashMap(); - conditionsTargetJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } - if (this.death_effect != null) { - Map deathEffectJson = new LinkedHashMap(); - npcJson.put("deathEffect", deathEffectJson); - if (this.death_effect.hp_boost_min != null || this.death_effect.hp_boost_max != null) { - Map hpJson = new LinkedHashMap(); - deathEffectJson.put("increaseCurrentHP", hpJson); - if (this.death_effect.hp_boost_min != null) hpJson.put("min", this.death_effect.hp_boost_min); - else hpJson.put("min", 0); - if (this.death_effect.hp_boost_max != null) hpJson.put("max", this.death_effect.hp_boost_max); - else hpJson.put("max", 0); - } - if (this.death_effect.ap_boost_min != null || this.death_effect.ap_boost_max != null) { - Map apJson = new LinkedHashMap(); - deathEffectJson.put("increaseCurrentAP", apJson); - if (this.death_effect.ap_boost_min != null) apJson.put("min", this.death_effect.ap_boost_min); - else apJson.put("min", 0); - if (this.death_effect.ap_boost_max != null) apJson.put("max", this.death_effect.ap_boost_max); - else apJson.put("max", 0); - } - if (this.death_effect.conditions_source != null) { - List conditionsSourceJson = new ArrayList(); - deathEffectJson.put("conditionsSource", conditionsSourceJson); - for (TimedActorConditionEffect condition : this.death_effect.conditions_source) { - Map conditionJson = new LinkedHashMap(); - conditionsSourceJson.add(conditionJson); - if (condition.condition != null) { - conditionJson.put("condition", condition.condition.id); - } else if (condition.condition_id != null) { - conditionJson.put("condition", condition.condition_id); - } - if (condition.magnitude != null) conditionJson.put("magnitude", condition.magnitude); - if (condition.duration != null) conditionJson.put("duration", condition.duration); - if (condition.chance != null) - conditionJson.put("chance", JSONElement.printJsonChance(condition.chance)); - } - } - } + writeHitEffectToMap(npcJson, this.hit_effect, "hitEffect"); + writeHitReceivedEffectToMap(npcJson, this.hit_received_effect, "hitReceivedEffect"); + writeDeathEffectToMap(npcJson, this.death_effect, "deathEffect"); return npcJson; } From 488dd92893a5d786949ca6f0ba88cbe74f00f5ad Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 17:25:39 +0200 Subject: [PATCH 52/94] extract actorConditionElementChanged + some parse stuff --- .../model/gamedata/Common.java | 12 +++++ .../atcontentstudio/model/gamedata/Item.java | 40 ++++------------ .../atcontentstudio/model/gamedata/NPC.java | 47 ++----------------- 3 files changed, 25 insertions(+), 74 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index b8ee41e..c85d383 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -10,6 +10,18 @@ import java.util.Map; public final class Common { + public static void actorConditionElementChanged(List list, GameDataElement oldOne, GameDataElement newOne,GameDataElement backlink){ + if (list != null) { + for (T c : list) { + if (c.condition == oldOne) { + oldOne.removeBacklink(backlink); + c.condition = (ActorCondition) newOne; + if (newOne != null) newOne.addBacklink(backlink); + } + } + } + + } //region link common stuff public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { if (conditions != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 5f44f59..30b9480 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -308,42 +308,18 @@ public class Item extends JSONElement { this.category = (ItemCategory) newOne; if (newOne != null) newOne.addBacklink(this); } else { - if (this.equip_effect != null && this.equip_effect.conditions != null) { - for (ActorConditionEffect c : this.equip_effect.conditions) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } + if (this.equip_effect != null) { + if (this.equip_effect.conditions != null) { + actorConditionElementChanged(this.equip_effect.conditions, oldOne, newOne, this); } } - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedActorConditionEffect c : this.hit_effect.conditions_source) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedActorConditionEffect c : this.hit_effect.conditions_target) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } + if (this.hit_effect != null) { + actorConditionElementChanged(this.hit_effect.conditions_source, oldOne, newOne, this); + actorConditionElementChanged(this.hit_effect.conditions_target, oldOne, newOne, this); } - if (this.kill_effect != null && this.kill_effect.conditions_source != null) { - for (TimedActorConditionEffect c : this.kill_effect.conditions_source) { - if (c.condition == oldOne) { - oldOne.removeBacklink(this); - c.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } + if (this.kill_effect != null) { + actorConditionElementChanged(this.kill_effect.conditions_source, oldOne, newOne, this); } } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 4d9e424..3dec0fe 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -171,19 +171,7 @@ public class NPC extends JSONElement { Map hitEffect = (Map) npcJson.get("hitEffect"); if (hitEffect != null) { - this.hit_effect = new HitEffect(); - if (hitEffect.get("increaseCurrentHP") != null) { - this.hit_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("max"))); - this.hit_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentHP")).get("min"))); - } - if (hitEffect.get("increaseCurrentAP") != null) { - this.hit_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("max"))); - this.hit_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) hitEffect.get("increaseCurrentAP")).get("min"))); - } - List conditionsSourceJson = (List) hitEffect.get("conditionsSource"); - this.hit_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); - List conditionsTargetJson = (List) hitEffect.get("conditionsTarget"); - this.hit_effect.conditions_target = parseTimedConditionEffects(conditionsTargetJson); + this.hit_effect = parseHitEffect(hitEffect); } Map hitReceivedEffect = (Map) npcJson.get("hitReceivedEffect"); @@ -193,19 +181,8 @@ public class NPC extends JSONElement { Map deathEffect = (Map) npcJson.get("deathEffect"); if (deathEffect != null) { - this.death_effect = new HitEffect(); - if (deathEffect.get("increaseCurrentHP") != null) { - this.death_effect.hp_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("max"))); - this.death_effect.hp_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentHP")).get("min"))); - } - if (deathEffect.get("increaseCurrentAP") != null) { - this.death_effect.ap_boost_max = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("max"))); - this.death_effect.ap_boost_min = JSONElement.getInteger((Number) (((Map) deathEffect.get("increaseCurrentAP")).get("min"))); - } - List conditionsSourceJson = (List) deathEffect.get("conditionsSource"); - this.death_effect.conditions_source = parseTimedConditionEffects(conditionsSourceJson); + this.death_effect = parseDeathEffect(deathEffect); } - } @Override @@ -302,23 +279,9 @@ public class NPC extends JSONElement { this.droplist = (Droplist) newOne; if (newOne != null) newOne.addBacklink(this); } else { - if (this.hit_effect != null && this.hit_effect.conditions_source != null) { - for (TimedActorConditionEffect tce : this.hit_effect.conditions_source) { - if (tce.condition == oldOne) { - oldOne.removeBacklink(this); - tce.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } - } - if (this.hit_effect != null && this.hit_effect.conditions_target != null) { - for (TimedActorConditionEffect tce : this.hit_effect.conditions_target) { - if (tce.condition == oldOne) { - oldOne.removeBacklink(this); - tce.condition = (ActorCondition) newOne; - if (newOne != null) newOne.addBacklink(this); - } - } + if (this.hit_effect != null) { + actorConditionElementChanged(this.hit_effect.conditions_source, oldOne, newOne, this); + actorConditionElementChanged(this.hit_effect.conditions_target, oldOne, newOne, this); } } } From 63e381a804df7f6cdde6caeb6d02f0834bd06a58 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 17:35:46 +0200 Subject: [PATCH 53/94] move ConditionsCellRenderer to CommonEditor --- .../ui/gamedataeditors/CommonEditor.java | 25 +++++++++++++++++ .../ui/gamedataeditors/ItemEditor.java | 27 +------------------ 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 00bd0b2..d717615 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -43,4 +43,29 @@ public class CommonEditor { return c; } } + public static class ConditionsCellRenderer extends DefaultListCellRenderer { + private static final long serialVersionUID = 7987880146189575234L; + + @Override + public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + if (c instanceof JLabel) { + JLabel label = ((JLabel) c); + Common.ActorConditionEffect effect = (Common.ActorConditionEffect) value; + + if (effect.condition != null) { + if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { + label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); + label.setText("Immune to actor condition " + effect.condition.getDesc()); + } else { + label.setIcon(new ImageIcon(effect.condition.getIcon())); + label.setText("Give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude); + } + } else { + label.setText("New, undefined actor condition effect."); + } + } + return c; + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 6f956c6..24b88c8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -211,7 +211,7 @@ public class ItemEditor extends JSONElementEditor { String titleEquipConditions = "Actor Conditions applied when equipped: "; equipConditionsModel = new ConditionsListModel(equipEffect); - ConditionsCellRenderer cellRendererEquipConditions = new ConditionsCellRenderer(); + CommonEditor.ConditionsCellRenderer cellRendererEquipConditions = new CommonEditor.ConditionsCellRenderer(); BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; BasicLambda selectedResetEquipConditions = ()->selectedEquipEffectCondition = null; @@ -1033,31 +1033,6 @@ public class ItemEditor extends JSONElementEditor { } } - public static class ConditionsCellRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 7987880146189575234L; - - @Override - public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel) c); - Common.ActorConditionEffect effect = (Common.ActorConditionEffect) value; - - if (effect.condition != null) { - if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { - label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText("Immune to actor condition " + effect.condition.getDesc()); - } else { - label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText("Give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude); - } - } else { - label.setText("New, undefined actor condition effect."); - } - } - return c; - } - } public static boolean isNull(Item.EquipEffect effect) { if (effect.conditions != null) return false; From f22052525cab6e3c6bbbe3532ef422f8f9f1319a Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 17:37:13 +0200 Subject: [PATCH 54/94] change wrong ConditionsCellRenderer to TimedConditionsCellRenderer --- .../gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 24b88c8..c5959e0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -287,7 +287,7 @@ public class ItemEditor extends JSONElementEditor { hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); String titleHitTargetConditions = "Actor Conditions applied to the target: "; hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); - ConditionsCellRenderer cellRendererHitTargetConditions = new ConditionsCellRenderer(); + CommonEditor.TimedConditionsCellRenderer cellRendererHitTargetConditions = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetHitTargetConditions = (value)->selectedHitEffectTargetCondition = value; BasicLambdaWithReturn selectedGetHitTargetConditions = ()->selectedHitEffectTargetCondition ; BasicLambda selectedResetHitTargetConditions = ()->selectedHitEffectTargetCondition = null; From 2ea425dda64723714512b2dd940d869afe96d519 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 18:20:52 +0200 Subject: [PATCH 55/94] use isImmunity & isClear & isInfinite more --- .../ui/gamedataeditors/ItemEditor.java | 24 +++++++------- .../ui/gamedataeditors/NPCEditor.java | 32 +++++++++---------- 2 files changed, 27 insertions(+), 29 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index c5959e0..afee997 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -537,9 +537,9 @@ public class ItemEditor extends JSONElementEditor { public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitSourceConditionClear.setSelected(clear); hitSourceConditionApply.setSelected(!clear && !immunity); @@ -728,9 +728,9 @@ public class ItemEditor extends JSONElementEditor { public void updateKillSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); killSourceConditionClear.setSelected(clear); killSourceConditionApply.setSelected(!clear && !immunity); @@ -872,9 +872,9 @@ public class ItemEditor extends JSONElementEditor { public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitReceivedSourceConditionClear.setSelected(clear); hitReceivedSourceConditionApply.setSelected(!clear && !immunity); @@ -968,9 +968,9 @@ public class ItemEditor extends JSONElementEditor { public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitReceivedTargetConditionClear.setSelected(clear); hitReceivedTargetConditionApply.setSelected(!clear && !immunity); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 32dada8..fe336aa 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -487,9 +487,9 @@ public class NPCEditor extends JSONElementEditor { public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitSourceConditionClear.setSelected(clear); hitSourceConditionApply.setSelected(!clear && !immunity); @@ -576,10 +576,9 @@ public class NPCEditor extends JSONElementEditor { } public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitTargetConditionClear.setSelected(clear); hitTargetConditionApply.setSelected(!clear && !immunity); @@ -667,10 +666,9 @@ public class NPCEditor extends JSONElementEditor { } public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitReceivedSourceConditionClear.setSelected(clear); hitReceivedSourceConditionApply.setSelected(!clear && !immunity); @@ -758,9 +756,9 @@ public class NPCEditor extends JSONElementEditor { public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); hitReceivedTargetConditionClear.setSelected(clear); hitReceivedTargetConditionApply.setSelected(!clear && !immunity); @@ -848,9 +846,9 @@ public class NPCEditor extends JSONElementEditor { public void updateDeathSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration != null && condition.duration > ActorCondition.DURATION_NONE); - boolean clear = (condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR) && (condition.duration == null || condition.duration == ActorCondition.DURATION_NONE); - boolean forever = condition.duration != null && condition.duration == ActorCondition.DURATION_FOREVER; + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); deathSourceConditionClear.setSelected(clear); deathSourceConditionApply.setSelected(!clear && !immunity); From ad15063dccf854beecb5b43ec6362099aaaf3c58 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 18:23:54 +0200 Subject: [PATCH 56/94] start to extract HitEffectPane --- .../ui/gamedataeditors/CommonEditor.java | 121 ++++- .../ui/gamedataeditors/ItemEditor.java | 16 +- .../ui/gamedataeditors/NPCEditor.java | 468 +++++++----------- 3 files changed, 317 insertions(+), 288 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index d717615..c729eba 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -2,12 +2,19 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.Common; -import com.gpl.rpg.atcontentstudio.ui.DefaultIcons; -import com.gpl.rpg.atcontentstudio.ui.OverlayIcon; +import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; +import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.utils.BasicLambda; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; +import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithReturn; +import com.gpl.rpg.atcontentstudio.utils.UiUtils; +import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; import java.awt.*; +import static com.gpl.rpg.atcontentstudio.ui.Editor.addIntegerField; + public class CommonEditor { public static class TimedConditionsCellRenderer extends DefaultListCellRenderer { @@ -68,4 +75,114 @@ public class CommonEditor { return c; } } + + public static class HitEffectPane { + Common.HitEffect hitEffect; + CollapsiblePanel hitEffectPane; + JSpinner hitEffectHPMin; + JSpinner hitEffectHPMax; + JSpinner hitEffectAPMin; + JSpinner hitEffectAPMax; + NPCEditor.SourceTimedConditionsListModel hitSourceConditionsModel; + NPCEditor.TargetTimedConditionsListModel hitTargetConditionsListModel; + JList hitSourceConditionsList; + JList hitTargetConditionsList; + Common.TimedActorConditionEffect selectedHitEffectSourceCondition; + Common.TimedActorConditionEffect selectedHitEffectTargetCondition; + + + Editor.MyComboBox hitSourceConditionBox; + JSpinner hitSourceConditionChance; + JRadioButton hitSourceConditionClear; + JRadioButton hitSourceConditionApply; + JRadioButton hitSourceConditionImmunity; + JSpinner hitSourceConditionMagnitude; + JRadioButton hitSourceConditionTimed; + JRadioButton hitSourceConditionForever; + JSpinner hitSourceConditionDuration; + + Editor.MyComboBox hitTargetConditionBox; + JSpinner hitTargetConditionChance; + JRadioButton hitTargetConditionClear; + JRadioButton hitTargetConditionApply; + JRadioButton hitTargetConditionImmunity; + JSpinner hitTargetConditionMagnitude; + JRadioButton hitTargetConditionTimed; + JRadioButton hitTargetConditionForever; + JSpinner hitTargetConditionDuration; + + /* + * create a new HitEffectPane with the selections (probably passed in from last time) + */ + public HitEffectPane(Common.TimedActorConditionEffect selectedHitEffectSourceCondition, Common.TimedActorConditionEffect selectedHitEffectTargetCondition) { + this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; + this.selectedHitEffectSourceCondition = selectedHitEffectSourceCondition; + } + + void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, BasicLambdaWithArg updatePaneSource, BasicLambdaWithArg updatePaneTarget) { + hitEffectPane = new CollapsiblePanel("Effect on every hit: "); + hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.hit_effect == null) { + hitEffect = new Common.HitEffect(); + } else { + hitEffect = npc.hit_effect; + } + hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); + hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); + hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); + hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); + + String titleSource = "Actor Conditions applied to the source: "; + hitSourceConditionsModel = new NPCEditor.SourceTimedConditionsListModel(hitEffect); + CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetSource = (value)-> selectedHitEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetSource = ()-> selectedHitEffectSourceCondition ; + BasicLambda selectedResetSource = ()-> selectedHitEffectSourceCondition = null; + + var resultSource = UiUtils.getCollapsibleItemList(listener, + hitSourceConditionsModel, + selectedResetSource, + selectedSetSource, + selectedGetSource, + (x) -> {}, + updatePaneSource, + npc.writable, + Common.TimedActorConditionEffect::new, + cellRendererSource, + titleSource, + (x) -> null); + hitSourceConditionsList = resultSource.list; + CollapsiblePanel hitSourceConditionsPane = resultSource.collapsiblePanel; + if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { + hitSourceConditionsPane.collapse(); + } + hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + + String titleTarget = "Actor Conditions applied to the target: "; + hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(hitEffect); + CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetTarget = (value)-> selectedHitEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetTarget = ()-> selectedHitEffectTargetCondition ; + BasicLambda selectedResetTarget = ()-> selectedHitEffectTargetCondition = null; + var resultTarget = UiUtils.getCollapsibleItemList(listener, + hitTargetConditionsListModel, + selectedResetTarget, + selectedSetTarget, + selectedGetTarget, + (x) -> {}, + updatePaneTarget, + npc.writable, + Common.TimedActorConditionEffect::new, + cellRendererTarget, + titleTarget, + (x) -> null); + hitTargetConditionsList = resultTarget.list; + CollapsiblePanel hitTargetConditionsPane = resultTarget.collapsiblePanel; + if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { + hitTargetConditionsPane.collapse(); + } + hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); + } + + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index afee997..9692fd8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -251,20 +251,17 @@ public class ItemEditor extends JSONElementEditor { hitHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, item.writable, listener); hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); - hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); + String title = "Actor Conditions applied to the source: "; + hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); + CommonEditor.TimedConditionsCellRenderer cellRenderer = new CommonEditor.TimedConditionsCellRenderer(); + BasicLambdaWithArg setSelected = (selectedItem) -> selectedHitEffectSourceCondition = selectedItem; BasicLambdaWithReturn getSelected = () -> hitSourceConditionsList.getSelectedValue(); - BasicLambda resetSelected = () -> { - selectedHitEffectSourceCondition = null; - }; - BasicLambdaWithArg setSelected = (selectedItem) -> { - selectedHitEffectSourceCondition = selectedItem; - }; + BasicLambda resetSelected = () -> selectedHitEffectSourceCondition = null; BasicLambdaWithArg valueChanged = (selectedReply) -> { }; BasicLambdaWithArg updateEditorPane = (editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener); - CommonEditor.TimedConditionsCellRenderer cellRenderer = new CommonEditor.TimedConditionsCellRenderer(); - String title = "Actor Conditions applied to the source: "; + var collapsibleItemList = UiUtils.getCollapsibleItemList( listener, hitSourceConditionsModel, @@ -285,6 +282,7 @@ public class ItemEditor extends JSONElementEditor { hitSourceConditionsPane.collapse(); } hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + String titleHitTargetConditions = "Actor Conditions applied to the target: "; hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); CommonEditor.TimedConditionsCellRenderer cellRendererHitTargetConditions = new CommonEditor.TimedConditionsCellRenderer(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index fe336aa..116591e 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -29,8 +29,6 @@ public class NPCEditor extends JSONElementEditor { private static final String json_view_id = "JSON"; private static final String dialogue_tree_id = "Dialogue Tree"; - private Common.TimedActorConditionEffect selectedHitEffectSourceCondition; - private Common.TimedActorConditionEffect selectedHitEffectTargetCondition; private Common.TimedActorConditionEffect selectedHitReceivedEffectSourceCondition; private Common.TimedActorConditionEffect selectedHitReceivedEffectTargetCondition; private Common.TimedActorConditionEffect selectedDeathEffectSourceCondition; @@ -62,38 +60,8 @@ public class NPCEditor extends JSONElementEditor { private JSpinner blockChance; private JSpinner dmgRes; - private Common.HitEffect hitEffect; - private CollapsiblePanel hitEffectPane; - private JSpinner hitEffectHPMin; - private JSpinner hitEffectHPMax; - private JSpinner hitEffectAPMin; - private JSpinner hitEffectAPMax; + private CommonEditor.HitEffectPane hitEffectPane; - private SourceTimedConditionsListModel hitSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; - private MyComboBox hitSourceConditionBox; - private JSpinner hitSourceConditionChance; - private JRadioButton hitSourceConditionClear; - private JRadioButton hitSourceConditionApply; - private JRadioButton hitSourceConditionImmunity; - private JSpinner hitSourceConditionMagnitude; - private JRadioButton hitSourceConditionTimed; - private JRadioButton hitSourceConditionForever; - private JSpinner hitSourceConditionDuration; - - private TargetTimedConditionsListModel hitTargetConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitTargetConditionsList; - private MyComboBox hitTargetConditionBox; - private JSpinner hitTargetConditionChance; - private JRadioButton hitTargetConditionClear; - private JRadioButton hitTargetConditionApply; - private JRadioButton hitTargetConditionImmunity; - private JSpinner hitTargetConditionMagnitude; - private JRadioButton hitTargetConditionTimed; - private JRadioButton hitTargetConditionForever; - private JSpinner hitTargetConditionDuration; private Common.HitReceivedEffect hitReceivedEffect; private CollapsiblePanel hitReceivedEffectPane; @@ -237,70 +205,15 @@ public class NPCEditor extends JSONElementEditor { critMult = addDoubleField(combatTraitPane, "Critical multiplier: ", npc.critical_multiplier, npc.writable, listener); blockChance = addIntegerField(combatTraitPane, "Block chance: ", npc.block_chance, false, npc.writable, listener); dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = npc.hit_effect; - } - hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); - hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); - hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); - hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); - String titleSource = "Actor Conditions applied to the source: "; - hitSourceConditionsListModel = new SourceTimedConditionsListModel(hitEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetSource = (value)->selectedHitEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetSource = ()->selectedHitEffectSourceCondition ; - BasicLambda selectedResetSource = ()->selectedHitEffectSourceCondition = null; - BasicLambdaWithArg updatePaneSource = (editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener); - - var resultSource = UiUtils.getCollapsibleItemList(listener, - hitSourceConditionsListModel, - selectedResetSource, - selectedSetSource, - selectedGetSource, - (x) -> {}, + hitEffectPane = new CommonEditor.HitEffectPane(this.hitEffectPane.selectedHitEffectSourceCondition, this.hitEffectPane.selectedHitEffectTargetCondition); + BasicLambdaWithArg updatePaneSource =(editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, hitEffectPane.selectedHitEffectSourceCondition, listener); + BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, hitEffectPane.selectedHitEffectTargetCondition, listener); + hitEffectPane.createHitEffectPaneContent(npc, + listener, updatePaneSource, - npc.writable, - Common.TimedActorConditionEffect::new, - cellRendererSource, - titleSource, - (x) -> null); - hitSourceConditionsList = resultSource.list; - CollapsiblePanel hitSourceConditionsPane = resultSource.collapsiblePanel; - if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); - } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - - String titleTarget = "Actor Conditions applied to the target: "; - hitTargetConditionsListModel = new TargetTimedConditionsListModel(hitEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetTarget = (value)->selectedHitEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetTarget = ()->selectedHitEffectTargetCondition ; - BasicLambda selectedResetTarget = ()->selectedHitEffectTargetCondition = null; - BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener); - var resultTarget = UiUtils.getCollapsibleItemList(listener, - hitTargetConditionsListModel, - selectedResetTarget, - selectedSetTarget, - selectedGetTarget, - (x) -> {}, - updatePaneTarget, - npc.writable, - Common.TimedActorConditionEffect::new, - cellRendererTarget, - titleTarget, - (x) -> null); - hitTargetConditionsList = resultTarget.list; - CollapsiblePanel hitTargetConditionsPane = resultTarget.collapsiblePanel; - if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { - hitTargetConditionsPane.collapse(); - } - combatTraitPane.add(hitEffectPane, JideBoxLayout.FIX); + updatePaneTarget); + combatTraitPane.add(hitEffectPane.hitEffectPane, JideBoxLayout.FIX); hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); @@ -413,72 +326,74 @@ public class NPCEditor extends JSONElementEditor { pane.add(combatTraitPane, JideBoxLayout.FIX); } + + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); - if (hitSourceConditionBox != null) { - removeElementListener(hitSourceConditionBox); + if (hitEffectPane.hitSourceConditionBox != null) { + removeElementListener(hitEffectPane.hitSourceConditionBox); } boolean writable = ((NPC) target).writable; Project proj = ((NPC) target).getProject(); - hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitEffectPane.hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitEffectPane.hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + hitEffectPane.hitSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitEffectPane.hitSourceConditionClear, JideBoxLayout.FIX); + hitEffectPane.hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitEffectPane.hitSourceConditionApply, JideBoxLayout.FIX); + hitEffectPane.hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitEffectPane.hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitEffectPane.hitSourceConditionImmunity, JideBoxLayout.FIX); ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); + radioEffectGroup.add(hitEffectPane.hitSourceConditionApply); + radioEffectGroup.add(hitEffectPane.hitSourceConditionClear); + radioEffectGroup.add(hitEffectPane.hitSourceConditionImmunity); - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + hitEffectPane.hitSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitEffectPane.hitSourceConditionTimed, JideBoxLayout.FIX); + hitEffectPane.hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitEffectPane.hitSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitEffectPane.hitSourceConditionForever, JideBoxLayout.FIX); ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); + radioDurationGroup.add(hitEffectPane.hitSourceConditionTimed); + radioDurationGroup.add(hitEffectPane.hitSourceConditionForever); updateHitSourceTimedConditionWidgets(condition); - hitSourceConditionClear.addActionListener(new ActionListener() { + hitEffectPane.hitSourceConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + listener.valueChanged(hitEffectPane.hitSourceConditionClear, new Boolean(hitEffectPane.hitSourceConditionClear.isSelected())); } }); - hitSourceConditionApply.addActionListener(new ActionListener() { + hitEffectPane.hitSourceConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + listener.valueChanged(hitEffectPane.hitSourceConditionApply, new Boolean(hitEffectPane.hitSourceConditionApply.isSelected())); } }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { + hitEffectPane.hitSourceConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + listener.valueChanged(hitEffectPane.hitSourceConditionImmunity, new Boolean(hitEffectPane.hitSourceConditionImmunity.isSelected())); } }); - hitSourceConditionTimed.addActionListener(new ActionListener() { + hitEffectPane.hitSourceConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + listener.valueChanged(hitEffectPane.hitSourceConditionTimed, new Boolean(hitEffectPane.hitSourceConditionTimed.isSelected())); } }); - hitSourceConditionForever.addActionListener(new ActionListener() { + hitEffectPane.hitSourceConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + listener.valueChanged(hitEffectPane.hitSourceConditionForever, new Boolean(hitEffectPane.hitSourceConditionForever.isSelected())); } }); pane.revalidate(); @@ -491,84 +406,84 @@ public class NPCEditor extends JSONElementEditor { boolean clear = condition.isClear(); boolean forever = condition.isInfinite(); - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); + hitEffectPane.hitSourceConditionClear.setSelected(clear); + hitEffectPane.hitSourceConditionApply.setSelected(!clear && !immunity); + hitEffectPane.hitSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitEffectPane.hitSourceConditionImmunity.setSelected(immunity); - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); + hitEffectPane.hitSourceConditionTimed.setSelected(!forever); + hitEffectPane.hitSourceConditionTimed.setEnabled(!clear); + hitEffectPane.hitSourceConditionDuration.setEnabled(!clear && !forever); + hitEffectPane.hitSourceConditionForever.setSelected(forever); + hitEffectPane.hitSourceConditionForever.setEnabled(!clear); } public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); - if (hitTargetConditionBox != null) { - removeElementListener(hitTargetConditionBox); + if (hitEffectPane.hitTargetConditionBox != null) { + removeElementListener(hitEffectPane.hitTargetConditionBox); } - boolean writable = ((NPC) target).writable; - Project proj = ((NPC) target).getProject(); + boolean writable = target.writable; + Project proj = target.getProject(); - hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitTargetConditionClear, JideBoxLayout.FIX); - hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); + hitEffectPane.hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitEffectPane.hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitEffectPane.hitTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitEffectPane.hitTargetConditionClear, JideBoxLayout.FIX); + hitEffectPane.hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitEffectPane.hitTargetConditionApply, JideBoxLayout.FIX); + hitEffectPane.hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitEffectPane.hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitEffectPane.hitTargetConditionImmunity, JideBoxLayout.FIX); ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitTargetConditionApply); - radioEffectGroup.add(hitTargetConditionClear); - radioEffectGroup.add(hitTargetConditionImmunity); + radioEffectGroup.add(hitEffectPane.hitTargetConditionApply); + radioEffectGroup.add(hitEffectPane.hitTargetConditionClear); + radioEffectGroup.add(hitEffectPane.hitTargetConditionImmunity); - hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitTargetConditionForever, JideBoxLayout.FIX); + hitEffectPane.hitTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitEffectPane.hitTargetConditionTimed, JideBoxLayout.FIX); + hitEffectPane.hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitEffectPane.hitTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitEffectPane.hitTargetConditionForever, JideBoxLayout.FIX); ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitTargetConditionTimed); - radioDurationGroup.add(hitTargetConditionForever); + radioDurationGroup.add(hitEffectPane.hitTargetConditionTimed); + radioDurationGroup.add(hitEffectPane.hitTargetConditionForever); updateHitTargetTimedConditionWidgets(condition); - hitTargetConditionClear.addActionListener(new ActionListener() { + hitEffectPane.hitTargetConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + listener.valueChanged(hitEffectPane.hitTargetConditionClear, new Boolean(hitEffectPane.hitTargetConditionClear.isSelected())); } }); - hitTargetConditionApply.addActionListener(new ActionListener() { + hitEffectPane.hitTargetConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + listener.valueChanged(hitEffectPane.hitTargetConditionApply, new Boolean(hitEffectPane.hitTargetConditionApply.isSelected())); } }); - hitTargetConditionImmunity.addActionListener(new ActionListener() { + hitEffectPane.hitTargetConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + listener.valueChanged(hitEffectPane.hitTargetConditionImmunity, new Boolean(hitEffectPane.hitTargetConditionImmunity.isSelected())); } }); - hitTargetConditionTimed.addActionListener(new ActionListener() { + hitEffectPane.hitTargetConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + listener.valueChanged(hitEffectPane.hitTargetConditionTimed, new Boolean(hitEffectPane.hitTargetConditionTimed.isSelected())); } }); - hitTargetConditionForever.addActionListener(new ActionListener() { + hitEffectPane.hitTargetConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + listener.valueChanged(hitEffectPane.hitTargetConditionForever, new Boolean(hitEffectPane.hitTargetConditionForever.isSelected())); } }); pane.revalidate(); @@ -580,16 +495,15 @@ public class NPCEditor extends JSONElementEditor { boolean clear = condition.isClear(); boolean forever = condition.isInfinite(); - hitTargetConditionClear.setSelected(clear); - hitTargetConditionApply.setSelected(!clear && !immunity); - hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitTargetConditionImmunity.setSelected(immunity); - - hitTargetConditionTimed.setSelected(!forever); - hitTargetConditionTimed.setEnabled(!clear); - hitTargetConditionDuration.setEnabled(!clear && !forever); - hitTargetConditionForever.setSelected(forever); - hitTargetConditionForever.setEnabled(!clear); + hitEffectPane.hitTargetConditionClear.setSelected(clear); + hitEffectPane.hitTargetConditionApply.setSelected(!clear && !immunity); + hitEffectPane.hitTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitEffectPane.hitTargetConditionImmunity.setSelected(immunity); + hitEffectPane.hitTargetConditionTimed.setSelected(!forever); + hitEffectPane.hitTargetConditionTimed.setEnabled(!clear); + hitEffectPane.hitTargetConditionDuration.setEnabled(!clear && !forever); + hitEffectPane.hitTargetConditionForever.setSelected(forever); + hitEffectPane.hitTargetConditionForever.setEnabled(!clear); } @@ -1019,132 +933,132 @@ public class NPCEditor extends JSONElementEditor { npc.block_chance = (Integer) value; } else if (source == dmgRes) { npc.damage_resistance = (Integer) value; - } else if (source == hitEffectHPMin) { - hitEffect.hp_boost_min = (Integer) value; + } else if (source == hitEffectPane.hitEffectHPMin) { + hitEffectPane.hitEffect.hp_boost_min = (Integer) value; updateHit = true; - } else if (source == hitEffectHPMax) { - hitEffect.hp_boost_max = (Integer) value; + } else if (source == hitEffectPane.hitEffectHPMax) { + hitEffectPane.hitEffect.hp_boost_max = (Integer) value; updateHit = true; - } else if (source == hitEffectAPMin) { - hitEffect.ap_boost_min = (Integer) value; + } else if (source == hitEffectPane.hitEffectAPMin) { + hitEffectPane.hitEffect.ap_boost_min = (Integer) value; updateHit = true; - } else if (source == hitEffectAPMax) { - hitEffect.ap_boost_max = (Integer) value; + } else if (source == hitEffectPane.hitEffectAPMax) { + hitEffectPane.hitEffect.ap_boost_max = (Integer) value; updateHit = true; - } else if (source == hitSourceConditionsList) { + } else if (source == hitEffectPane.hitSourceConditionsList) { updateHit = true; - } else if (source == hitSourceConditionBox) { - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.removeBacklink(npc); + } else if (source == hitEffectPane.hitSourceConditionBox) { + if (hitEffectPane.selectedHitEffectSourceCondition.condition != null) { + hitEffectPane.selectedHitEffectSourceCondition.condition.removeBacklink(npc); } - selectedHitEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitEffectSourceCondition.condition != null) { - selectedHitEffectSourceCondition.condition.addBacklink(npc); - selectedHitEffectSourceCondition.condition_id = selectedHitEffectSourceCondition.condition.id; + hitEffectPane.selectedHitEffectSourceCondition.condition = (ActorCondition) value; + if (hitEffectPane.selectedHitEffectSourceCondition.condition != null) { + hitEffectPane.selectedHitEffectSourceCondition.condition.addBacklink(npc); + hitEffectPane.selectedHitEffectSourceCondition.condition_id = hitEffectPane.selectedHitEffectSourceCondition.condition.id; } else { - selectedHitEffectSourceCondition.condition_id = null; + hitEffectPane.selectedHitEffectSourceCondition.condition_id = null; } - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - } else if (source == hitSourceConditionClear && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.hitSourceConditionClear && (Boolean) value) { + hitEffectPane.selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + hitEffectPane.selectedHitEffectSourceCondition.duration = null; + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); updateHit = true; - } else if (source == hitSourceConditionApply && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; + } else if (source == hitEffectPane.hitSourceConditionApply && (Boolean) value) { + hitEffectPane.selectedHitEffectSourceCondition.magnitude = (Integer) hitEffectPane.hitSourceConditionMagnitude.getValue(); + hitEffectPane.selectedHitEffectSourceCondition.duration = hitEffectPane.hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitSourceConditionDuration.getValue(); + if (hitEffectPane.selectedHitEffectSourceCondition.duration == null || hitEffectPane.selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedHitEffectSourceCondition.duration = 1; } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); updateHit = true; - } else if (source == hitSourceConditionImmunity && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; + } else if (source == hitEffectPane.hitSourceConditionImmunity && (Boolean) value) { + hitEffectPane.selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + hitEffectPane.selectedHitEffectSourceCondition.duration = hitEffectPane.hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitSourceConditionDuration.getValue(); + if (hitEffectPane.selectedHitEffectSourceCondition.duration == null || hitEffectPane.selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedHitEffectSourceCondition.duration = 1; } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); updateHit = true; - } else if (source == hitSourceConditionMagnitude) { - selectedHitEffectSourceCondition.magnitude = (Integer) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.hitSourceConditionMagnitude) { + hitEffectPane.selectedHitEffectSourceCondition.magnitude = (Integer) value; + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); updateHit = true; - } else if (source == hitSourceConditionTimed && (Boolean) value) { - selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; + } else if (source == hitEffectPane.hitSourceConditionTimed && (Boolean) value) { + hitEffectPane.selectedHitEffectSourceCondition.duration = (Integer) hitEffectPane.hitSourceConditionDuration.getValue(); + if (hitEffectPane.selectedHitEffectSourceCondition.duration == null || hitEffectPane.selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedHitEffectSourceCondition.duration = 1; } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); updateHit = true; - } else if (source == hitSourceConditionForever && (Boolean) value) { - selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.hitSourceConditionForever && (Boolean) value) { + hitEffectPane.selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); updateHit = true; - } else if (source == hitSourceConditionDuration) { - selectedHitEffectSourceCondition.duration = (Integer) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.hitSourceConditionDuration) { + hitEffectPane.selectedHitEffectSourceCondition.duration = (Integer) value; + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); updateHit = true; - } else if (source == hitSourceConditionChance) { - selectedHitEffectSourceCondition.chance = (Double) value; - hitSourceConditionsListModel.itemChanged(selectedHitEffectSourceCondition); - } else if (source == hitTargetConditionsList) { + } else if (source == hitEffectPane.hitSourceConditionChance) { + hitEffectPane.selectedHitEffectSourceCondition.chance = (Double) value; + hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.hitTargetConditionsList) { updateHit = true; - } else if (source == hitTargetConditionBox) { - updateConditionEffect((ActorCondition) value, npc, selectedHitEffectTargetCondition, hitTargetConditionsListModel); - } else if (source == hitTargetConditionClear && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitEffectPane.hitTargetConditionBox) { + updateConditionEffect((ActorCondition) value, npc, hitEffectPane.selectedHitEffectTargetCondition, hitEffectPane.hitTargetConditionsListModel); + } else if (source == hitEffectPane.hitTargetConditionClear && (Boolean) value) { + hitEffectPane.selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + hitEffectPane.selectedHitEffectTargetCondition.duration = null; + updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); updateHit = true; - } else if (source == hitTargetConditionApply && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; + } else if (source == hitEffectPane.hitTargetConditionApply && (Boolean) value) { + hitEffectPane.selectedHitEffectTargetCondition.magnitude = (Integer) hitEffectPane.hitTargetConditionMagnitude.getValue(); + hitEffectPane.selectedHitEffectTargetCondition.duration = hitEffectPane.hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitTargetConditionDuration.getValue(); + if (hitEffectPane.selectedHitEffectTargetCondition.duration == null || hitEffectPane.selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedHitEffectTargetCondition.duration = 1; } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); updateHit = true; - } else if (source == hitTargetConditionImmunity && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; + } else if (source == hitEffectPane.hitTargetConditionImmunity && (Boolean) value) { + hitEffectPane.selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + hitEffectPane.selectedHitEffectTargetCondition.duration = hitEffectPane.hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitTargetConditionDuration.getValue(); + if (hitEffectPane.selectedHitEffectTargetCondition.duration == null || hitEffectPane.selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedHitEffectTargetCondition.duration = 1; } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); updateHit = true; - } else if (source == hitTargetConditionMagnitude) { - selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitEffectPane.hitTargetConditionMagnitude) { + hitEffectPane.selectedHitEffectTargetCondition.magnitude = (Integer) value; + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); updateHit = true; - } else if (source == hitTargetConditionTimed && (Boolean) value) { - selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; + } else if (source == hitEffectPane.hitTargetConditionTimed && (Boolean) value) { + hitEffectPane.selectedHitEffectTargetCondition.duration = (Integer) hitEffectPane.hitTargetConditionDuration.getValue(); + if (hitEffectPane.selectedHitEffectTargetCondition.duration == null || hitEffectPane.selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedHitEffectTargetCondition.duration = 1; } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); updateHit = true; - } else if (source == hitTargetConditionForever && (Boolean) value) { - selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitEffectPane.hitTargetConditionForever && (Boolean) value) { + hitEffectPane.selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); updateHit = true; - } else if (source == hitTargetConditionDuration) { - selectedHitEffectTargetCondition.duration = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitEffectPane.hitTargetConditionDuration) { + hitEffectPane.selectedHitEffectTargetCondition.duration = (Integer) value; + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); updateHit = true; - } else if (source == hitTargetConditionChance) { - selectedHitEffectTargetCondition.chance = (Double) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } else if (source == hitEffectPane.hitTargetConditionChance) { + hitEffectPane.selectedHitEffectTargetCondition.chance = (Double) value; + hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); } else if (source == hitReceivedEffectHPMin) { hitReceivedEffect.hp_boost_min = (Integer) value; updateHitReceived = true; @@ -1360,10 +1274,10 @@ public class NPCEditor extends JSONElementEditor { } if (updateHit) { - if (isNull(hitEffect)) { + if (isNull(hitEffectPane.hitEffect)) { npc.hit_effect = null; } else { - npc.hit_effect = hitEffect; + npc.hit_effect = hitEffectPane.hitEffect; } } if (updateHitReceived) { From 27a86ee654cdc22131d9354abbe10501ae010d1b Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 18:43:54 +0200 Subject: [PATCH 57/94] continue to extract HitEffectPane --- .../ui/gamedataeditors/CommonEditor.java | 184 +++++++++++++++++- .../ui/gamedataeditors/NPCEditor.java | 109 +---------- 2 files changed, 187 insertions(+), 106 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index c729eba..69527d1 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -1,5 +1,6 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; +import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.Common; import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; @@ -12,6 +13,8 @@ import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import static com.gpl.rpg.atcontentstudio.ui.Editor.addIntegerField; @@ -119,7 +122,7 @@ public class CommonEditor { this.selectedHitEffectSourceCondition = selectedHitEffectSourceCondition; } - void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, BasicLambdaWithArg updatePaneSource, BasicLambdaWithArg updatePaneTarget) { + void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor) { hitEffectPane = new CollapsiblePanel("Effect on every hit: "); hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); if (npc.hit_effect == null) { @@ -138,6 +141,7 @@ public class CommonEditor { BasicLambdaWithArg selectedSetSource = (value)-> selectedHitEffectSourceCondition = value; BasicLambdaWithReturn selectedGetSource = ()-> selectedHitEffectSourceCondition ; BasicLambda selectedResetSource = ()-> selectedHitEffectSourceCondition = null; + BasicLambdaWithArg updatePaneSource =(editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener, editor); var resultSource = UiUtils.getCollapsibleItemList(listener, hitSourceConditionsModel, @@ -164,6 +168,8 @@ public class CommonEditor { BasicLambdaWithArg selectedSetTarget = (value)-> selectedHitEffectTargetCondition = value; BasicLambdaWithReturn selectedGetTarget = ()-> selectedHitEffectTargetCondition ; BasicLambda selectedResetTarget = ()-> selectedHitEffectTargetCondition = null; + BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener, editor); + var resultTarget = UiUtils.getCollapsibleItemList(listener, hitTargetConditionsListModel, selectedResetTarget, @@ -184,5 +190,181 @@ public class CommonEditor { hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); } + public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { + pane.removeAll(); + if (hitSourceConditionBox != null) { + e.removeElementListener(hitSourceConditionBox); + } + + boolean writable = e.target.writable; + Project proj = e.target.getProject(); + + hitSourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitSourceConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitSourceConditionClear, JideBoxLayout.FIX); + hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitSourceConditionApply, JideBoxLayout.FIX); + hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitSourceConditionApply); + radioEffectGroup.add(hitSourceConditionClear); + radioEffectGroup.add(hitSourceConditionImmunity); + + hitSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); + hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitSourceConditionTimed); + radioDurationGroup.add(hitSourceConditionForever); + + updateHitSourceTimedConditionWidgets(condition); + + hitSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + } + }); + hitSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + } + }); + hitSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + } + }); + + hitSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + } + }); + hitSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { + pane.removeAll(); + if (hitTargetConditionBox != null) { + e.removeElementListener(hitTargetConditionBox); + } + + boolean writable = e.target.writable; + Project proj = e.target.getProject(); + + hitTargetConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitTargetConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitTargetConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitTargetConditionClear, JideBoxLayout.FIX); + hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitTargetConditionApply, JideBoxLayout.FIX); + hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitTargetConditionApply); + radioEffectGroup.add(hitTargetConditionClear); + radioEffectGroup.add(hitTargetConditionImmunity); + + hitTargetConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); + hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitTargetConditionForever = new JRadioButton("Forever"); + pane.add(hitTargetConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitTargetConditionTimed); + radioDurationGroup.add(hitTargetConditionForever); + + updateHitTargetTimedConditionWidgets(condition); + + hitTargetConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + } + }); + hitTargetConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + } + }); + hitTargetConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + } + }); + + hitTargetConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + } + }); + hitTargetConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + + public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); + + hitSourceConditionClear.setSelected(clear); + hitSourceConditionApply.setSelected(!clear && !immunity); + hitSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitSourceConditionImmunity.setSelected(immunity); + + hitSourceConditionTimed.setSelected(!forever); + hitSourceConditionTimed.setEnabled(!clear); + hitSourceConditionDuration.setEnabled(!clear && !forever); + hitSourceConditionForever.setSelected(forever); + hitSourceConditionForever.setEnabled(!clear); + } + + public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); + + hitTargetConditionClear.setSelected(clear); + hitTargetConditionApply.setSelected(!clear && !immunity); + hitTargetConditionMagnitude.setEnabled(!clear && !immunity); + hitTargetConditionImmunity.setSelected(immunity); + hitTargetConditionTimed.setSelected(!forever); + hitTargetConditionTimed.setEnabled(!clear); + hitTargetConditionDuration.setEnabled(!clear && !forever); + hitTargetConditionForever.setSelected(forever); + hitTargetConditionForever.setEnabled(!clear); + + } } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 116591e..a216516 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -207,12 +207,7 @@ public class NPCEditor extends JSONElementEditor { dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); hitEffectPane = new CommonEditor.HitEffectPane(this.hitEffectPane.selectedHitEffectSourceCondition, this.hitEffectPane.selectedHitEffectTargetCondition); - BasicLambdaWithArg updatePaneSource =(editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, hitEffectPane.selectedHitEffectSourceCondition, listener); - BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, hitEffectPane.selectedHitEffectTargetCondition, listener); - hitEffectPane.createHitEffectPaneContent(npc, - listener, - updatePaneSource, - updatePaneTarget); + hitEffectPane.createHitEffectPaneContent(npc, listener, this); combatTraitPane.add(hitEffectPane.hitEffectPane, JideBoxLayout.FIX); hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); @@ -320,6 +315,7 @@ public class NPCEditor extends JSONElementEditor { deathSourceConditionsPane.collapse(); } deathEffectPane.add(deathSourceConditionsPane, JideBoxLayout.FIX); + combatTraitPane.add(deathEffectPane, JideBoxLayout.FIX); @@ -401,109 +397,12 @@ public class NPCEditor extends JSONElementEditor { } public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitEffectPane.hitSourceConditionClear.setSelected(clear); - hitEffectPane.hitSourceConditionApply.setSelected(!clear && !immunity); - hitEffectPane.hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitEffectPane.hitSourceConditionImmunity.setSelected(immunity); - - hitEffectPane.hitSourceConditionTimed.setSelected(!forever); - hitEffectPane.hitSourceConditionTimed.setEnabled(!clear); - hitEffectPane.hitSourceConditionDuration.setEnabled(!clear && !forever); - hitEffectPane.hitSourceConditionForever.setSelected(forever); - hitEffectPane.hitSourceConditionForever.setEnabled(!clear); + hitEffectPane.updateHitSourceTimedConditionWidgets(condition); } - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitEffectPane.hitTargetConditionBox != null) { - removeElementListener(hitEffectPane.hitTargetConditionBox); - } - - boolean writable = target.writable; - Project proj = target.getProject(); - - hitEffectPane.hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitEffectPane.hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitEffectPane.hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitEffectPane.hitTargetConditionClear, JideBoxLayout.FIX); - hitEffectPane.hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitEffectPane.hitTargetConditionApply, JideBoxLayout.FIX); - hitEffectPane.hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitEffectPane.hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitEffectPane.hitTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitEffectPane.hitTargetConditionApply); - radioEffectGroup.add(hitEffectPane.hitTargetConditionClear); - radioEffectGroup.add(hitEffectPane.hitTargetConditionImmunity); - - hitEffectPane.hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitEffectPane.hitTargetConditionTimed, JideBoxLayout.FIX); - hitEffectPane.hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitEffectPane.hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitEffectPane.hitTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitEffectPane.hitTargetConditionTimed); - radioDurationGroup.add(hitEffectPane.hitTargetConditionForever); - - updateHitTargetTimedConditionWidgets(condition); - - hitEffectPane.hitTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitTargetConditionClear, new Boolean(hitEffectPane.hitTargetConditionClear.isSelected())); - } - }); - hitEffectPane.hitTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitTargetConditionApply, new Boolean(hitEffectPane.hitTargetConditionApply.isSelected())); - } - }); - hitEffectPane.hitTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitTargetConditionImmunity, new Boolean(hitEffectPane.hitTargetConditionImmunity.isSelected())); - } - }); - - hitEffectPane.hitTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitTargetConditionTimed, new Boolean(hitEffectPane.hitTargetConditionTimed.isSelected())); - } - }); - hitEffectPane.hitTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitTargetConditionForever, new Boolean(hitEffectPane.hitTargetConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitEffectPane.hitTargetConditionClear.setSelected(clear); - hitEffectPane.hitTargetConditionApply.setSelected(!clear && !immunity); - hitEffectPane.hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitEffectPane.hitTargetConditionImmunity.setSelected(immunity); - hitEffectPane.hitTargetConditionTimed.setSelected(!forever); - hitEffectPane.hitTargetConditionTimed.setEnabled(!clear); - hitEffectPane.hitTargetConditionDuration.setEnabled(!clear && !forever); - hitEffectPane.hitTargetConditionForever.setSelected(forever); - hitEffectPane.hitTargetConditionForever.setEnabled(!clear); + hitEffectPane.updateHitTargetTimedConditionWidgets(condition); } From ab91d330bde78609bacafac8d947056d06e7f92b Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 18:50:58 +0200 Subject: [PATCH 58/94] extract parts of HitEffectPane into DeathEffectPane for better usage --- .../ui/gamedataeditors/CommonEditor.java | 305 ++++++++++-------- .../ui/gamedataeditors/NPCEditor.java | 2 +- 2 files changed, 164 insertions(+), 143 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 69527d1..8e68f07 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -79,31 +79,18 @@ public class CommonEditor { } } - public static class HitEffectPane { + public static class HitEffectPane extends DeathEffectPane { Common.HitEffect hitEffect; CollapsiblePanel hitEffectPane; JSpinner hitEffectHPMin; JSpinner hitEffectHPMax; JSpinner hitEffectAPMin; JSpinner hitEffectAPMax; - NPCEditor.SourceTimedConditionsListModel hitSourceConditionsModel; NPCEditor.TargetTimedConditionsListModel hitTargetConditionsListModel; JList hitSourceConditionsList; JList hitTargetConditionsList; - Common.TimedActorConditionEffect selectedHitEffectSourceCondition; Common.TimedActorConditionEffect selectedHitEffectTargetCondition; - - Editor.MyComboBox hitSourceConditionBox; - JSpinner hitSourceConditionChance; - JRadioButton hitSourceConditionClear; - JRadioButton hitSourceConditionApply; - JRadioButton hitSourceConditionImmunity; - JSpinner hitSourceConditionMagnitude; - JRadioButton hitSourceConditionTimed; - JRadioButton hitSourceConditionForever; - JSpinner hitSourceConditionDuration; - Editor.MyComboBox hitTargetConditionBox; JSpinner hitTargetConditionChance; JRadioButton hitTargetConditionClear; @@ -118,49 +105,12 @@ public class CommonEditor { * create a new HitEffectPane with the selections (probably passed in from last time) */ public HitEffectPane(Common.TimedActorConditionEffect selectedHitEffectSourceCondition, Common.TimedActorConditionEffect selectedHitEffectTargetCondition) { + super(selectedHitEffectSourceCondition); this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; - this.selectedHitEffectSourceCondition = selectedHitEffectSourceCondition; } void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor) { - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = npc.hit_effect; - } - hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); - hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); - hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); - hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); - - String titleSource = "Actor Conditions applied to the source: "; - hitSourceConditionsModel = new NPCEditor.SourceTimedConditionsListModel(hitEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetSource = (value)-> selectedHitEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetSource = ()-> selectedHitEffectSourceCondition ; - BasicLambda selectedResetSource = ()-> selectedHitEffectSourceCondition = null; - BasicLambdaWithArg updatePaneSource =(editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener, editor); - - var resultSource = UiUtils.getCollapsibleItemList(listener, - hitSourceConditionsModel, - selectedResetSource, - selectedSetSource, - selectedGetSource, - (x) -> {}, - updatePaneSource, - npc.writable, - Common.TimedActorConditionEffect::new, - cellRendererSource, - titleSource, - (x) -> null); - hitSourceConditionsList = resultSource.list; - CollapsiblePanel hitSourceConditionsPane = resultSource.collapsiblePanel; - if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); - } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + createDeathEffectPaneContent(npc, listener, editor); String titleTarget = "Actor Conditions applied to the target: "; hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(hitEffect); @@ -190,77 +140,6 @@ public class CommonEditor { hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); } - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { - pane.removeAll(); - if (hitSourceConditionBox != null) { - e.removeElementListener(hitSourceConditionBox); - } - - boolean writable = e.target.writable; - Project proj = e.target.getProject(); - - hitSourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); - - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); - - updateHitSourceTimedConditionWidgets(condition); - - hitSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); - } - }); - hitSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); - } - }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); - } - }); - - hitSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); - } - }); - hitSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { pane.removeAll(); if (hitTargetConditionBox != null) { @@ -332,24 +211,6 @@ public class CommonEditor { pane.repaint(); } - - public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); - - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); - } - public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { boolean immunity = condition.isImmunity(); boolean clear = condition.isClear(); @@ -367,4 +228,164 @@ public class CommonEditor { } } + + public static class DeathEffectPane { + Common.DeathEffect hitEffect; + CollapsiblePanel hitEffectPane; + JSpinner hitEffectHPMin; + JSpinner hitEffectHPMax; + JSpinner hitEffectAPMin; + JSpinner hitEffectAPMax; + NPCEditor.SourceTimedConditionsListModel hitSourceConditionsModel; + JList hitSourceConditionsList; + Common.TimedActorConditionEffect selectedHitEffectSourceCondition; + + Editor.MyComboBox hitSourceConditionBox; + JSpinner hitSourceConditionChance; + JRadioButton hitSourceConditionClear; + JRadioButton hitSourceConditionApply; + JRadioButton hitSourceConditionImmunity; + JSpinner hitSourceConditionMagnitude; + JRadioButton hitSourceConditionTimed; + JRadioButton hitSourceConditionForever; + JSpinner hitSourceConditionDuration; + + /* + * create a new DeatchEffectPane with the selections (probably passed in from last time) + */ + public DeathEffectPane(Common.TimedActorConditionEffect selectedHitEffectSourceCondition) { + this.selectedHitEffectSourceCondition = selectedHitEffectSourceCondition; + } + + void createDeathEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor) { + hitEffectPane = new CollapsiblePanel("Effect on every hit: "); + hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); + if (npc.hit_effect == null) { + hitEffect = new Common.HitEffect(); + } else { + hitEffect = npc.hit_effect; + } + hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); + hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); + hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); + hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); + + String titleSource = "Actor Conditions applied to the source: "; + hitSourceConditionsModel = new NPCEditor.SourceTimedConditionsListModel(hitEffect); + CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetSource = (value)-> selectedHitEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetSource = ()-> selectedHitEffectSourceCondition ; + BasicLambda selectedResetSource = ()-> selectedHitEffectSourceCondition = null; + BasicLambdaWithArg updatePaneSource =(editorPane) -> updateDeathEffectSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener, editor); + + var resultSource = UiUtils.getCollapsibleItemList(listener, + hitSourceConditionsModel, + selectedResetSource, + selectedSetSource, + selectedGetSource, + (x) -> {}, + updatePaneSource, + npc.writable, + Common.TimedActorConditionEffect::new, + cellRendererSource, + titleSource, + (x) -> null); + hitSourceConditionsList = resultSource.list; + CollapsiblePanel hitSourceConditionsPane = resultSource.collapsiblePanel; + if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { + hitSourceConditionsPane.collapse(); + } + hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + } + + public void updateDeathEffectSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { + pane.removeAll(); + if (hitSourceConditionBox != null) { + e.removeElementListener(hitSourceConditionBox); + } + + boolean writable = e.target.writable; + Project proj = e.target.getProject(); + + hitSourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + hitSourceConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + hitSourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(hitSourceConditionClear, JideBoxLayout.FIX); + hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(hitSourceConditionApply, JideBoxLayout.FIX); + hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(hitSourceConditionApply); + radioEffectGroup.add(hitSourceConditionClear); + radioEffectGroup.add(hitSourceConditionImmunity); + + hitSourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); + hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitSourceConditionForever = new JRadioButton("Forever"); + pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(hitSourceConditionTimed); + radioDurationGroup.add(hitSourceConditionForever); + + updateDeathEffectSourceTimedConditionWidgets(condition); + + hitSourceConditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + } + }); + hitSourceConditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + } + }); + hitSourceConditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + } + }); + + hitSourceConditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + } + }); + hitSourceConditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + } + }); + pane.revalidate(); + pane.repaint(); + } + + + public void updateDeathEffectSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); + + hitSourceConditionClear.setSelected(clear); + hitSourceConditionApply.setSelected(!clear && !immunity); + hitSourceConditionMagnitude.setEnabled(!clear && !immunity); + hitSourceConditionImmunity.setSelected(immunity); + + hitSourceConditionTimed.setSelected(!forever); + hitSourceConditionTimed.setEnabled(!clear); + hitSourceConditionDuration.setEnabled(!clear && !forever); + hitSourceConditionForever.setSelected(forever); + hitSourceConditionForever.setEnabled(!clear); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index a216516..98a44f5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -397,7 +397,7 @@ public class NPCEditor extends JSONElementEditor { } public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - hitEffectPane.updateHitSourceTimedConditionWidgets(condition); + hitEffectPane.updateDeathEffectSourceTimedConditionWidgets(condition); } From 7f0b55a71ce2acbb5fb20a8d864fe3c51e2edafa Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 18:57:59 +0200 Subject: [PATCH 59/94] add possibility for hint where the effect is applied to --- .../ui/gamedataeditors/CommonEditor.java | 40 +++++++++++-------- .../ui/gamedataeditors/NPCEditor.java | 2 +- 2 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 8e68f07..86c0c25 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -53,6 +53,7 @@ public class CommonEditor { return c; } } + public static class ConditionsCellRenderer extends DefaultListCellRenderer { private static final long serialVersionUID = 7987880146189575234L; @@ -109,15 +110,15 @@ public class CommonEditor { this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; } - void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor) { - createDeathEffectPaneContent(npc, listener, editor); + void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint) { + createDeathEffectPaneContent(npc, listener, editor, applyToHint); String titleTarget = "Actor Conditions applied to the target: "; hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(hitEffect); CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetTarget = (value)-> selectedHitEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetTarget = ()-> selectedHitEffectTargetCondition ; - BasicLambda selectedResetTarget = ()-> selectedHitEffectTargetCondition = null; + BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; + BasicLambda selectedResetTarget = () -> selectedHitEffectTargetCondition = null; BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener, editor); var resultTarget = UiUtils.getCollapsibleItemList(listener, @@ -125,7 +126,8 @@ public class CommonEditor { selectedResetTarget, selectedSetTarget, selectedGetTarget, - (x) -> {}, + (x) -> { + }, updatePaneTarget, npc.writable, Common.TimedActorConditionEffect::new, @@ -257,7 +259,12 @@ public class CommonEditor { this.selectedHitEffectSourceCondition = selectedHitEffectSourceCondition; } - void createDeathEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor) { + void createDeathEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint) { + if (applyToHint == null || applyToHint == "") { + applyToHint = ""; + } else { + applyToHint = " (%s)".formatted(applyToHint); + } hitEffectPane = new CollapsiblePanel("Effect on every hit: "); hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); if (npc.hit_effect == null) { @@ -265,25 +272,26 @@ public class CommonEditor { } else { hitEffect = npc.hit_effect; } - hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, npc.writable, listener); - hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, npc.writable, listener); - hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, npc.writable, listener); - hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, npc.writable, listener); + hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min%s: ".formatted(applyToHint), hitEffect.hp_boost_min, true, npc.writable, listener); + hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max%s: ".formatted(applyToHint), hitEffect.hp_boost_max, true, npc.writable, listener); + hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min%s: ".formatted(applyToHint), hitEffect.ap_boost_min, true, npc.writable, listener); + hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max%s: ".formatted(applyToHint), hitEffect.ap_boost_max, true, npc.writable, listener); String titleSource = "Actor Conditions applied to the source: "; hitSourceConditionsModel = new NPCEditor.SourceTimedConditionsListModel(hitEffect); CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetSource = (value)-> selectedHitEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetSource = ()-> selectedHitEffectSourceCondition ; - BasicLambda selectedResetSource = ()-> selectedHitEffectSourceCondition = null; - BasicLambdaWithArg updatePaneSource =(editorPane) -> updateDeathEffectSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener, editor); + BasicLambdaWithArg selectedSetSource = (value) -> selectedHitEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetSource = () -> selectedHitEffectSourceCondition; + BasicLambda selectedResetSource = () -> selectedHitEffectSourceCondition = null; + BasicLambdaWithArg updatePaneSource = (editorPane) -> updateDeathEffectSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener, editor); var resultSource = UiUtils.getCollapsibleItemList(listener, hitSourceConditionsModel, selectedResetSource, selectedSetSource, selectedGetSource, - (x) -> {}, + (x) -> { + }, updatePaneSource, npc.writable, Common.TimedActorConditionEffect::new, diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 98a44f5..18cbf2b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -207,7 +207,7 @@ public class NPCEditor extends JSONElementEditor { dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); hitEffectPane = new CommonEditor.HitEffectPane(this.hitEffectPane.selectedHitEffectSourceCondition, this.hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.createHitEffectPaneContent(npc, listener, this); + hitEffectPane.createHitEffectPaneContent(npc, listener, this, null); combatTraitPane.add(hitEffectPane.hitEffectPane, JideBoxLayout.FIX); hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); From 5031fa3c729c9ecc68b1c31799064e3ebaa78a08 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 19:58:22 +0200 Subject: [PATCH 60/94] rename some stuff --- .../ui/gamedataeditors/CommonEditor.java | 196 ++++++++--------- .../ui/gamedataeditors/NPCEditor.java | 203 ++++++------------ 2 files changed, 163 insertions(+), 236 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 86c0c25..ff37862 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -15,6 +15,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.util.function.Supplier; import static com.gpl.rpg.atcontentstudio.ui.Editor.addIntegerField; @@ -81,14 +82,9 @@ public class CommonEditor { } public static class HitEffectPane extends DeathEffectPane { - Common.HitEffect hitEffect; - CollapsiblePanel hitEffectPane; - JSpinner hitEffectHPMin; - JSpinner hitEffectHPMax; - JSpinner hitEffectAPMin; - JSpinner hitEffectAPMax; + /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! + Common.HitEffect effect; NPCEditor.TargetTimedConditionsListModel hitTargetConditionsListModel; - JList hitSourceConditionsList; JList hitTargetConditionsList; Common.TimedActorConditionEffect selectedHitEffectTargetCondition; @@ -110,11 +106,12 @@ public class CommonEditor { this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; } - void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint) { - createDeathEffectPaneContent(npc, listener, editor, applyToHint); + void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint, boolean writable, Common.HitEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModel1) { + effect = e; + createDeathEffectPaneContent(npc, listener, editor, applyToHint, writable, e, sourceConditionsModel1, Common.TimedActorConditionEffect::new); String titleTarget = "Actor Conditions applied to the target: "; - hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(hitEffect); + hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(effect); CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; @@ -129,7 +126,7 @@ public class CommonEditor { (x) -> { }, updatePaneTarget, - npc.writable, + writable, Common.TimedActorConditionEffect::new, cellRendererTarget, titleTarget, @@ -139,7 +136,7 @@ public class CommonEditor { if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { hitTargetConditionsPane.collapse(); } - hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); + effectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); } public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { @@ -231,147 +228,144 @@ public class CommonEditor { } } - public static class DeathEffectPane { - Common.DeathEffect hitEffect; - CollapsiblePanel hitEffectPane; - JSpinner hitEffectHPMin; - JSpinner hitEffectHPMax; - JSpinner hitEffectAPMin; - JSpinner hitEffectAPMax; - NPCEditor.SourceTimedConditionsListModel hitSourceConditionsModel; - JList hitSourceConditionsList; - Common.TimedActorConditionEffect selectedHitEffectSourceCondition; + public static class DeathEffectPane> { + Common.DeathEffect effect; + CollapsiblePanel effectPane; + JSpinner effectHPMin; + JSpinner effectHPMax; + JSpinner effectAPMin; + JSpinner effectAPMax; + M sourceConditionsModel; + JList sourceConditionsList; + E selectedEffectSourceCondition; - Editor.MyComboBox hitSourceConditionBox; - JSpinner hitSourceConditionChance; - JRadioButton hitSourceConditionClear; - JRadioButton hitSourceConditionApply; - JRadioButton hitSourceConditionImmunity; - JSpinner hitSourceConditionMagnitude; - JRadioButton hitSourceConditionTimed; - JRadioButton hitSourceConditionForever; - JSpinner hitSourceConditionDuration; + Editor.MyComboBox sourceConditionBox; + JSpinner sourceConditionChance; + JRadioButton sourceConditionClear; + JRadioButton sourceConditionApply; + JRadioButton sourceConditionImmunity; + JSpinner sourceConditionMagnitude; + JRadioButton sourceConditionTimed; + JRadioButton sourceConditionForever; + JSpinner sourceConditionDuration; /* * create a new DeatchEffectPane with the selections (probably passed in from last time) */ - public DeathEffectPane(Common.TimedActorConditionEffect selectedHitEffectSourceCondition) { - this.selectedHitEffectSourceCondition = selectedHitEffectSourceCondition; + public DeathEffectPane(E selectedEffectSourceCondition) { + this.selectedEffectSourceCondition = selectedEffectSourceCondition; } - void createDeathEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint) { + void createDeathEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint, boolean writable, Common.DeathEffect e, M sourceConditionsModel, Supplier sourceNewSupplier) { if (applyToHint == null || applyToHint == "") { applyToHint = ""; } else { applyToHint = " (%s)".formatted(applyToHint); } - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); - if (npc.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = npc.hit_effect; - } - hitEffectHPMin = addIntegerField(hitEffectPane, "HP bonus min%s: ".formatted(applyToHint), hitEffect.hp_boost_min, true, npc.writable, listener); - hitEffectHPMax = addIntegerField(hitEffectPane, "HP bonus max%s: ".formatted(applyToHint), hitEffect.hp_boost_max, true, npc.writable, listener); - hitEffectAPMin = addIntegerField(hitEffectPane, "AP bonus min%s: ".formatted(applyToHint), hitEffect.ap_boost_min, true, npc.writable, listener); - hitEffectAPMax = addIntegerField(hitEffectPane, "AP bonus max%s: ".formatted(applyToHint), hitEffect.ap_boost_max, true, npc.writable, listener); + effectPane = new CollapsiblePanel("Effect on every hit: "); + effectPane.setLayout(new JideBoxLayout(effectPane, JideBoxLayout.PAGE_AXIS)); + + effect = e; + effectHPMin = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToHint), effect.hp_boost_min, true, writable, listener); + effectHPMax = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToHint), effect.hp_boost_max, true, writable, listener); + effectAPMin = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToHint), effect.ap_boost_min, true, writable, listener); + effectAPMax = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToHint), effect.ap_boost_max, true, writable, listener); String titleSource = "Actor Conditions applied to the source: "; - hitSourceConditionsModel = new NPCEditor.SourceTimedConditionsListModel(hitEffect); + this.sourceConditionsModel = sourceConditionsModel; CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetSource = (value) -> selectedHitEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetSource = () -> selectedHitEffectSourceCondition; - BasicLambda selectedResetSource = () -> selectedHitEffectSourceCondition = null; - BasicLambdaWithArg updatePaneSource = (editorPane) -> updateDeathEffectSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener, editor); + BasicLambdaWithArg selectedSetSource = (value) -> selectedEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetSource = () -> selectedEffectSourceCondition; + BasicLambda selectedResetSource = () -> selectedEffectSourceCondition = null; + BasicLambdaWithArg updatePaneSource = (editorPane) -> updateEffectSourceTimedConditionEditorPane(editorPane, selectedEffectSourceCondition, listener, editor); var resultSource = UiUtils.getCollapsibleItemList(listener, - hitSourceConditionsModel, + this.sourceConditionsModel, selectedResetSource, selectedSetSource, selectedGetSource, (x) -> { }, updatePaneSource, - npc.writable, - Common.TimedActorConditionEffect::new, + writable, + sourceNewSupplier, cellRendererSource, titleSource, (x) -> null); - hitSourceConditionsList = resultSource.list; - CollapsiblePanel hitSourceConditionsPane = resultSource.collapsiblePanel; - if (npc.hit_effect == null || npc.hit_effect.conditions_source == null || npc.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); + sourceConditionsList = resultSource.list; + CollapsiblePanel sourceConditionsPane = resultSource.collapsiblePanel; + if (effect == null || effect.conditions_source == null || effect.conditions_source.isEmpty()) { + sourceConditionsPane.collapse(); } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); + effectPane.add(sourceConditionsPane, JideBoxLayout.FIX); } - public void updateDeathEffectSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { + public void updateEffectSourceTimedConditionEditorPane(JPanel pane, E condition, final FieldUpdateListener listener, Editor e) { pane.removeAll(); - if (hitSourceConditionBox != null) { - e.removeElementListener(hitSourceConditionBox); + if (sourceConditionBox != null) { + e.removeElementListener(sourceConditionBox); } boolean writable = e.target.writable; Project proj = e.target.getProject(); - hitSourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + sourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); + sourceConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); + sourceConditionClear = new JRadioButton("Clear active condition"); + pane.add(sourceConditionClear, JideBoxLayout.FIX); + sourceConditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(sourceConditionApply, JideBoxLayout.FIX); + sourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + sourceConditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(sourceConditionImmunity, JideBoxLayout.FIX); ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); + radioEffectGroup.add(sourceConditionApply); + radioEffectGroup.add(sourceConditionClear); + radioEffectGroup.add(sourceConditionImmunity); - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); + sourceConditionTimed = new JRadioButton("For a number of rounds"); + pane.add(sourceConditionTimed, JideBoxLayout.FIX); + sourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + sourceConditionForever = new JRadioButton("Forever"); + pane.add(sourceConditionForever, JideBoxLayout.FIX); ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); + radioDurationGroup.add(sourceConditionTimed); + radioDurationGroup.add(sourceConditionForever); - updateDeathEffectSourceTimedConditionWidgets(condition); + updateEffectSourceTimedConditionWidgets(condition); - hitSourceConditionClear.addActionListener(new ActionListener() { + sourceConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, new Boolean(hitSourceConditionClear.isSelected())); + listener.valueChanged(sourceConditionClear, new Boolean(sourceConditionClear.isSelected())); } }); - hitSourceConditionApply.addActionListener(new ActionListener() { + sourceConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, new Boolean(hitSourceConditionApply.isSelected())); + listener.valueChanged(sourceConditionApply, new Boolean(sourceConditionApply.isSelected())); } }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { + sourceConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, new Boolean(hitSourceConditionImmunity.isSelected())); + listener.valueChanged(sourceConditionImmunity, new Boolean(sourceConditionImmunity.isSelected())); } }); - hitSourceConditionTimed.addActionListener(new ActionListener() { + sourceConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, new Boolean(hitSourceConditionTimed.isSelected())); + listener.valueChanged(sourceConditionTimed, new Boolean(sourceConditionTimed.isSelected())); } }); - hitSourceConditionForever.addActionListener(new ActionListener() { + sourceConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, new Boolean(hitSourceConditionForever.isSelected())); + listener.valueChanged(sourceConditionForever, new Boolean(sourceConditionForever.isSelected())); } }); pane.revalidate(); @@ -379,21 +373,21 @@ public class CommonEditor { } - public void updateDeathEffectSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { + public void updateEffectSourceTimedConditionWidgets(E condition) { boolean immunity = condition.isImmunity(); boolean clear = condition.isClear(); boolean forever = condition.isInfinite(); - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); + sourceConditionClear.setSelected(clear); + sourceConditionApply.setSelected(!clear && !immunity); + sourceConditionMagnitude.setEnabled(!clear && !immunity); + sourceConditionImmunity.setSelected(immunity); - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); + sourceConditionTimed.setSelected(!forever); + sourceConditionTimed.setEnabled(!clear); + sourceConditionDuration.setEnabled(!clear && !forever); + sourceConditionForever.setSelected(forever); + sourceConditionForever.setEnabled(!clear); } } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 18cbf2b..71530f1 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -206,9 +206,15 @@ public class NPCEditor extends JSONElementEditor { blockChance = addIntegerField(combatTraitPane, "Block chance: ", npc.block_chance, false, npc.writable, listener); dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); - hitEffectPane = new CommonEditor.HitEffectPane(this.hitEffectPane.selectedHitEffectSourceCondition, this.hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.createHitEffectPaneContent(npc, listener, this, null); - combatTraitPane.add(hitEffectPane.hitEffectPane, JideBoxLayout.FIX); + Common.HitEffect hitEffect; + if (npc.hit_effect == null) { + hitEffect = new Common.HitEffect(); + } else { + hitEffect = npc.hit_effect; + } + hitEffectPane = new CommonEditor.HitEffectPane(this.hitEffectPane.selectedEffectSourceCondition, this.hitEffectPane.selectedHitEffectTargetCondition); + hitEffectPane.createHitEffectPaneContent(npc, listener, this, null, npc.writable, hitEffect, new SourceTimedConditionsListModel(hitEffect)); + combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); @@ -322,82 +328,9 @@ public class NPCEditor extends JSONElementEditor { pane.add(combatTraitPane, JideBoxLayout.FIX); } - - - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitEffectPane.hitSourceConditionBox != null) { - removeElementListener(hitEffectPane.hitSourceConditionBox); - } - - boolean writable = ((NPC) target).writable; - Project proj = ((NPC) target).getProject(); - - hitEffectPane.hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitEffectPane.hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitEffectPane.hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitEffectPane.hitSourceConditionClear, JideBoxLayout.FIX); - hitEffectPane.hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitEffectPane.hitSourceConditionApply, JideBoxLayout.FIX); - hitEffectPane.hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitEffectPane.hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitEffectPane.hitSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitEffectPane.hitSourceConditionApply); - radioEffectGroup.add(hitEffectPane.hitSourceConditionClear); - radioEffectGroup.add(hitEffectPane.hitSourceConditionImmunity); - - hitEffectPane.hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitEffectPane.hitSourceConditionTimed, JideBoxLayout.FIX); - hitEffectPane.hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitEffectPane.hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitEffectPane.hitSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitEffectPane.hitSourceConditionTimed); - radioDurationGroup.add(hitEffectPane.hitSourceConditionForever); - - updateHitSourceTimedConditionWidgets(condition); - - hitEffectPane.hitSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitSourceConditionClear, new Boolean(hitEffectPane.hitSourceConditionClear.isSelected())); - } - }); - hitEffectPane.hitSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitSourceConditionApply, new Boolean(hitEffectPane.hitSourceConditionApply.isSelected())); - } - }); - hitEffectPane.hitSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitSourceConditionImmunity, new Boolean(hitEffectPane.hitSourceConditionImmunity.isSelected())); - } - }); - - hitEffectPane.hitSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitSourceConditionTimed, new Boolean(hitEffectPane.hitSourceConditionTimed.isSelected())); - } - }); - hitEffectPane.hitSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitEffectPane.hitSourceConditionForever, new Boolean(hitEffectPane.hitSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - hitEffectPane.updateDeathEffectSourceTimedConditionWidgets(condition); + hitEffectPane.updateEffectSourceTimedConditionWidgets(condition); } @@ -832,80 +765,80 @@ public class NPCEditor extends JSONElementEditor { npc.block_chance = (Integer) value; } else if (source == dmgRes) { npc.damage_resistance = (Integer) value; - } else if (source == hitEffectPane.hitEffectHPMin) { - hitEffectPane.hitEffect.hp_boost_min = (Integer) value; + } else if (source == hitEffectPane.effectHPMin) { + hitEffectPane.effect.hp_boost_min = (Integer) value; updateHit = true; - } else if (source == hitEffectPane.hitEffectHPMax) { - hitEffectPane.hitEffect.hp_boost_max = (Integer) value; + } else if (source == hitEffectPane.effectHPMax) { + hitEffectPane.effect.hp_boost_max = (Integer) value; updateHit = true; - } else if (source == hitEffectPane.hitEffectAPMin) { - hitEffectPane.hitEffect.ap_boost_min = (Integer) value; + } else if (source == hitEffectPane.effectAPMin) { + hitEffectPane.effect.ap_boost_min = (Integer) value; updateHit = true; - } else if (source == hitEffectPane.hitEffectAPMax) { - hitEffectPane.hitEffect.ap_boost_max = (Integer) value; + } else if (source == hitEffectPane.effectAPMax) { + hitEffectPane.effect.ap_boost_max = (Integer) value; updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionsList) { + } else if (source == hitEffectPane.sourceConditionsList) { updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionBox) { - if (hitEffectPane.selectedHitEffectSourceCondition.condition != null) { - hitEffectPane.selectedHitEffectSourceCondition.condition.removeBacklink(npc); + } else if (source == hitEffectPane.sourceConditionBox) { + if (hitEffectPane.selectedEffectSourceCondition.condition != null) { + hitEffectPane.selectedEffectSourceCondition.condition.removeBacklink(npc); } - hitEffectPane.selectedHitEffectSourceCondition.condition = (ActorCondition) value; - if (hitEffectPane.selectedHitEffectSourceCondition.condition != null) { - hitEffectPane.selectedHitEffectSourceCondition.condition.addBacklink(npc); - hitEffectPane.selectedHitEffectSourceCondition.condition_id = hitEffectPane.selectedHitEffectSourceCondition.condition.id; + hitEffectPane.selectedEffectSourceCondition.condition = (ActorCondition) value; + if (hitEffectPane.selectedEffectSourceCondition.condition != null) { + hitEffectPane.selectedEffectSourceCondition.condition.addBacklink(npc); + hitEffectPane.selectedEffectSourceCondition.condition_id = hitEffectPane.selectedEffectSourceCondition.condition.id; } else { - hitEffectPane.selectedHitEffectSourceCondition.condition_id = null; + hitEffectPane.selectedEffectSourceCondition.condition_id = null; } - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); - } else if (source == hitEffectPane.hitSourceConditionClear && (Boolean) value) { - hitEffectPane.selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - hitEffectPane.selectedHitEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); + } else if (source == hitEffectPane.sourceConditionClear && (Boolean) value) { + hitEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + hitEffectPane.selectedEffectSourceCondition.duration = null; + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionApply && (Boolean) value) { - hitEffectPane.selectedHitEffectSourceCondition.magnitude = (Integer) hitEffectPane.hitSourceConditionMagnitude.getValue(); - hitEffectPane.selectedHitEffectSourceCondition.duration = hitEffectPane.hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitSourceConditionDuration.getValue(); - if (hitEffectPane.selectedHitEffectSourceCondition.duration == null || hitEffectPane.selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedHitEffectSourceCondition.duration = 1; + } else if (source == hitEffectPane.sourceConditionApply && (Boolean) value) { + hitEffectPane.selectedEffectSourceCondition.magnitude = (Integer) hitEffectPane.sourceConditionMagnitude.getValue(); + hitEffectPane.selectedEffectSourceCondition.duration = hitEffectPane.sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.sourceConditionDuration.getValue(); + if (hitEffectPane.selectedEffectSourceCondition.duration == null || hitEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedEffectSourceCondition.duration = 1; } - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionImmunity && (Boolean) value) { - hitEffectPane.selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - hitEffectPane.selectedHitEffectSourceCondition.duration = hitEffectPane.hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitSourceConditionDuration.getValue(); - if (hitEffectPane.selectedHitEffectSourceCondition.duration == null || hitEffectPane.selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedHitEffectSourceCondition.duration = 1; + } else if (source == hitEffectPane.sourceConditionImmunity && (Boolean) value) { + hitEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + hitEffectPane.selectedEffectSourceCondition.duration = hitEffectPane.sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.sourceConditionDuration.getValue(); + if (hitEffectPane.selectedEffectSourceCondition.duration == null || hitEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedEffectSourceCondition.duration = 1; } - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionMagnitude) { - hitEffectPane.selectedHitEffectSourceCondition.magnitude = (Integer) value; - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.sourceConditionMagnitude) { + hitEffectPane.selectedEffectSourceCondition.magnitude = (Integer) value; + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionTimed && (Boolean) value) { - hitEffectPane.selectedHitEffectSourceCondition.duration = (Integer) hitEffectPane.hitSourceConditionDuration.getValue(); - if (hitEffectPane.selectedHitEffectSourceCondition.duration == null || hitEffectPane.selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedHitEffectSourceCondition.duration = 1; + } else if (source == hitEffectPane.sourceConditionTimed && (Boolean) value) { + hitEffectPane.selectedEffectSourceCondition.duration = (Integer) hitEffectPane.sourceConditionDuration.getValue(); + if (hitEffectPane.selectedEffectSourceCondition.duration == null || hitEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + hitEffectPane.selectedEffectSourceCondition.duration = 1; } - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionForever && (Boolean) value) { - hitEffectPane.selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedHitEffectSourceCondition); - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.sourceConditionForever && (Boolean) value) { + hitEffectPane.selectedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionDuration) { - hitEffectPane.selectedHitEffectSourceCondition.duration = (Integer) value; - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.sourceConditionDuration) { + hitEffectPane.selectedEffectSourceCondition.duration = (Integer) value; + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); updateHit = true; - } else if (source == hitEffectPane.hitSourceConditionChance) { - hitEffectPane.selectedHitEffectSourceCondition.chance = (Double) value; - hitEffectPane.hitSourceConditionsModel.itemChanged(hitEffectPane.selectedHitEffectSourceCondition); + } else if (source == hitEffectPane.sourceConditionChance) { + hitEffectPane.selectedEffectSourceCondition.chance = (Double) value; + hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); } else if (source == hitEffectPane.hitTargetConditionsList) { updateHit = true; } else if (source == hitEffectPane.hitTargetConditionBox) { @@ -1173,10 +1106,10 @@ public class NPCEditor extends JSONElementEditor { } if (updateHit) { - if (isNull(hitEffectPane.hitEffect)) { + if (isNull(hitEffectPane.effect)) { npc.hit_effect = null; } else { - npc.hit_effect = hitEffectPane.hitEffect; + npc.hit_effect = hitEffectPane.effect; } } if (updateHitReceived) { From 572c658b437aae049394603a0aa5585bde223332 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 20:41:40 +0200 Subject: [PATCH 61/94] change some constructor stuff for it and switch the deathEffectPane to the new DeathEffectPane class --- .../ui/gamedataeditors/CommonEditor.java | 36 ++- .../ui/gamedataeditors/NPCEditor.java | 275 +++++------------- 2 files changed, 96 insertions(+), 215 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index ff37862..4f55493 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -3,7 +3,6 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.Common; -import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.utils.BasicLambda; import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; @@ -101,14 +100,14 @@ public class CommonEditor { /* * create a new HitEffectPane with the selections (probably passed in from last time) */ - public HitEffectPane(Common.TimedActorConditionEffect selectedHitEffectSourceCondition, Common.TimedActorConditionEffect selectedHitEffectTargetCondition) { - super(selectedHitEffectSourceCondition); + public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint) { + super(title, sourceNewSupplier, editor, applyToHint); this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; } - void createHitEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint, boolean writable, Common.HitEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModel1) { + void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.HitEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModelInput) { effect = e; - createDeathEffectPaneContent(npc, listener, editor, applyToHint, writable, e, sourceConditionsModel1, Common.TimedActorConditionEffect::new); + createDeathEffectPaneContent( listener, writable, e, sourceConditionsModelInput); String titleTarget = "Actor Conditions applied to the target: "; hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(effect); @@ -116,7 +115,7 @@ public class CommonEditor { BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; BasicLambda selectedResetTarget = () -> selectedHitEffectTargetCondition = null; - BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener, editor); + BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener, this.editor); var resultTarget = UiUtils.getCollapsibleItemList(listener, hitTargetConditionsListModel, @@ -127,13 +126,13 @@ public class CommonEditor { }, updatePaneTarget, writable, - Common.TimedActorConditionEffect::new, + this.conditionSupplier, cellRendererTarget, titleTarget, (x) -> null); hitTargetConditionsList = resultTarget.list; CollapsiblePanel hitTargetConditionsPane = resultTarget.collapsiblePanel; - if (npc.hit_effect == null || npc.hit_effect.conditions_target == null || npc.hit_effect.conditions_target.isEmpty()) { + if (effect == null || effect.conditions_target == null || effect.conditions_target.isEmpty()) { hitTargetConditionsPane.collapse(); } effectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); @@ -229,6 +228,12 @@ public class CommonEditor { } public static class DeathEffectPane> { + protected Supplier conditionSupplier; + protected String title; + protected Editor editor; + protected String applyToHint; + + Common.DeathEffect effect; CollapsiblePanel effectPane; JSpinner effectHPMin; @@ -252,17 +257,20 @@ public class CommonEditor { /* * create a new DeatchEffectPane with the selections (probably passed in from last time) */ - public DeathEffectPane(E selectedEffectSourceCondition) { - this.selectedEffectSourceCondition = selectedEffectSourceCondition; + public DeathEffectPane(String title, Supplier conditionSupplier, Editor editor, String applyToHint) { + this.title = title; + this.conditionSupplier = conditionSupplier; + this.editor = editor; + this.applyToHint = applyToHint; } - void createDeathEffectPaneContent(NPC npc, FieldUpdateListener listener, Editor editor, String applyToHint, boolean writable, Common.DeathEffect e, M sourceConditionsModel, Supplier sourceNewSupplier) { + void createDeathEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.DeathEffect e, M sourceConditionsModel) { if (applyToHint == null || applyToHint == "") { applyToHint = ""; } else { applyToHint = " (%s)".formatted(applyToHint); } - effectPane = new CollapsiblePanel("Effect on every hit: "); + effectPane = new CollapsiblePanel(title); effectPane.setLayout(new JideBoxLayout(effectPane, JideBoxLayout.PAGE_AXIS)); effect = e; @@ -271,7 +279,7 @@ public class CommonEditor { effectAPMin = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToHint), effect.ap_boost_min, true, writable, listener); effectAPMax = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToHint), effect.ap_boost_max, true, writable, listener); - String titleSource = "Actor Conditions applied to the source: "; + String titleSource = "Actor Conditions applied to the source%s: ".formatted(applyToHint); this.sourceConditionsModel = sourceConditionsModel; CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetSource = (value) -> selectedEffectSourceCondition = value; @@ -288,7 +296,7 @@ public class CommonEditor { }, updatePaneSource, writable, - sourceNewSupplier, + conditionSupplier, cellRendererSource, titleSource, (x) -> null); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 71530f1..1670d0a 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -31,7 +31,6 @@ public class NPCEditor extends JSONElementEditor { private Common.TimedActorConditionEffect selectedHitReceivedEffectSourceCondition; private Common.TimedActorConditionEffect selectedHitReceivedEffectTargetCondition; - private Common.TimedActorConditionEffect selectedDeathEffectSourceCondition; private JButton npcIcon; private JTextField idField; @@ -100,25 +99,7 @@ public class NPCEditor extends JSONElementEditor { private JRadioButton hitReceivedTargetConditionForever; private JSpinner hitReceivedTargetConditionDuration; - private Common.DeathEffect deathEffect; - private CollapsiblePanel deathEffectPane; - private JSpinner deathEffectHPMin; - private JSpinner deathEffectHPMax; - private JSpinner deathEffectAPMin; - private JSpinner deathEffectAPMax; - - private SourceTimedConditionsListModel deathSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList deathSourceConditionsList; - private MyComboBox deathSourceConditionBox; - private JSpinner deathSourceConditionChance; - private JRadioButton deathSourceConditionClear; - private JRadioButton deathSourceConditionApply; - private JRadioButton deathSourceConditionImmunity; - private JSpinner deathSourceConditionMagnitude; - private JRadioButton deathSourceConditionTimed; - private JRadioButton deathSourceConditionForever; - private JSpinner deathSourceConditionDuration; + private CommonEditor.DeathEffectPane deathEffectPane; private JPanel dialogueGraphPane; private DialogueGraphView dialogueGraphView; @@ -212,8 +193,12 @@ public class NPCEditor extends JSONElementEditor { } else { hitEffect = npc.hit_effect; } - hitEffectPane = new CommonEditor.HitEffectPane(this.hitEffectPane.selectedEffectSourceCondition, this.hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.createHitEffectPaneContent(npc, listener, this, null, npc.writable, hitEffect, new SourceTimedConditionsListModel(hitEffect)); + if (hitEffectPane == null) + hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, "test"); + hitEffectPane.createHitEffectPaneContent(listener, + npc.writable, + hitEffect, + new SourceTimedConditionsListModel(hitEffect)); combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); @@ -284,46 +269,20 @@ public class NPCEditor extends JSONElementEditor { } combatTraitPane.add(hitReceivedEffectPane, JideBoxLayout.FIX); - deathEffectPane = new CollapsiblePanel("Effect when killed: "); - deathEffectPane.setLayout(new JideBoxLayout(deathEffectPane, JideBoxLayout.PAGE_AXIS)); + Common.DeathEffect deathEffect; if (npc.death_effect == null) { deathEffect = new Common.DeathEffect(); } else { deathEffect = npc.death_effect; } - deathEffectHPMin = addIntegerField(deathEffectPane, "Killer HP bonus min: ", deathEffect.hp_boost_min, true, npc.writable, listener); - deathEffectHPMax = addIntegerField(deathEffectPane, "Killer HP bonus max: ", deathEffect.hp_boost_max, true, npc.writable, listener); - deathEffectAPMin = addIntegerField(deathEffectPane, "Killer AP bonus min: ", deathEffect.ap_boost_min, true, npc.writable, listener); - deathEffectAPMax = addIntegerField(deathEffectPane, "Killer AP bonus max: ", deathEffect.ap_boost_max, true, npc.writable, listener); - - String titleDeathSource = "Actor Conditions applied to the killer: "; - deathSourceConditionsListModel = new SourceTimedConditionsListModel(deathEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererDeathSource = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetDeathSource = (value)->selectedDeathEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetDeathSource = ()->selectedDeathEffectSourceCondition ; - BasicLambda selectedResetDeathSource = ()->selectedDeathEffectSourceCondition = null; - BasicLambdaWithArg updatePaneDeathSource = (editorPane) -> updateDeathSourceTimedConditionEditorPane(editorPane, selectedDeathEffectSourceCondition, listener); - var resultDeathSource = UiUtils.getCollapsibleItemList(listener, - deathSourceConditionsListModel, - selectedResetDeathSource, - selectedSetDeathSource, - selectedGetDeathSource, - (x) -> {}, - updatePaneDeathSource, + if (deathEffectPane == null) + deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", Common.TimedActorConditionEffect::new, this, "Killer"); + deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, - Common.TimedActorConditionEffect::new, - cellRendererDeathSource, - titleDeathSource, - (x) -> null); - deathSourceConditionsList = resultDeathSource.list; - CollapsiblePanel deathSourceConditionsPane = resultDeathSource.collapsiblePanel; - if (npc.death_effect == null || npc.death_effect.conditions_source == null || npc.death_effect.conditions_source.isEmpty()) { - deathSourceConditionsPane.collapse(); - } - deathEffectPane.add(deathSourceConditionsPane, JideBoxLayout.FIX); - - combatTraitPane.add(deathEffectPane, JideBoxLayout.FIX); - + deathEffect, + new SourceTimedConditionsListModel(deathEffect) + ); + combatTraitPane.add(deathEffectPane.effectPane, JideBoxLayout.FIX); pane.add(combatTraitPane, JideBoxLayout.FIX); } @@ -518,94 +477,8 @@ public class NPCEditor extends JSONElementEditor { hitReceivedTargetConditionForever.setEnabled(!clear); } - public void updateDeathSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (deathSourceConditionBox != null) { - removeElementListener(deathSourceConditionBox); - } - - boolean writable = ((NPC) target).writable; - Project proj = ((NPC) target).getProject(); - - deathSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - deathSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - deathSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(deathSourceConditionClear, JideBoxLayout.FIX); - deathSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(deathSourceConditionApply, JideBoxLayout.FIX); - deathSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - deathSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(deathSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(deathSourceConditionApply); - radioEffectGroup.add(deathSourceConditionClear); - radioEffectGroup.add(deathSourceConditionImmunity); - - deathSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(deathSourceConditionTimed, JideBoxLayout.FIX); - deathSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - deathSourceConditionForever = new JRadioButton("Forever"); - pane.add(deathSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(deathSourceConditionTimed); - radioDurationGroup.add(deathSourceConditionForever); - - updateDeathSourceTimedConditionWidgets(condition); - - deathSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionClear, new Boolean(deathSourceConditionClear.isSelected())); - } - }); - deathSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionApply, new Boolean(deathSourceConditionApply.isSelected())); - } - }); - deathSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionImmunity, new Boolean(deathSourceConditionImmunity.isSelected())); - } - }); - - deathSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionTimed, new Boolean(deathSourceConditionTimed.isSelected())); - } - }); - deathSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(deathSourceConditionForever, new Boolean(deathSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - public void updateDeathSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - deathSourceConditionClear.setSelected(clear); - deathSourceConditionApply.setSelected(!clear && !immunity); - deathSourceConditionMagnitude.setEnabled(!clear && !immunity); - deathSourceConditionImmunity.setSelected(immunity); - - deathSourceConditionTimed.setSelected(!forever); - deathSourceConditionTimed.setEnabled(!clear); - deathSourceConditionDuration.setEnabled(!clear && !forever); - deathSourceConditionForever.setSelected(forever); - deathSourceConditionForever.setEnabled(!clear); + deathEffectPane.updateEffectSourceTimedConditionWidgets(condition); } public static class TargetTimedConditionsListModel extends OrderedListenerListModel { @@ -1029,80 +902,80 @@ public class NPCEditor extends JSONElementEditor { } else if (source == hitReceivedTargetConditionChance) { selectedHitReceivedEffectTargetCondition.chance = (Double) value; hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - } else if (source == deathEffectHPMin) { - deathEffect.hp_boost_min = (Integer) value; + } else if (source == deathEffectPane.effectHPMin) { + deathEffectPane. effect.hp_boost_min = (Integer) value; updateDeath = true; - } else if (source == deathEffectHPMax) { - deathEffect.hp_boost_max = (Integer) value; + } else if (source == deathEffectPane. effectHPMax) { + deathEffectPane. effect.hp_boost_max = (Integer) value; updateDeath = true; - } else if (source == deathEffectAPMin) { - deathEffect.ap_boost_min = (Integer) value; + } else if (source == deathEffectPane. effectAPMin) { + deathEffectPane. effect.ap_boost_min = (Integer) value; updateDeath = true; - } else if (source == deathEffectAPMax) { - deathEffect.ap_boost_max = (Integer) value; + } else if (source == deathEffectPane. effectAPMax) { + deathEffectPane. effect.ap_boost_max = (Integer) value; updateDeath = true; - } else if (source == deathSourceConditionsList) { + } else if (source == deathEffectPane. sourceConditionsList) { updateDeath = true; - } else if (source == deathSourceConditionBox) { - if (selectedDeathEffectSourceCondition.condition != null) { - selectedDeathEffectSourceCondition.condition.removeBacklink(npc); + } else if (source == deathEffectPane. sourceConditionBox) { + if (deathEffectPane.selectedEffectSourceCondition.condition != null) { + deathEffectPane.selectedEffectSourceCondition.condition.removeBacklink(npc); } - selectedDeathEffectSourceCondition.condition = (ActorCondition) value; - if (selectedDeathEffectSourceCondition.condition != null) { - selectedDeathEffectSourceCondition.condition.addBacklink(npc); - selectedDeathEffectSourceCondition.condition_id = selectedDeathEffectSourceCondition.condition.id; + deathEffectPane.selectedEffectSourceCondition.condition = (ActorCondition) value; + if (deathEffectPane.selectedEffectSourceCondition.condition != null) { + deathEffectPane.selectedEffectSourceCondition.condition.addBacklink(npc); + deathEffectPane.selectedEffectSourceCondition.condition_id = deathEffectPane.selectedEffectSourceCondition.condition.id; } else { - selectedDeathEffectSourceCondition.condition_id = null; + deathEffectPane.selectedEffectSourceCondition.condition_id = null; } - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); - } else if (source == deathSourceConditionClear && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedDeathEffectSourceCondition.duration = null; - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); + } else if (source == deathEffectPane. sourceConditionClear && (Boolean) value) { + deathEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + deathEffectPane.selectedEffectSourceCondition.duration = null; + updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); updateDeath = true; - } else if (source == deathSourceConditionApply && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = (Integer) deathSourceConditionMagnitude.getValue(); - selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; + } else if (source == deathEffectPane. sourceConditionApply && (Boolean) value) { + deathEffectPane.selectedEffectSourceCondition.magnitude = (Integer) deathEffectPane. sourceConditionMagnitude.getValue(); + deathEffectPane.selectedEffectSourceCondition.duration = deathEffectPane. sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathEffectPane. sourceConditionDuration.getValue(); + if (deathEffectPane.selectedEffectSourceCondition.duration == null || deathEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + deathEffectPane.selectedEffectSourceCondition.duration = 1; } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); updateDeath = true; - } else if (source == deathSourceConditionImmunity && (Boolean) value) { - selectedDeathEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedDeathEffectSourceCondition.duration = deathSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; + } else if (source == deathEffectPane. sourceConditionImmunity && (Boolean) value) { + deathEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + deathEffectPane.selectedEffectSourceCondition.duration = deathEffectPane. sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathEffectPane. sourceConditionDuration.getValue(); + if (deathEffectPane.selectedEffectSourceCondition.duration == null || deathEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + deathEffectPane.selectedEffectSourceCondition.duration = 1; } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); updateDeath = true; - } else if (source == deathSourceConditionMagnitude) { - selectedDeathEffectSourceCondition.magnitude = (Integer) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } else if (source == deathEffectPane. sourceConditionMagnitude) { + deathEffectPane.selectedEffectSourceCondition.magnitude = (Integer) value; + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); updateDeath = true; - } else if (source == deathSourceConditionTimed && (Boolean) value) { - selectedDeathEffectSourceCondition.duration = (Integer) deathSourceConditionDuration.getValue(); - if (selectedDeathEffectSourceCondition.duration == null || selectedDeathEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedDeathEffectSourceCondition.duration = 1; + } else if (source == deathEffectPane. sourceConditionTimed && (Boolean) value) { + deathEffectPane.selectedEffectSourceCondition.duration = (Integer) deathEffectPane. sourceConditionDuration.getValue(); + if (deathEffectPane.selectedEffectSourceCondition.duration == null || deathEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + deathEffectPane.selectedEffectSourceCondition.duration = 1; } - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); updateDeath = true; - } else if (source == deathSourceConditionForever && (Boolean) value) { - selectedDeathEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateDeathSourceTimedConditionWidgets(selectedDeathEffectSourceCondition); - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } else if (source == deathEffectPane. sourceConditionForever && (Boolean) value) { + deathEffectPane.selectedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); updateDeath = true; - } else if (source == deathSourceConditionDuration) { - selectedDeathEffectSourceCondition.duration = (Integer) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } else if (source == deathEffectPane. sourceConditionDuration) { + deathEffectPane.selectedEffectSourceCondition.duration = (Integer) value; + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); updateDeath = true; - } else if (source == deathSourceConditionChance) { - selectedDeathEffectSourceCondition.chance = (Double) value; - deathSourceConditionsListModel.itemChanged(selectedDeathEffectSourceCondition); + } else if (source == deathEffectPane. sourceConditionChance) { + deathEffectPane.selectedEffectSourceCondition.chance = (Double) value; + deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); } if (updateHit) { @@ -1120,10 +993,10 @@ public class NPCEditor extends JSONElementEditor { } } if (updateDeath) { - if (isNull(deathEffect)) { + if (isNull(deathEffectPane. effect)) { npc.death_effect = null; } else { - npc.death_effect = deathEffect; + npc.death_effect = deathEffectPane. effect; } } From ebafae750333315b9735fa666fd729a13d3ed2a5 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 21:03:04 +0200 Subject: [PATCH 62/94] extract some valueChanged stuff for DeathEffectPane & HitEffectPane --- .../gpl/rpg/atcontentstudio/ui/Editor.java | 8 +- .../ui/gamedataeditors/CommonEditor.java | 147 ++++++++++++- .../ui/gamedataeditors/NPCEditor.java | 200 +----------------- 3 files changed, 151 insertions(+), 204 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index b971732..1fbd519 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -1105,10 +1105,10 @@ public abstract class Editor extends JPanel implements ProjectElementListener { } - protected > void updateConditionEffect(ActorCondition value, - GameDataElement backlink, - E selectedHitEffectTargetCondition, - T hitTargetConditionsModel) { + public > void updateConditionEffect(ActorCondition value, + GameDataElement backlink, + E selectedHitEffectTargetCondition, + T hitTargetConditionsModel) { if (selectedHitEffectTargetCondition.condition != null) { selectedHitEffectTargetCondition.condition.removeBacklink(backlink); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 4f55493..160c91f 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -1,5 +1,6 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; +import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; import com.gpl.rpg.atcontentstudio.model.gamedata.Common; @@ -105,9 +106,9 @@ public class CommonEditor { this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; } - void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.HitEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModelInput) { + void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.HitEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModelInput) { effect = e; - createDeathEffectPaneContent( listener, writable, e, sourceConditionsModelInput); + createDeathEffectPaneContent(listener, writable, e, sourceConditionsModelInput); String titleTarget = "Actor Conditions applied to the target: "; hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(effect); @@ -225,6 +226,68 @@ public class CommonEditor { hitTargetConditionForever.setEnabled(!clear); } + + @Override + public boolean valueChanged(JComponent source, Object value, GameDataElement backlink) { + boolean updateHit = super.valueChanged(source, value, backlink); + if (!updateHit) { + if (source == hitTargetConditionsList) { + updateHit = true; + } else if (source == hitTargetConditionBox) { + editor.updateConditionEffect((ActorCondition) value, backlink, selectedHitEffectTargetCondition, hitTargetConditionsListModel); + } else if (source == hitTargetConditionClear && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = null; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionApply && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionImmunity && (Boolean) value) { + selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionMagnitude) { + selectedHitEffectTargetCondition.magnitude = (Integer) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionTimed && (Boolean) value) { + selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); + if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { + selectedHitEffectTargetCondition.duration = 1; + } + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionForever && (Boolean) value) { + selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; + updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionDuration) { + selectedHitEffectTargetCondition.duration = (Integer) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + updateHit = true; + } else if (source == hitTargetConditionChance) { + selectedHitEffectTargetCondition.chance = (Double) value; + hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); + } + } + + return updateHit; + } } public static class DeathEffectPane> { @@ -397,5 +460,85 @@ public class CommonEditor { sourceConditionForever.setSelected(forever); sourceConditionForever.setEnabled(!clear); } + + public boolean valueChanged(JComponent source, Object value, GameDataElement backlink) { + boolean updateHit = false; + if (source == effectHPMin) { + effect.hp_boost_min = (Integer) value; + updateHit = true; + } else if (source == effectHPMax) { + effect.hp_boost_max = (Integer) value; + updateHit = true; + } else if (source == effectAPMin) { + effect.ap_boost_min = (Integer) value; + updateHit = true; + } else if (source == effectAPMax) { + effect.ap_boost_max = (Integer) value; + updateHit = true; + } else if (source == sourceConditionsList) { + updateHit = true; + } else if (source == sourceConditionBox) { + if (selectedEffectSourceCondition.condition != null) { + selectedEffectSourceCondition.condition.removeBacklink(backlink); + } + selectedEffectSourceCondition.condition = (ActorCondition) value; + if (selectedEffectSourceCondition.condition != null) { + selectedEffectSourceCondition.condition.addBacklink(backlink); + selectedEffectSourceCondition.condition_id = selectedEffectSourceCondition.condition.id; + } else { + selectedEffectSourceCondition.condition_id = null; + } + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + } else if (source == sourceConditionClear && (Boolean) value) { + selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedEffectSourceCondition.duration = null; + updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + updateHit = true; + } else if (source == sourceConditionApply && (Boolean) value) { + selectedEffectSourceCondition.magnitude = (Integer) sourceConditionMagnitude.getValue(); + selectedEffectSourceCondition.duration = sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) sourceConditionDuration.getValue(); + if (selectedEffectSourceCondition.duration == null || selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedEffectSourceCondition.duration = 1; + } + updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + updateHit = true; + } else if (source == sourceConditionImmunity && (Boolean) value) { + selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedEffectSourceCondition.duration = sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) sourceConditionDuration.getValue(); + if (selectedEffectSourceCondition.duration == null || selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedEffectSourceCondition.duration = 1; + } + updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + updateHit = true; + } else if (source == sourceConditionMagnitude) { + selectedEffectSourceCondition.magnitude = (Integer) value; + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + updateHit = true; + } else if (source == sourceConditionTimed && (Boolean) value) { + selectedEffectSourceCondition.duration = (Integer) sourceConditionDuration.getValue(); + if (selectedEffectSourceCondition.duration == null || selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { + selectedEffectSourceCondition.duration = 1; + } + updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + updateHit = true; + } else if (source == sourceConditionForever && (Boolean) value) { + selectedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; + updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + updateHit = true; + } else if (source == sourceConditionDuration) { + selectedEffectSourceCondition.duration = (Integer) value; + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + updateHit = true; + } else if (source == sourceConditionChance) { + selectedEffectSourceCondition.chance = (Double) value; + sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + } + return updateHit; + } } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 1670d0a..0104e73 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -638,132 +638,8 @@ public class NPCEditor extends JSONElementEditor { npc.block_chance = (Integer) value; } else if (source == dmgRes) { npc.damage_resistance = (Integer) value; - } else if (source == hitEffectPane.effectHPMin) { - hitEffectPane.effect.hp_boost_min = (Integer) value; + } else if(hitEffectPane != null &&hitEffectPane.valueChanged(source, value, npc)) { updateHit = true; - } else if (source == hitEffectPane.effectHPMax) { - hitEffectPane.effect.hp_boost_max = (Integer) value; - updateHit = true; - } else if (source == hitEffectPane.effectAPMin) { - hitEffectPane.effect.ap_boost_min = (Integer) value; - updateHit = true; - } else if (source == hitEffectPane.effectAPMax) { - hitEffectPane.effect.ap_boost_max = (Integer) value; - updateHit = true; - } else if (source == hitEffectPane.sourceConditionsList) { - updateHit = true; - } else if (source == hitEffectPane.sourceConditionBox) { - if (hitEffectPane.selectedEffectSourceCondition.condition != null) { - hitEffectPane.selectedEffectSourceCondition.condition.removeBacklink(npc); - } - hitEffectPane.selectedEffectSourceCondition.condition = (ActorCondition) value; - if (hitEffectPane.selectedEffectSourceCondition.condition != null) { - hitEffectPane.selectedEffectSourceCondition.condition.addBacklink(npc); - hitEffectPane.selectedEffectSourceCondition.condition_id = hitEffectPane.selectedEffectSourceCondition.condition.id; - } else { - hitEffectPane.selectedEffectSourceCondition.condition_id = null; - } - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - } else if (source == hitEffectPane.sourceConditionClear && (Boolean) value) { - hitEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - hitEffectPane.selectedEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - updateHit = true; - } else if (source == hitEffectPane.sourceConditionApply && (Boolean) value) { - hitEffectPane.selectedEffectSourceCondition.magnitude = (Integer) hitEffectPane.sourceConditionMagnitude.getValue(); - hitEffectPane.selectedEffectSourceCondition.duration = hitEffectPane.sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.sourceConditionDuration.getValue(); - if (hitEffectPane.selectedEffectSourceCondition.duration == null || hitEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - updateHit = true; - } else if (source == hitEffectPane.sourceConditionImmunity && (Boolean) value) { - hitEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - hitEffectPane.selectedEffectSourceCondition.duration = hitEffectPane.sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.sourceConditionDuration.getValue(); - if (hitEffectPane.selectedEffectSourceCondition.duration == null || hitEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - updateHit = true; - } else if (source == hitEffectPane.sourceConditionMagnitude) { - hitEffectPane.selectedEffectSourceCondition.magnitude = (Integer) value; - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - updateHit = true; - } else if (source == hitEffectPane.sourceConditionTimed && (Boolean) value) { - hitEffectPane.selectedEffectSourceCondition.duration = (Integer) hitEffectPane.sourceConditionDuration.getValue(); - if (hitEffectPane.selectedEffectSourceCondition.duration == null || hitEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - updateHit = true; - } else if (source == hitEffectPane.sourceConditionForever && (Boolean) value) { - hitEffectPane.selectedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(hitEffectPane.selectedEffectSourceCondition); - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - updateHit = true; - } else if (source == hitEffectPane.sourceConditionDuration) { - hitEffectPane.selectedEffectSourceCondition.duration = (Integer) value; - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - updateHit = true; - } else if (source == hitEffectPane.sourceConditionChance) { - hitEffectPane.selectedEffectSourceCondition.chance = (Double) value; - hitEffectPane.sourceConditionsModel.itemChanged(hitEffectPane.selectedEffectSourceCondition); - } else if (source == hitEffectPane.hitTargetConditionsList) { - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionBox) { - updateConditionEffect((ActorCondition) value, npc, hitEffectPane.selectedHitEffectTargetCondition, hitEffectPane.hitTargetConditionsListModel); - } else if (source == hitEffectPane.hitTargetConditionClear && (Boolean) value) { - hitEffectPane.selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - hitEffectPane.selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionApply && (Boolean) value) { - hitEffectPane.selectedHitEffectTargetCondition.magnitude = (Integer) hitEffectPane.hitTargetConditionMagnitude.getValue(); - hitEffectPane.selectedHitEffectTargetCondition.duration = hitEffectPane.hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitTargetConditionDuration.getValue(); - if (hitEffectPane.selectedHitEffectTargetCondition.duration == null || hitEffectPane.selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionImmunity && (Boolean) value) { - hitEffectPane.selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - hitEffectPane.selectedHitEffectTargetCondition.duration = hitEffectPane.hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitEffectPane.hitTargetConditionDuration.getValue(); - if (hitEffectPane.selectedHitEffectTargetCondition.duration == null || hitEffectPane.selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionMagnitude) { - hitEffectPane.selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionTimed && (Boolean) value) { - hitEffectPane.selectedHitEffectTargetCondition.duration = (Integer) hitEffectPane.hitTargetConditionDuration.getValue(); - if (hitEffectPane.selectedHitEffectTargetCondition.duration == null || hitEffectPane.selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - hitEffectPane.selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionForever && (Boolean) value) { - hitEffectPane.selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(hitEffectPane.selectedHitEffectTargetCondition); - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionDuration) { - hitEffectPane.selectedHitEffectTargetCondition.duration = (Integer) value; - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitEffectPane.hitTargetConditionChance) { - hitEffectPane.selectedHitEffectTargetCondition.chance = (Double) value; - hitEffectPane.hitTargetConditionsListModel.itemChanged(hitEffectPane.selectedHitEffectTargetCondition); } else if (source == hitReceivedEffectHPMin) { hitReceivedEffect.hp_boost_min = (Integer) value; updateHitReceived = true; @@ -902,80 +778,8 @@ public class NPCEditor extends JSONElementEditor { } else if (source == hitReceivedTargetConditionChance) { selectedHitReceivedEffectTargetCondition.chance = (Double) value; hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - } else if (source == deathEffectPane.effectHPMin) { - deathEffectPane. effect.hp_boost_min = (Integer) value; + } else if (deathEffectPane.valueChanged(source, value, npc)) { updateDeath = true; - } else if (source == deathEffectPane. effectHPMax) { - deathEffectPane. effect.hp_boost_max = (Integer) value; - updateDeath = true; - } else if (source == deathEffectPane. effectAPMin) { - deathEffectPane. effect.ap_boost_min = (Integer) value; - updateDeath = true; - } else if (source == deathEffectPane. effectAPMax) { - deathEffectPane. effect.ap_boost_max = (Integer) value; - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionsList) { - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionBox) { - if (deathEffectPane.selectedEffectSourceCondition.condition != null) { - deathEffectPane.selectedEffectSourceCondition.condition.removeBacklink(npc); - } - deathEffectPane.selectedEffectSourceCondition.condition = (ActorCondition) value; - if (deathEffectPane.selectedEffectSourceCondition.condition != null) { - deathEffectPane.selectedEffectSourceCondition.condition.addBacklink(npc); - deathEffectPane.selectedEffectSourceCondition.condition_id = deathEffectPane.selectedEffectSourceCondition.condition.id; - } else { - deathEffectPane.selectedEffectSourceCondition.condition_id = null; - } - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - } else if (source == deathEffectPane. sourceConditionClear && (Boolean) value) { - deathEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - deathEffectPane.selectedEffectSourceCondition.duration = null; - updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionApply && (Boolean) value) { - deathEffectPane.selectedEffectSourceCondition.magnitude = (Integer) deathEffectPane. sourceConditionMagnitude.getValue(); - deathEffectPane.selectedEffectSourceCondition.duration = deathEffectPane. sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathEffectPane. sourceConditionDuration.getValue(); - if (deathEffectPane.selectedEffectSourceCondition.duration == null || deathEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - deathEffectPane.selectedEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionImmunity && (Boolean) value) { - deathEffectPane.selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - deathEffectPane.selectedEffectSourceCondition.duration = deathEffectPane. sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) deathEffectPane. sourceConditionDuration.getValue(); - if (deathEffectPane.selectedEffectSourceCondition.duration == null || deathEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - deathEffectPane.selectedEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionMagnitude) { - deathEffectPane.selectedEffectSourceCondition.magnitude = (Integer) value; - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionTimed && (Boolean) value) { - deathEffectPane.selectedEffectSourceCondition.duration = (Integer) deathEffectPane. sourceConditionDuration.getValue(); - if (deathEffectPane.selectedEffectSourceCondition.duration == null || deathEffectPane.selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - deathEffectPane.selectedEffectSourceCondition.duration = 1; - } - updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionForever && (Boolean) value) { - deathEffectPane.selectedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateDeathSourceTimedConditionWidgets(deathEffectPane.selectedEffectSourceCondition); - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionDuration) { - deathEffectPane.selectedEffectSourceCondition.duration = (Integer) value; - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); - updateDeath = true; - } else if (source == deathEffectPane. sourceConditionChance) { - deathEffectPane.selectedEffectSourceCondition.chance = (Double) value; - deathEffectPane. sourceConditionsModel.itemChanged(deathEffectPane.selectedEffectSourceCondition); } if (updateHit) { From 270c613f66c1253dd7fd9471807ef36c1890b76b Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 21:17:44 +0200 Subject: [PATCH 63/94] add applyToTargetHint to HitEffectPanel --- .../atcontentstudio/ui/gamedataeditors/CommonEditor.java | 6 +++++- .../rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java | 7 ++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 160c91f..7e2d6d8 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -84,6 +84,9 @@ public class CommonEditor { public static class HitEffectPane extends DeathEffectPane { /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! Common.HitEffect effect; + + String applyToTargetHint; + NPCEditor.TargetTimedConditionsListModel hitTargetConditionsListModel; JList hitTargetConditionsList; Common.TimedActorConditionEffect selectedHitEffectTargetCondition; @@ -101,9 +104,10 @@ public class CommonEditor { /* * create a new HitEffectPane with the selections (probably passed in from last time) */ - public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint) { + public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { super(title, sourceNewSupplier, editor, applyToHint); this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; + this.applyToTargetHint = applyToTargetHint; } void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.HitEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModelInput) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 0104e73..63a434b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -194,11 +194,8 @@ public class NPCEditor extends JSONElementEditor { hitEffect = npc.hit_effect; } if (hitEffectPane == null) - hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, "test"); - hitEffectPane.createHitEffectPaneContent(listener, - npc.writable, - hitEffect, - new SourceTimedConditionsListModel(hitEffect)); + hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); + hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new SourceTimedConditionsListModel(hitEffect)); combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); From c78fcde63337ea3bb2c108df265ff65f7dfe90d6 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 21:17:51 +0200 Subject: [PATCH 64/94] extract hitReceivedEffect stuff into HitReceivedEffectPane --- .../ui/gamedataeditors/CommonEditor.java | 22 + .../ui/gamedataeditors/NPCEditor.java | 442 +----------------- 2 files changed, 33 insertions(+), 431 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 7e2d6d8..5944686 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -81,6 +81,28 @@ public class CommonEditor { } } + public static class HitRecievedEffectPane extends HitEffectPane { + /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! + Common.HitReceivedEffect effect; + private JSpinner hitReceivedEffectHPMinTarget; + private JSpinner hitReceivedEffectHPMaxTarget; + private JSpinner hitReceivedEffectAPMinTarget; + private JSpinner hitReceivedEffectAPMaxTarget; + public HitRecievedEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { + super(title, sourceNewSupplier, editor, applyToHint,applyToTargetHint); + } + + void createHitReceivedEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.HitReceivedEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModelInput) { + effect = e; + createHitEffectPaneContent(listener, writable, e, sourceConditionsModelInput); + + hitReceivedEffectHPMinTarget = addIntegerField(effectPane, "Attacker HP bonus min%s: ".formatted(applyToTargetHint), effect.target.hp_boost_min, true, writable, listener); + hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, "Attacker HP bonus max%s: ".formatted(applyToTargetHint), effect.target.hp_boost_max, true, writable, listener); + hitReceivedEffectAPMinTarget = addIntegerField(effectPane, "Attacker AP bonus min%s: ".formatted(applyToTargetHint), effect.target.ap_boost_min, true, writable, listener); + hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, "Attacker AP bonus max%s: ".formatted(applyToTargetHint), effect.target.ap_boost_max, true, writable, listener); + } + } + public static class HitEffectPane extends DeathEffectPane { /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! Common.HitEffect effect; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 63a434b..30813c9 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -2,15 +2,11 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; -import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.*; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; import com.gpl.rpg.atcontentstudio.ui.*; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; -import com.gpl.rpg.atcontentstudio.utils.BasicLambda; -import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; -import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithReturn; import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; @@ -29,8 +25,6 @@ public class NPCEditor extends JSONElementEditor { private static final String json_view_id = "JSON"; private static final String dialogue_tree_id = "Dialogue Tree"; - private Common.TimedActorConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedActorConditionEffect selectedHitReceivedEffectTargetCondition; private JButton npcIcon; private JTextField idField; @@ -60,45 +54,7 @@ public class NPCEditor extends JSONElementEditor { private JSpinner dmgRes; private CommonEditor.HitEffectPane hitEffectPane; - - - private Common.HitReceivedEffect hitReceivedEffect; - private CollapsiblePanel hitReceivedEffectPane; - private JSpinner hitReceivedEffectHPMin; - private JSpinner hitReceivedEffectHPMax; - private JSpinner hitReceivedEffectAPMin; - private JSpinner hitReceivedEffectAPMax; - private JSpinner hitReceivedEffectHPMinTarget; - private JSpinner hitReceivedEffectHPMaxTarget; - private JSpinner hitReceivedEffectAPMinTarget; - private JSpinner hitReceivedEffectAPMaxTarget; - - private SourceTimedConditionsListModel hitReceivedSourceConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedSourceConditionsList; - private MyComboBox hitReceivedSourceConditionBox; - private JSpinner hitReceivedSourceConditionChance; - private JRadioButton hitReceivedSourceConditionClear; - private JRadioButton hitReceivedSourceConditionApply; - private JRadioButton hitReceivedSourceConditionImmunity; - private JSpinner hitReceivedSourceConditionMagnitude; - private JRadioButton hitReceivedSourceConditionTimed; - private JRadioButton hitReceivedSourceConditionForever; - private JSpinner hitReceivedSourceConditionDuration; - - private TargetTimedConditionsListModel hitReceivedTargetConditionsListModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedTargetConditionsList; - private MyComboBox hitReceivedTargetConditionBox; - private JSpinner hitReceivedTargetConditionChance; - private JRadioButton hitReceivedTargetConditionClear; - private JRadioButton hitReceivedTargetConditionApply; - private JRadioButton hitReceivedTargetConditionImmunity; - private JSpinner hitReceivedTargetConditionMagnitude; - private JRadioButton hitReceivedTargetConditionTimed; - private JRadioButton hitReceivedTargetConditionForever; - private JSpinner hitReceivedTargetConditionDuration; - + private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane; private CommonEditor.DeathEffectPane deathEffectPane; private JPanel dialogueGraphPane; @@ -198,73 +154,16 @@ public class NPCEditor extends JSONElementEditor { hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new SourceTimedConditionsListModel(hitEffect)); combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); - hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); - hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); + Common.HitReceivedEffect hitReceivedEffect; if (npc.hit_received_effect == null) { hitReceivedEffect = new Common.HitReceivedEffect(); } else { hitReceivedEffect = npc.hit_received_effect; } - hitReceivedEffectHPMin = addIntegerField(hitReceivedEffectPane, "NPC HP bonus min: ", hitReceivedEffect.hp_boost_min, true, npc.writable, listener); - hitReceivedEffectHPMax = addIntegerField(hitReceivedEffectPane, "NPC HP bonus max: ", hitReceivedEffect.hp_boost_max, true, npc.writable, listener); - hitReceivedEffectAPMin = addIntegerField(hitReceivedEffectPane, "NPC AP bonus min: ", hitReceivedEffect.ap_boost_min, true, npc.writable, listener); - hitReceivedEffectAPMax = addIntegerField(hitReceivedEffectPane, "NPC AP bonus max: ", hitReceivedEffect.ap_boost_max, true, npc.writable, listener); - hitReceivedEffectHPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus min: ", hitReceivedEffect.target.hp_boost_min, true, npc.writable, listener); - hitReceivedEffectHPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker HP bonus max: ", hitReceivedEffect.target.hp_boost_max, true, npc.writable, listener); - hitReceivedEffectAPMinTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus min: ", hitReceivedEffect.target.ap_boost_min, true, npc.writable, listener); - hitReceivedEffectAPMaxTarget = addIntegerField(hitReceivedEffectPane, "Attacker AP bonus max: ", hitReceivedEffect.target.ap_boost_max, true, npc.writable, listener); - - String titleReceivedSource = "Actor Conditions applied to this NPC: "; - hitReceivedSourceConditionsListModel = new SourceTimedConditionsListModel(hitReceivedEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererReceivedSource = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetReceivedSource = (value)->selectedHitReceivedEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetReceivedSource = ()->selectedHitReceivedEffectSourceCondition ; - BasicLambda selectedResetReceivedSource = ()->selectedHitReceivedEffectSourceCondition = null; - BasicLambdaWithArg updatePaneReceivedSource = (editorPane) -> updateHitReceivedSourceTimedConditionEditorPane(editorPane, selectedHitReceivedEffectSourceCondition, listener); - var resultReceivedSource = UiUtils.getCollapsibleItemList(listener, - hitReceivedSourceConditionsListModel, - selectedResetReceivedSource, - selectedSetReceivedSource, - selectedGetReceivedSource, - (x) -> {}, - updatePaneReceivedSource, - npc.writable, - Common.TimedActorConditionEffect::new, - cellRendererReceivedSource, - titleReceivedSource, - (x) -> null); - hitReceivedSourceConditionsList = resultReceivedSource.list; - CollapsiblePanel hitReceivedSourceConditionsPane = resultReceivedSource.collapsiblePanel; - if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_source == null || npc.hit_received_effect.conditions_source.isEmpty()) { - hitReceivedSourceConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - - String titleReceivedTarget = "Actor Conditions applied to the attacker: "; - hitReceivedTargetConditionsListModel = new TargetTimedConditionsListModel(hitReceivedEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererReceivedTarget = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetReceivedTarget = (value)->selectedHitReceivedEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition ; - BasicLambda selectedResetReceivedTarget = ()->selectedHitReceivedEffectTargetCondition = null; - BasicLambdaWithArg updatePaneReceivedTarget = (editorPane) -> updateHitReceivedTargetTimedConditionEditorPane(editorPane, selectedHitReceivedEffectTargetCondition, listener); - var resultReceivedTarget = UiUtils.getCollapsibleItemList(listener, - hitReceivedTargetConditionsListModel, - selectedResetReceivedTarget, - selectedSetReceivedTarget, - selectedGetReceivedTarget, - (x) -> {}, - updatePaneReceivedTarget, - npc.writable, - Common.TimedActorConditionEffect::new, - cellRendererReceivedTarget, - titleReceivedTarget, - (x) -> null); - hitReceivedTargetConditionsList = resultReceivedTarget.list; - CollapsiblePanel hitReceivedTargetConditionsPane = resultReceivedTarget.collapsiblePanel; - if (npc.hit_received_effect == null || npc.hit_received_effect.conditions_target == null || npc.hit_received_effect.conditions_target.isEmpty()) { - hitReceivedTargetConditionsPane.collapse(); - } - combatTraitPane.add(hitReceivedEffectPane, JideBoxLayout.FIX); + if (hitReceivedEffectPane == null) + hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, "NPC", "Attacker"); + hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, new SourceTimedConditionsListModel(hitReceivedEffect)); + combatTraitPane.add(hitReceivedEffectPane.effectPane, JideBoxLayout.FIX); Common.DeathEffect deathEffect; if (npc.death_effect == null) { @@ -274,10 +173,7 @@ public class NPCEditor extends JSONElementEditor { } if (deathEffectPane == null) deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", Common.TimedActorConditionEffect::new, this, "Killer"); - deathEffectPane.createDeathEffectPaneContent(listener, - npc.writable, - deathEffect, - new SourceTimedConditionsListModel(deathEffect) + deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, deathEffect, new SourceTimedConditionsListModel(deathEffect) ); combatTraitPane.add(deathEffectPane.effectPane, JideBoxLayout.FIX); @@ -294,186 +190,6 @@ public class NPCEditor extends JSONElementEditor { hitEffectPane.updateHitTargetTimedConditionWidgets(condition); } - - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedSourceConditionBox != null) { - removeElementListener(hitReceivedSourceConditionBox); - } - - boolean writable = ((NPC) target).writable; - Project proj = ((NPC) target).getProject(); - - hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); - hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); - hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedSourceConditionApply); - radioEffectGroup.add(hitReceivedSourceConditionClear); - radioEffectGroup.add(hitReceivedSourceConditionImmunity); - - hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); - hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedSourceConditionTimed); - radioDurationGroup.add(hitReceivedSourceConditionForever); - - updateHitReceivedSourceTimedConditionWidgets(condition); - - hitReceivedSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionClear, new Boolean(hitReceivedSourceConditionClear.isSelected())); - } - }); - hitReceivedSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionApply, new Boolean(hitReceivedSourceConditionApply.isSelected())); - } - }); - hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionImmunity, new Boolean(hitReceivedSourceConditionImmunity.isSelected())); - } - }); - - hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionTimed, new Boolean(hitReceivedSourceConditionTimed.isSelected())); - } - }); - hitReceivedSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionForever, new Boolean(hitReceivedSourceConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitReceivedSourceConditionClear.setSelected(clear); - hitReceivedSourceConditionApply.setSelected(!clear && !immunity); - hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedSourceConditionImmunity.setSelected(immunity); - - hitReceivedSourceConditionTimed.setSelected(!forever); - hitReceivedSourceConditionTimed.setEnabled(!clear); - hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); - hitReceivedSourceConditionForever.setSelected(forever); - hitReceivedSourceConditionForever.setEnabled(!clear); - } - - - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedTargetConditionBox != null) { - removeElementListener(hitReceivedTargetConditionBox); - } - - boolean writable = ((NPC) target).writable; - Project proj = ((NPC) target).getProject(); - - hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); - hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); - hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedTargetConditionApply); - radioEffectGroup.add(hitReceivedTargetConditionClear); - radioEffectGroup.add(hitReceivedTargetConditionImmunity); - - hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); - hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedTargetConditionTimed); - radioDurationGroup.add(hitReceivedTargetConditionForever); - - updateHitReceivedTargetTimedConditionWidgets(condition); - - hitReceivedTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionClear, new Boolean(hitReceivedTargetConditionClear.isSelected())); - } - }); - hitReceivedTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionApply, new Boolean(hitReceivedTargetConditionApply.isSelected())); - } - }); - hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionImmunity, new Boolean(hitReceivedTargetConditionImmunity.isSelected())); - } - }); - - hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionTimed, new Boolean(hitReceivedTargetConditionTimed.isSelected())); - } - }); - hitReceivedTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionForever, new Boolean(hitReceivedTargetConditionForever.isSelected())); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitReceivedTargetConditionClear.setSelected(clear); - hitReceivedTargetConditionApply.setSelected(!clear && !immunity); - hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedTargetConditionImmunity.setSelected(immunity); - - hitReceivedTargetConditionTimed.setSelected(!forever); - hitReceivedTargetConditionTimed.setEnabled(!clear); - hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); - hitReceivedTargetConditionForever.setSelected(forever); - hitReceivedTargetConditionForever.setEnabled(!clear); - } - public void updateDeathSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { deathEffectPane.updateEffectSourceTimedConditionWidgets(condition); } @@ -637,145 +353,9 @@ public class NPCEditor extends JSONElementEditor { npc.damage_resistance = (Integer) value; } else if(hitEffectPane != null &&hitEffectPane.valueChanged(source, value, npc)) { updateHit = true; - } else if (source == hitReceivedEffectHPMin) { - hitReceivedEffect.hp_boost_min = (Integer) value; + } else if (hitReceivedEffectPane != null && hitReceivedEffectPane.valueChanged(source, value, npc)) { updateHitReceived = true; - } else if (source == hitReceivedEffectHPMax) { - hitReceivedEffect.hp_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMin) { - hitReceivedEffect.ap_boost_min = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMax) { - hitReceivedEffect.ap_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMinTarget) { - hitReceivedEffect.target.hp_boost_min = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectHPMaxTarget) { - hitReceivedEffect.target.hp_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMinTarget) { - hitReceivedEffect.target.ap_boost_min = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedEffectAPMaxTarget) { - hitReceivedEffect.target.ap_boost_max = (Integer) value; - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionBox) { - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.removeBacklink(npc); - } - selectedHitReceivedEffectSourceCondition.condition = (ActorCondition) value; - if (selectedHitReceivedEffectSourceCondition.condition != null) { - selectedHitReceivedEffectSourceCondition.condition.addBacklink(npc); - selectedHitReceivedEffectSourceCondition.condition_id = selectedHitReceivedEffectSourceCondition.condition.id; - } else { - selectedHitReceivedEffectSourceCondition.condition_id = null; - } - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = null; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionMagnitude) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionDuration) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionChance) { - selectedHitReceivedEffectSourceCondition.chance = (Double) value; - hitReceivedSourceConditionsListModel.itemChanged(selectedHitReceivedEffectSourceCondition); - } else if (source == hitReceivedTargetConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionBox) { - updateConditionEffect((ActorCondition) value, npc, selectedHitReceivedEffectTargetCondition, hitReceivedTargetConditionsListModel); - } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = null; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionMagnitude) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionDuration) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionChance) { - selectedHitReceivedEffectTargetCondition.chance = (Double) value; - hitReceivedTargetConditionsListModel.itemChanged(selectedHitReceivedEffectTargetCondition); - } else if (deathEffectPane.valueChanged(source, value, npc)) { + } else if (deathEffectPane != null && deathEffectPane.valueChanged(source, value, npc)) { updateDeath = true; } @@ -787,10 +367,10 @@ public class NPCEditor extends JSONElementEditor { } } if (updateHitReceived) { - if (isNull(hitReceivedEffect)) { + if (isNull(hitEffectPane.effect)) { npc.hit_received_effect = null; } else { - npc.hit_received_effect = hitReceivedEffect; + npc.hit_received_effect = hitReceivedEffectPane.effect; } } if (updateDeath) { From 9ae9914dde06bc1786c0dc89717f2662f8d06947 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 21:29:09 +0200 Subject: [PATCH 65/94] cleanup --- .../ui/gamedataeditors/NPCEditor.java | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 30813c9..3ae095d 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -180,20 +180,6 @@ public class NPCEditor extends JSONElementEditor { pane.add(combatTraitPane, JideBoxLayout.FIX); } - - public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - hitEffectPane.updateEffectSourceTimedConditionWidgets(condition); - } - - - public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - hitEffectPane.updateHitTargetTimedConditionWidgets(condition); - } - - public void updateDeathSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - deathEffectPane.updateEffectSourceTimedConditionWidgets(condition); - } - public static class TargetTimedConditionsListModel extends OrderedListenerListModel { public TargetTimedConditionsListModel(Common.HitEffect effect) { super(effect); From 380bb1de17177bb4ae55d890ab083bc639d1cf3d Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 21:47:36 +0200 Subject: [PATCH 66/94] improve DeathEffectPane generics & inheritance --- .../ui/gamedataeditors/CommonEditor.java | 75 +++++++++++-------- .../ui/gamedataeditors/NPCEditor.java | 4 +- 2 files changed, 47 insertions(+), 32 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 5944686..4e00b0e 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -81,20 +81,21 @@ public class CommonEditor { } } - public static class HitRecievedEffectPane extends HitEffectPane { + public static class HitRecievedEffectPane> extends HitEffectPane { /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! - Common.HitReceivedEffect effect; + EFFECT effect; private JSpinner hitReceivedEffectHPMinTarget; private JSpinner hitReceivedEffectHPMaxTarget; private JSpinner hitReceivedEffectAPMinTarget; private JSpinner hitReceivedEffectAPMaxTarget; - public HitRecievedEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { - super(title, sourceNewSupplier, editor, applyToHint,applyToTargetHint); + + public HitRecievedEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { + super(title, sourceNewSupplier, editor, applyToHint, applyToTargetHint); } - void createHitReceivedEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.HitReceivedEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModelInput) { + void createHitReceivedEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModelInput, MODEL targetConditionsModelInput) { effect = e; - createHitEffectPaneContent(listener, writable, e, sourceConditionsModelInput); + createHitEffectPaneContent(listener, writable, e, sourceConditionsModelInput, targetConditionsModelInput); hitReceivedEffectHPMinTarget = addIntegerField(effectPane, "Attacker HP bonus min%s: ".formatted(applyToTargetHint), effect.target.hp_boost_min, true, writable, listener); hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, "Attacker HP bonus max%s: ".formatted(applyToTargetHint), effect.target.hp_boost_max, true, writable, listener); @@ -103,15 +104,15 @@ public class CommonEditor { } } - public static class HitEffectPane extends DeathEffectPane { + public static class HitEffectPane> extends DeathEffectPane { /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! - Common.HitEffect effect; + EFFECT effect; String applyToTargetHint; - NPCEditor.TargetTimedConditionsListModel hitTargetConditionsListModel; + MODEL hitTargetConditionsListModel; JList hitTargetConditionsList; - Common.TimedActorConditionEffect selectedHitEffectTargetCondition; + ELEMENT selectedHitEffectTargetCondition; Editor.MyComboBox hitTargetConditionBox; JSpinner hitTargetConditionChance; @@ -126,21 +127,26 @@ public class CommonEditor { /* * create a new HitEffectPane with the selections (probably passed in from last time) */ - public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { + public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { super(title, sourceNewSupplier, editor, applyToHint); this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; this.applyToTargetHint = applyToTargetHint; } - void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.HitEffect e, NPCEditor.SourceTimedConditionsListModel sourceConditionsModelInput) { + void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModelInput, MODEL hitTargetConditionsListModel1) { effect = e; + hitTargetConditionsListModel = hitTargetConditionsListModel1; createDeathEffectPaneContent(listener, writable, e, sourceConditionsModelInput); + } + + @Override + protected void addLists(FieldUpdateListener listener, boolean writable) { + super.addLists(listener, writable); String titleTarget = "Actor Conditions applied to the target: "; - hitTargetConditionsListModel = new NPCEditor.TargetTimedConditionsListModel(effect); CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; + BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; + BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; BasicLambda selectedResetTarget = () -> selectedHitEffectTargetCondition = null; BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener, this.editor); @@ -316,22 +322,22 @@ public class CommonEditor { } } - public static class DeathEffectPane> { - protected Supplier conditionSupplier; + public static class DeathEffectPane> { + protected Supplier conditionSupplier; protected String title; protected Editor editor; protected String applyToHint; - Common.DeathEffect effect; + EFFECT effect; CollapsiblePanel effectPane; JSpinner effectHPMin; JSpinner effectHPMax; JSpinner effectAPMin; JSpinner effectAPMax; - M sourceConditionsModel; - JList sourceConditionsList; - E selectedEffectSourceCondition; + MODEL sourceConditionsModel; + JList sourceConditionsList; + ELEMENT selectedEffectSourceCondition; Editor.MyComboBox sourceConditionBox; JSpinner sourceConditionChance; @@ -346,14 +352,17 @@ public class CommonEditor { /* * create a new DeatchEffectPane with the selections (probably passed in from last time) */ - public DeathEffectPane(String title, Supplier conditionSupplier, Editor editor, String applyToHint) { + public DeathEffectPane(String title, Supplier conditionSupplier, Editor editor, String applyToHint) { this.title = title; this.conditionSupplier = conditionSupplier; this.editor = editor; this.applyToHint = applyToHint; } - void createDeathEffectPaneContent(FieldUpdateListener listener, boolean writable, Common.DeathEffect e, M sourceConditionsModel) { + void createDeathEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModel) { + effect = e; + this.sourceConditionsModel = sourceConditionsModel; + if (applyToHint == null || applyToHint == "") { applyToHint = ""; } else { @@ -362,17 +371,23 @@ public class CommonEditor { effectPane = new CollapsiblePanel(title); effectPane.setLayout(new JideBoxLayout(effectPane, JideBoxLayout.PAGE_AXIS)); - effect = e; + + addFields(listener, writable); + addLists(listener, writable); + } + + protected void addFields(FieldUpdateListener listener, boolean writable) { effectHPMin = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToHint), effect.hp_boost_min, true, writable, listener); effectHPMax = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToHint), effect.hp_boost_max, true, writable, listener); effectAPMin = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToHint), effect.ap_boost_min, true, writable, listener); effectAPMax = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToHint), effect.ap_boost_max, true, writable, listener); + } + protected void addLists(FieldUpdateListener listener, boolean writable) { String titleSource = "Actor Conditions applied to the source%s: ".formatted(applyToHint); - this.sourceConditionsModel = sourceConditionsModel; - CommonEditor.TimedConditionsCellRenderer cellRendererSource = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetSource = (value) -> selectedEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetSource = () -> selectedEffectSourceCondition; + TimedConditionsCellRenderer cellRendererSource = new TimedConditionsCellRenderer(); + BasicLambdaWithArg selectedSetSource = (value) -> selectedEffectSourceCondition = value; + BasicLambdaWithReturn selectedGetSource = () -> selectedEffectSourceCondition; BasicLambda selectedResetSource = () -> selectedEffectSourceCondition = null; BasicLambdaWithArg updatePaneSource = (editorPane) -> updateEffectSourceTimedConditionEditorPane(editorPane, selectedEffectSourceCondition, listener, editor); @@ -397,7 +412,7 @@ public class CommonEditor { effectPane.add(sourceConditionsPane, JideBoxLayout.FIX); } - public void updateEffectSourceTimedConditionEditorPane(JPanel pane, E condition, final FieldUpdateListener listener, Editor e) { + public void updateEffectSourceTimedConditionEditorPane(JPanel pane, ELEMENT condition, final FieldUpdateListener listener, Editor e) { pane.removeAll(); if (sourceConditionBox != null) { e.removeElementListener(sourceConditionBox); @@ -470,7 +485,7 @@ public class CommonEditor { } - public void updateEffectSourceTimedConditionWidgets(E condition) { + public void updateEffectSourceTimedConditionWidgets(ELEMENT condition) { boolean immunity = condition.isImmunity(); boolean clear = condition.isClear(); boolean forever = condition.isInfinite(); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 3ae095d..c659962 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -151,7 +151,7 @@ public class NPCEditor extends JSONElementEditor { } if (hitEffectPane == null) hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); - hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new SourceTimedConditionsListModel(hitEffect)); + hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new SourceTimedConditionsListModel(hitEffect), new TargetTimedConditionsListModel(hitEffect)); combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); Common.HitReceivedEffect hitReceivedEffect; @@ -162,7 +162,7 @@ public class NPCEditor extends JSONElementEditor { } if (hitReceivedEffectPane == null) hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, "NPC", "Attacker"); - hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, new SourceTimedConditionsListModel(hitReceivedEffect)); + hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, new SourceTimedConditionsListModel(hitReceivedEffect), new TargetTimedConditionsListModel(hitReceivedEffect)); combatTraitPane.add(hitReceivedEffectPane.effectPane, JideBoxLayout.FIX); Common.DeathEffect deathEffect; From 0c69438a33acee75c32b72e2cc29dd10d5c1c301 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 21:55:08 +0200 Subject: [PATCH 67/94] move the hitReceivedEffect fields to the correct position --- .../ui/gamedataeditors/CommonEditor.java | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 4e00b0e..a8f749c 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -96,11 +96,14 @@ public class CommonEditor { void createHitReceivedEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModelInput, MODEL targetConditionsModelInput) { effect = e; createHitEffectPaneContent(listener, writable, e, sourceConditionsModelInput, targetConditionsModelInput); - - hitReceivedEffectHPMinTarget = addIntegerField(effectPane, "Attacker HP bonus min%s: ".formatted(applyToTargetHint), effect.target.hp_boost_min, true, writable, listener); - hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, "Attacker HP bonus max%s: ".formatted(applyToTargetHint), effect.target.hp_boost_max, true, writable, listener); - hitReceivedEffectAPMinTarget = addIntegerField(effectPane, "Attacker AP bonus min%s: ".formatted(applyToTargetHint), effect.target.ap_boost_min, true, writable, listener); - hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, "Attacker AP bonus max%s: ".formatted(applyToTargetHint), effect.target.ap_boost_max, true, writable, listener); + } + @Override + protected void addFields(FieldUpdateListener listener, boolean writable) { + super.addFields(listener, writable); + hitReceivedEffectHPMinTarget = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToTargetHint), effect.target.hp_boost_min, true, writable, listener); + hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToTargetHint), effect.target.hp_boost_max, true, writable, listener); + hitReceivedEffectAPMinTarget = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToTargetHint), effect.target.ap_boost_min, true, writable, listener); + hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToTargetHint), effect.target.ap_boost_max, true, writable, listener); } } @@ -130,6 +133,12 @@ public class CommonEditor { public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { super(title, sourceNewSupplier, editor, applyToHint); this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; + + if (applyToTargetHint == null || applyToTargetHint == "") { + applyToTargetHint = ""; + } else { + applyToTargetHint = " (%s)".formatted(applyToTargetHint); + } this.applyToTargetHint = applyToTargetHint; } @@ -143,7 +152,7 @@ public class CommonEditor { protected void addLists(FieldUpdateListener listener, boolean writable) { super.addLists(listener, writable); - String titleTarget = "Actor Conditions applied to the target: "; + String titleTarget = "Actor Conditions applied to the target%s: ".formatted(applyToTargetHint); CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; From 7eb60117c40504f6be4b026abe3f7f33f0e8bab7 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 22:09:45 +0200 Subject: [PATCH 68/94] fix bug in writeMinMaxToMap --- src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index c85d383..6336870 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -67,7 +67,7 @@ public final class Common { if (min != null || max != null) { Map minMaxMap = new LinkedHashMap(); parent.put(key, minMaxMap); - writeMinMaxToMap(parent, min, max, defaultValue); + writeMinMaxToMap(minMaxMap, min, max, defaultValue); } } public static void writeDescriptionToMap(Map parent, String description) { From de2b47821be3aaafd7f7af9ed52a34a3558d3cd2 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Mon, 23 Jun 2025 22:12:16 +0200 Subject: [PATCH 69/94] add TODOs that need to be done before finishing. --- DEDUP-TODO.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 DEDUP-TODO.md diff --git a/DEDUP-TODO.md b/DEDUP-TODO.md new file mode 100644 index 0000000..55bd346 --- /dev/null +++ b/DEDUP-TODO.md @@ -0,0 +1,8 @@ +# TODOs I still have before I can create a PR +## this is not a List of things i should do, but what HAS to be done. + +There are probably a lot of things that could be optimized, which will not be on this list +(which will probably also be done, they are just not important enough to track them) + + +- check, why for example the "Forever" button is active for not altered entities (ex.: NPC->hitEffect) if they have a condition already there From 56242e85f28c3d85240feb1806507c30dd8ba32d Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 14:44:45 +0200 Subject: [PATCH 70/94] check TODOs --- DEDUP-TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DEDUP-TODO.md b/DEDUP-TODO.md index 55bd346..f3c5160 100644 --- a/DEDUP-TODO.md +++ b/DEDUP-TODO.md @@ -6,3 +6,5 @@ There are probably a lot of things that could be optimized, which will not be on - check, why for example the "Forever" button is active for not altered entities (ex.: NPC->hitEffect) if they have a condition already there + - apparently that's always been like that... (or at least on the most recent main branch) + From 127ed760060e515c2c353ca3c026a41cd2dd2a00 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 14:53:59 +0200 Subject: [PATCH 71/94] improve isNull check --- .../model/gamedata/Common.java | 26 +++++++++++++ .../ui/gamedataeditors/NPCEditor.java | 38 ++----------------- 2 files changed, 29 insertions(+), 35 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 6336870..4b9987a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -270,21 +270,47 @@ public final class Common { public Integer hp_boost_max = null; public Integer ap_boost_min = null; public Integer ap_boost_max = null; + + public boolean isNull() { + if (ap_boost_min != null) return false; + if (ap_boost_max != null) return false; + if (hp_boost_min != null) return false; + if (hp_boost_max != null) return false; + return true; + } } public static class DeathEffect extends BasicEffect { //Available from parsed state public List conditions_source = null; + @Override + public boolean isNull(){ + if(!super.isNull()) return false; + if (conditions_source != null) return false; + return true; + } } public static class HitEffect extends DeathEffect { //Available from parsed state public List conditions_target = null; + @Override + public boolean isNull(){ + if(!super.isNull()) return false; + if (conditions_target != null) return false; + return true; + } } public static class HitReceivedEffect extends Common.HitEffect { //Available from parsed state public BasicEffect target = new BasicEffect(); + @Override + public boolean isNull(){ + if(!super.isNull()) return false; + if (!target.isNull()) return false; + return true; + } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index c659962..7f33bb9 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -212,38 +212,6 @@ public class NPCEditor extends JSONElementEditor { } } - public static boolean isNull(Common.HitEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - public static boolean isNull(Common.HitReceivedEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.target.ap_boost_min != null) return false; - if (effect.target.ap_boost_max != null) return false; - if (effect.target.hp_boost_min != null) return false; - if (effect.target.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - public static boolean isNull(Common.DeathEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - return true; - } public class NPCFieldUpdater implements FieldUpdateListener { @@ -346,21 +314,21 @@ public class NPCEditor extends JSONElementEditor { } if (updateHit) { - if (isNull(hitEffectPane.effect)) { + if (hitEffectPane.effect.isNull()) { npc.hit_effect = null; } else { npc.hit_effect = hitEffectPane.effect; } } if (updateHitReceived) { - if (isNull(hitEffectPane.effect)) { + if (hitEffectPane.effect.isNull()) { npc.hit_received_effect = null; } else { npc.hit_received_effect = hitReceivedEffectPane.effect; } } if (updateDeath) { - if (isNull(deathEffectPane. effect)) { + if (deathEffectPane.effect.isNull()) { npc.death_effect = null; } else { npc.death_effect = deathEffectPane. effect; From 18b92a3921fe64f7a3a4ac20f717db6145e4ccab Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 15:16:36 +0200 Subject: [PATCH 72/94] add valueChanged override for HitRecievedEffectPane --- .../ui/gamedataeditors/CommonEditor.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index a8f749c..b39f393 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -105,6 +105,29 @@ public class CommonEditor { hitReceivedEffectAPMinTarget = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToTargetHint), effect.target.ap_boost_min, true, writable, listener); hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToTargetHint), effect.target.ap_boost_max, true, writable, listener); } + + + @Override + public boolean valueChanged(JComponent source, Object value, GameDataElement backlink) { + boolean updateHitReceived = super.valueChanged(source, value, backlink); + if (!updateHitReceived) { + if (source == hitReceivedEffectHPMinTarget) { + effect.target.hp_boost_min = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectHPMaxTarget) { + effect.target.hp_boost_max = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMinTarget) { + effect.target.ap_boost_min = (Integer) value; + updateHitReceived = true; + } else if (source == hitReceivedEffectAPMaxTarget) { + effect.target.ap_boost_max = (Integer) value; + updateHitReceived = true; + } + } + + return updateHitReceived; + } } public static class HitEffectPane> extends DeathEffectPane { From ec04b810d9b150ee4e61102c55bc56a9a1285ded Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 15:23:44 +0200 Subject: [PATCH 73/94] fix bug --- .../gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 7f33bb9..30aa4ab 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -321,7 +321,7 @@ public class NPCEditor extends JSONElementEditor { } } if (updateHitReceived) { - if (hitEffectPane.effect.isNull()) { + if (hitReceivedEffectPane.effect.isNull()) { npc.hit_received_effect = null; } else { npc.hit_received_effect = hitReceivedEffectPane.effect; From 62ed795fed2077f955ba910cfb1602664b7e1b55 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 15:38:41 +0200 Subject: [PATCH 74/94] add codeStyle to git --- .idea/codeStyles/Project.xml | 9 +++++++++ .idea/codeStyles/codeStyleConfig.xml | 5 +++++ 2 files changed, 14 insertions(+) create mode 100644 .idea/codeStyles/Project.xml create mode 100644 .idea/codeStyles/codeStyleConfig.xml diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..386fbca --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file From 6dcd8599b32dda7d0cfb8346c4a34c3c804e28ea Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 15:38:55 +0200 Subject: [PATCH 75/94] reformat CommonEditor --- .../ui/gamedataeditors/CommonEditor.java | 127 +++++++++--------- 1 file changed, 65 insertions(+), 62 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index b39f393..1d81c9a 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -27,8 +27,7 @@ public class CommonEditor { @Override public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel) c); + if (c instanceof JLabel label) { Common.TimedActorConditionEffect effect = (Common.TimedActorConditionEffect) value; if (effect.condition != null) { @@ -39,13 +38,16 @@ public class CommonEditor { if (clear) { label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance + "% chances to clear actor condition " + effect.condition.getDesc()); + label.setText( + effect.chance + "% chances to clear actor condition " + effect.condition.getDesc()); } else if (immunity) { label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); - label.setText(effect.chance + "% chances to give immunity to " + effect.condition.getDesc() + (forever ? " forever" : " for " + effect.duration + " rounds")); + label.setText( + effect.chance + "% chances to give immunity to " + effect.condition.getDesc() + (forever ? " forever" : " for " + effect.duration + " rounds")); } else { label.setIcon(new ImageIcon(effect.condition.getIcon())); - label.setText(effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); + label.setText( + effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); } } else { label.setText("New, undefined actor condition effect."); @@ -61,8 +63,7 @@ public class CommonEditor { @Override public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel) { - JLabel label = ((JLabel) c); + if (c instanceof JLabel label) { Common.ActorConditionEffect effect = (Common.ActorConditionEffect) value; if (effect.condition != null) { @@ -97,13 +98,18 @@ public class CommonEditor { effect = e; createHitEffectPaneContent(listener, writable, e, sourceConditionsModelInput, targetConditionsModelInput); } + @Override protected void addFields(FieldUpdateListener listener, boolean writable) { super.addFields(listener, writable); - hitReceivedEffectHPMinTarget = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToTargetHint), effect.target.hp_boost_min, true, writable, listener); - hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToTargetHint), effect.target.hp_boost_max, true, writable, listener); - hitReceivedEffectAPMinTarget = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToTargetHint), effect.target.ap_boost_min, true, writable, listener); - hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToTargetHint), effect.target.ap_boost_max, true, writable, listener); + hitReceivedEffectHPMinTarget = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToTargetHint), + effect.target.hp_boost_min, true, writable, listener); + hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToTargetHint), + effect.target.hp_boost_max, true, writable, listener); + hitReceivedEffectAPMinTarget = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToTargetHint), + effect.target.ap_boost_min, true, writable, listener); + hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToTargetHint), + effect.target.ap_boost_max, true, writable, listener); } @@ -180,21 +186,14 @@ public class CommonEditor { BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; BasicLambda selectedResetTarget = () -> selectedHitEffectTargetCondition = null; - BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener, this.editor); + BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane( + editorPane, selectedHitEffectTargetCondition, listener, this.editor); - var resultTarget = UiUtils.getCollapsibleItemList(listener, - hitTargetConditionsListModel, - selectedResetTarget, - selectedSetTarget, - selectedGetTarget, - (x) -> { - }, - updatePaneTarget, - writable, - this.conditionSupplier, - cellRendererTarget, - titleTarget, - (x) -> null); + var resultTarget = UiUtils.getCollapsibleItemList(listener, hitTargetConditionsListModel, + selectedResetTarget, selectedSetTarget, selectedGetTarget, + (x) -> { + }, updatePaneTarget, writable, this.conditionSupplier, + cellRendererTarget, titleTarget, (x) -> null); hitTargetConditionsList = resultTarget.list; CollapsiblePanel hitTargetConditionsPane = resultTarget.collapsiblePanel; if (effect == null || effect.conditions_target == null || effect.conditions_target.isEmpty()) { @@ -212,13 +211,16 @@ public class CommonEditor { boolean writable = e.target.writable; Project proj = e.target.getProject(); - hitTargetConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitTargetConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + hitTargetConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, + writable, listener); + hitTargetConditionChance = Editor.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); hitTargetConditionClear = new JRadioButton("Clear active condition"); pane.add(hitTargetConditionClear, JideBoxLayout.FIX); hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", + condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, + 1, false, writable, listener); hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); @@ -229,7 +231,8 @@ public class CommonEditor { hitTargetConditionTimed = new JRadioButton("For a number of rounds"); pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, + listener); hitTargetConditionForever = new JRadioButton("Forever"); pane.add(hitTargetConditionForever, JideBoxLayout.FIX); @@ -242,32 +245,32 @@ public class CommonEditor { hitTargetConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, new Boolean(hitTargetConditionClear.isSelected())); + listener.valueChanged(hitTargetConditionClear, hitTargetConditionClear.isSelected()); } }); hitTargetConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, new Boolean(hitTargetConditionApply.isSelected())); + listener.valueChanged(hitTargetConditionApply, hitTargetConditionApply.isSelected()); } }); hitTargetConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, new Boolean(hitTargetConditionImmunity.isSelected())); + listener.valueChanged(hitTargetConditionImmunity, hitTargetConditionImmunity.isSelected()); } }); hitTargetConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, new Boolean(hitTargetConditionTimed.isSelected())); + listener.valueChanged(hitTargetConditionTimed, hitTargetConditionTimed.isSelected()); } }); hitTargetConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, new Boolean(hitTargetConditionForever.isSelected())); + listener.valueChanged(hitTargetConditionForever, hitTargetConditionForever.isSelected()); } }); pane.revalidate(); @@ -298,7 +301,8 @@ public class CommonEditor { if (source == hitTargetConditionsList) { updateHit = true; } else if (source == hitTargetConditionBox) { - editor.updateConditionEffect((ActorCondition) value, backlink, selectedHitEffectTargetCondition, hitTargetConditionsListModel); + editor.updateConditionEffect((ActorCondition) value, backlink, selectedHitEffectTargetCondition, + hitTargetConditionsListModel); } else if (source == hitTargetConditionClear && (Boolean) value) { selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; selectedHitEffectTargetCondition.duration = null; @@ -409,10 +413,14 @@ public class CommonEditor { } protected void addFields(FieldUpdateListener listener, boolean writable) { - effectHPMin = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToHint), effect.hp_boost_min, true, writable, listener); - effectHPMax = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToHint), effect.hp_boost_max, true, writable, listener); - effectAPMin = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToHint), effect.ap_boost_min, true, writable, listener); - effectAPMax = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToHint), effect.ap_boost_max, true, writable, listener); + effectHPMin = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToHint), effect.hp_boost_min, + true, writable, listener); + effectHPMax = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToHint), effect.hp_boost_max, + true, writable, listener); + effectAPMin = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToHint), effect.ap_boost_min, + true, writable, listener); + effectAPMax = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToHint), effect.ap_boost_max, + true, writable, listener); } protected void addLists(FieldUpdateListener listener, boolean writable) { @@ -421,21 +429,12 @@ public class CommonEditor { BasicLambdaWithArg selectedSetSource = (value) -> selectedEffectSourceCondition = value; BasicLambdaWithReturn selectedGetSource = () -> selectedEffectSourceCondition; BasicLambda selectedResetSource = () -> selectedEffectSourceCondition = null; - BasicLambdaWithArg updatePaneSource = (editorPane) -> updateEffectSourceTimedConditionEditorPane(editorPane, selectedEffectSourceCondition, listener, editor); + BasicLambdaWithArg updatePaneSource = (editorPane) -> updateEffectSourceTimedConditionEditorPane( + editorPane, selectedEffectSourceCondition, listener, editor); - var resultSource = UiUtils.getCollapsibleItemList(listener, - this.sourceConditionsModel, - selectedResetSource, - selectedSetSource, - selectedGetSource, - (x) -> { - }, - updatePaneSource, - writable, - conditionSupplier, - cellRendererSource, - titleSource, - (x) -> null); + var resultSource = UiUtils.getCollapsibleItemList(listener, this.sourceConditionsModel, selectedResetSource, + selectedSetSource, selectedGetSource, (x) -> { + }, updatePaneSource, writable, conditionSupplier, cellRendererSource, titleSource, (x) -> null); sourceConditionsList = resultSource.list; CollapsiblePanel sourceConditionsPane = resultSource.collapsiblePanel; if (effect == null || effect.conditions_source == null || effect.conditions_source.isEmpty()) { @@ -453,14 +452,17 @@ public class CommonEditor { boolean writable = e.target.writable; Project proj = e.target.getProject(); - sourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - sourceConditionChance = e.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + sourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, + listener); + sourceConditionChance = Editor.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); sourceConditionClear = new JRadioButton("Clear active condition"); pane.add(sourceConditionClear, JideBoxLayout.FIX); sourceConditionApply = new JRadioButton("Apply condition with magnitude"); pane.add(sourceConditionApply, JideBoxLayout.FIX); - sourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); + sourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", + condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, + 1, false, writable, listener); sourceConditionImmunity = new JRadioButton("Give immunity to condition"); pane.add(sourceConditionImmunity, JideBoxLayout.FIX); @@ -471,7 +473,8 @@ public class CommonEditor { sourceConditionTimed = new JRadioButton("For a number of rounds"); pane.add(sourceConditionTimed, JideBoxLayout.FIX); - sourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); + sourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, + listener); sourceConditionForever = new JRadioButton("Forever"); pane.add(sourceConditionForever, JideBoxLayout.FIX); @@ -484,32 +487,32 @@ public class CommonEditor { sourceConditionClear.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionClear, new Boolean(sourceConditionClear.isSelected())); + listener.valueChanged(sourceConditionClear, sourceConditionClear.isSelected()); } }); sourceConditionApply.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionApply, new Boolean(sourceConditionApply.isSelected())); + listener.valueChanged(sourceConditionApply, sourceConditionApply.isSelected()); } }); sourceConditionImmunity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionImmunity, new Boolean(sourceConditionImmunity.isSelected())); + listener.valueChanged(sourceConditionImmunity, sourceConditionImmunity.isSelected()); } }); sourceConditionTimed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionTimed, new Boolean(sourceConditionTimed.isSelected())); + listener.valueChanged(sourceConditionTimed, sourceConditionTimed.isSelected()); } }); sourceConditionForever.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionForever, new Boolean(sourceConditionForever.isSelected())); + listener.valueChanged(sourceConditionForever, sourceConditionForever.isSelected()); } }); pane.revalidate(); From b7e9bf0582ec937824595478de492e433c0fdec1 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 16:07:50 +0200 Subject: [PATCH 76/94] move ListModels to CommonEditor for re-use --- .../ui/gamedataeditors/CommonEditor.java | 38 +++++++++++++++++++ .../ui/gamedataeditors/NPCEditor.java | 37 ++---------------- 2 files changed, 41 insertions(+), 34 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 1d81c9a..19b8498 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -15,6 +15,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.util.List; import java.util.function.Supplier; import static com.gpl.rpg.atcontentstudio.ui.Editor.addIntegerField; @@ -617,4 +618,41 @@ public class CommonEditor { return updateHit; } } + + + //region list-models + + public static class TargetTimedConditionsListModel extends OrderedListenerListModel { + public TargetTimedConditionsListModel(Common.HitEffect effect) { + super(effect); + } + + @Override + protected java.util.List getItems() { + return source.conditions_target; + } + + @Override + protected void setItems(java.util.List items) { + source.conditions_target = items; + } + } + + public static class SourceTimedConditionsListModel extends OrderedListenerListModel { + public SourceTimedConditionsListModel(Common.DeathEffect effect) { + super(effect); + } + + @Override + protected java.util.List getItems() { + return source.conditions_source; + } + + @Override + protected void setItems(List items) { + source.conditions_source = items; + } + } + + //endregion } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 30aa4ab..32fe94b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -151,7 +151,7 @@ public class NPCEditor extends JSONElementEditor { } if (hitEffectPane == null) hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); - hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new SourceTimedConditionsListModel(hitEffect), new TargetTimedConditionsListModel(hitEffect)); + hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new CommonEditor.SourceTimedConditionsListModel(hitEffect), new CommonEditor.TargetTimedConditionsListModel(hitEffect)); combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); Common.HitReceivedEffect hitReceivedEffect; @@ -162,7 +162,7 @@ public class NPCEditor extends JSONElementEditor { } if (hitReceivedEffectPane == null) hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, "NPC", "Attacker"); - hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, new SourceTimedConditionsListModel(hitReceivedEffect), new TargetTimedConditionsListModel(hitReceivedEffect)); + hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, new CommonEditor.SourceTimedConditionsListModel(hitReceivedEffect), new CommonEditor.TargetTimedConditionsListModel(hitReceivedEffect)); combatTraitPane.add(hitReceivedEffectPane.effectPane, JideBoxLayout.FIX); Common.DeathEffect deathEffect; @@ -173,44 +173,13 @@ public class NPCEditor extends JSONElementEditor { } if (deathEffectPane == null) deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", Common.TimedActorConditionEffect::new, this, "Killer"); - deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, deathEffect, new SourceTimedConditionsListModel(deathEffect) + deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, deathEffect, new CommonEditor.SourceTimedConditionsListModel(deathEffect) ); combatTraitPane.add(deathEffectPane.effectPane, JideBoxLayout.FIX); pane.add(combatTraitPane, JideBoxLayout.FIX); } - public static class TargetTimedConditionsListModel extends OrderedListenerListModel { - public TargetTimedConditionsListModel(Common.HitEffect effect) { - super(effect); - } - - @Override - protected List getItems() { - return source.conditions_target; - } - - @Override - protected void setItems(List items) { - source.conditions_target = items; - } - } - - public static class SourceTimedConditionsListModel extends OrderedListenerListModel { - public SourceTimedConditionsListModel(Common.DeathEffect effect) { - super(effect); - } - - @Override - protected List getItems() { - return source.conditions_source; - } - - @Override - protected void setItems(List items) { - source.conditions_source = items; - } - } public class NPCFieldUpdater implements FieldUpdateListener { From 2dbe881dd700c117207389ff640ac83f0a109213 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 16:08:25 +0200 Subject: [PATCH 77/94] change ItemEditor to use *EffectPane classes --- .../ui/gamedataeditors/ItemEditor.java | 1231 +---------------- 1 file changed, 54 insertions(+), 1177 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 9692fd8..b2686c7 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -14,7 +14,6 @@ import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; -import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; @@ -32,11 +31,6 @@ public class ItemEditor extends JSONElementEditor { private Common.ActorConditionEffect selectedEquipEffectCondition; - private Common.TimedActorConditionEffect selectedHitEffectSourceCondition; - private Common.TimedActorConditionEffect selectedHitEffectTargetCondition; - private Common.TimedActorConditionEffect selectedKillEffectCondition; - private Common.TimedActorConditionEffect selectedHitReceivedEffectSourceCondition; - private Common.TimedActorConditionEffect selectedHitReceivedEffectTargetCondition; private JButton itemIcon; @@ -66,7 +60,7 @@ public class ItemEditor extends JSONElementEditor { private JSpinner equipIncUseCost; private JSpinner equipIncReequipCost; private JSpinner equipIncAttackCost; - private ConditionsListModel equipConditionsModel; + private EquipConditionsListModel equipConditionsModel; @SuppressWarnings("rawtypes") private JList equipConditionsList; private MyComboBox equipConditionBox; @@ -74,90 +68,9 @@ public class ItemEditor extends JSONElementEditor { private JRadioButton equipConditionImmunity; private JSpinner equipConditionMagnitude; - private CollapsiblePanel hitEffectPane; - private Common.HitEffect hitEffect; - private JSpinner hitHPMin; - private JSpinner hitHPMax; - private JSpinner hitAPMin; - private JSpinner hitAPMax; - private SourceTimedConditionsListModel hitSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitSourceConditionsList; - private MyComboBox hitSourceConditionBox; - private JSpinner hitSourceConditionChance; - private JRadioButton hitSourceConditionClear; - private JRadioButton hitSourceConditionApply; - private JRadioButton hitSourceConditionImmunity; - private JSpinner hitSourceConditionMagnitude; - private JRadioButton hitSourceConditionTimed; - private JRadioButton hitSourceConditionForever; - private JSpinner hitSourceConditionDuration; - private TargetTimedConditionsListModel hitTargetConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitTargetConditionsList; - private MyComboBox hitTargetConditionBox; - private JSpinner hitTargetConditionChance; - private JRadioButton hitTargetConditionClear; - private JRadioButton hitTargetConditionApply; - private JRadioButton hitTargetConditionImmunity; - private JSpinner hitTargetConditionMagnitude; - private JRadioButton hitTargetConditionTimed; - private JRadioButton hitTargetConditionForever; - private JSpinner hitTargetConditionDuration; - - private CollapsiblePanel killEffectPane; - private Common.DeathEffect killEffect; - private JSpinner killHPMin; - private JSpinner killHPMax; - private JSpinner killAPMin; - private JSpinner killAPMax; - private SourceTimedConditionsListModel killSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList killSourceConditionsList; - private MyComboBox killSourceConditionBox; - private JSpinner killSourceConditionChance; - private JRadioButton killSourceConditionClear; - private JRadioButton killSourceConditionApply; - private JRadioButton killSourceConditionImmunity; - private JSpinner killSourceConditionMagnitude; - private JRadioButton killSourceConditionTimed; - private JRadioButton killSourceConditionForever; - private JSpinner killSourceConditionDuration; - - private CollapsiblePanel hitReceivedEffectPane; - private Common.HitReceivedEffect hitReceivedEffect; - private JSpinner hitReceivedHPMin; - private JSpinner hitReceivedHPMax; - private JSpinner hitReceivedAPMin; - private JSpinner hitReceivedAPMax; - private JSpinner hitReceivedHPMinTarget; - private JSpinner hitReceivedHPMaxTarget; - private JSpinner hitReceivedAPMinTarget; - private JSpinner hitReceivedAPMaxTarget; - private SourceTimedConditionsListModel hitReceivedSourceConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedSourceConditionsList; - private MyComboBox hitReceivedSourceConditionBox; - private JSpinner hitReceivedSourceConditionChance; - private JRadioButton hitReceivedSourceConditionClear; - private JRadioButton hitReceivedSourceConditionApply; - private JRadioButton hitReceivedSourceConditionImmunity; - private JSpinner hitReceivedSourceConditionMagnitude; - private JRadioButton hitReceivedSourceConditionTimed; - private JRadioButton hitReceivedSourceConditionForever; - private JSpinner hitReceivedSourceConditionDuration; - private TargetTimedConditionsListModel hitReceivedTargetConditionsModel; - @SuppressWarnings("rawtypes") - private JList hitReceivedTargetConditionsList; - private MyComboBox hitReceivedTargetConditionBox; - private JSpinner hitReceivedTargetConditionChance; - private JRadioButton hitReceivedTargetConditionClear; - private JRadioButton hitReceivedTargetConditionApply; - private JRadioButton hitReceivedTargetConditionImmunity; - private JSpinner hitReceivedTargetConditionMagnitude; - private JRadioButton hitReceivedTargetConditionTimed; - private JRadioButton hitReceivedTargetConditionForever; - private JSpinner hitReceivedTargetConditionDuration; + private CommonEditor.HitEffectPane hitEffectPane; + private CommonEditor.DeathEffectPane killEffectPane; + private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane; public ItemEditor(Item item) { super(item, item.getDesc(), item.getIcon()); @@ -210,7 +123,7 @@ public class ItemEditor extends JSONElementEditor { equipIncAttackCost = addIntegerField(equipEffectPane, "Increase attack cost: ", equipEffect.increase_attack_cost, true, item.writable, listener); String titleEquipConditions = "Actor Conditions applied when equipped: "; - equipConditionsModel = new ConditionsListModel(equipEffect); + equipConditionsModel = new EquipConditionsListModel(equipEffect); CommonEditor.ConditionsCellRenderer cellRendererEquipConditions = new CommonEditor.ConditionsCellRenderer(); BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; @@ -240,508 +153,62 @@ public class ItemEditor extends JSONElementEditor { equipEffectPane.collapse(); } - hitEffectPane = new CollapsiblePanel("Effect on every hit: "); - hitEffectPane.setLayout(new JideBoxLayout(hitEffectPane, JideBoxLayout.PAGE_AXIS)); + Common.HitEffect hitEffect; if (item.hit_effect == null) { hitEffect = new Common.HitEffect(); } else { hitEffect = item.hit_effect; } - hitHPMin = addIntegerField(hitEffectPane, "HP bonus min: ", hitEffect.hp_boost_min, true, item.writable, listener); - hitHPMax = addIntegerField(hitEffectPane, "HP bonus max: ", hitEffect.hp_boost_max, true, item.writable, listener); - hitAPMin = addIntegerField(hitEffectPane, "AP bonus min: ", hitEffect.ap_boost_min, true, item.writable, listener); - hitAPMax = addIntegerField(hitEffectPane, "AP bonus max: ", hitEffect.ap_boost_max, true, item.writable, listener); + if (hitEffectPane == null) + hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); + hitEffectPane.createHitEffectPaneContent(listener, item.writable, hitEffect, new CommonEditor.SourceTimedConditionsListModel(hitEffect), new CommonEditor.TargetTimedConditionsListModel(hitEffect)); + pane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); - String title = "Actor Conditions applied to the source: "; - hitSourceConditionsModel = new SourceTimedConditionsListModel(hitEffect); - CommonEditor.TimedConditionsCellRenderer cellRenderer = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg setSelected = (selectedItem) -> selectedHitEffectSourceCondition = selectedItem; - BasicLambdaWithReturn getSelected = () -> hitSourceConditionsList.getSelectedValue(); - BasicLambda resetSelected = () -> selectedHitEffectSourceCondition = null; - BasicLambdaWithArg valueChanged = (selectedReply) -> { - }; - BasicLambdaWithArg updateEditorPane = (editorPane) -> updateHitSourceTimedConditionEditorPane(editorPane, selectedHitEffectSourceCondition, listener); - - var collapsibleItemList = UiUtils.getCollapsibleItemList( - listener, - hitSourceConditionsModel, - resetSelected, - setSelected, - getSelected, - valueChanged, - updateEditorPane, - item.writable, - Common.TimedActorConditionEffect::new, - cellRenderer, - title, - (x) -> null - ); - CollapsiblePanel hitSourceConditionsPane = collapsibleItemList.collapsiblePanel; - hitSourceConditionsList = collapsibleItemList.list; - if (item.hit_effect == null || item.hit_effect.conditions_source == null || item.hit_effect.conditions_source.isEmpty()) { - hitSourceConditionsPane.collapse(); - } - hitEffectPane.add(hitSourceConditionsPane, JideBoxLayout.FIX); - - String titleHitTargetConditions = "Actor Conditions applied to the target: "; - hitTargetConditionsModel = new TargetTimedConditionsListModel(hitEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererHitTargetConditions = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetHitTargetConditions = (value)->selectedHitEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetHitTargetConditions = ()->selectedHitEffectTargetCondition ; - BasicLambda selectedResetHitTargetConditions = ()->selectedHitEffectTargetCondition = null; - BasicLambdaWithArg updatePaneHitTargetConditions = (editorPane) -> updateHitTargetTimedConditionEditorPane(editorPane, selectedHitEffectTargetCondition, listener); - var resultHitTargetConditions = UiUtils.getCollapsibleItemList(listener, - hitTargetConditionsModel, - selectedResetHitTargetConditions, - selectedSetHitTargetConditions, - selectedGetHitTargetConditions, - (x) -> {}, - updatePaneHitTargetConditions, - item.writable, - Common.TimedActorConditionEffect::new, - cellRendererHitTargetConditions, - titleHitTargetConditions, - (x) -> null); - hitTargetConditionsList = resultHitTargetConditions.list; - CollapsiblePanel hitTargetConditionsPane = resultHitTargetConditions.collapsiblePanel; - if (item.hit_effect == null || item.hit_effect.conditions_target == null || item.hit_effect.conditions_target.isEmpty()) { - hitTargetConditionsPane.collapse(); - } - hitEffectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); - if (item.hit_effect == null) { - hitEffectPane.collapse(); - } - pane.add(hitEffectPane, JideBoxLayout.FIX); - - - killEffectPane = new CollapsiblePanel(killLabel); - killEffectPane.setLayout(new JideBoxLayout(killEffectPane, JideBoxLayout.PAGE_AXIS)); + Common.DeathEffect killEffect; if (item.kill_effect == null) { killEffect = new Common.DeathEffect(); } else { killEffect = item.kill_effect; } - killHPMin = addIntegerField(killEffectPane, "HP bonus min: ", killEffect.hp_boost_min, true, item.writable, listener); - killHPMax = addIntegerField(killEffectPane, "HP bonus max: ", killEffect.hp_boost_max, true, item.writable, listener); - killAPMin = addIntegerField(killEffectPane, "AP bonus min: ", killEffect.ap_boost_min, true, item.writable, listener); - killAPMax = addIntegerField(killEffectPane, "AP bonus max: ", killEffect.ap_boost_max, true, item.writable, listener); + if (killEffectPane == null) + killEffectPane = new CommonEditor.DeathEffectPane(killLabel, Common.TimedActorConditionEffect::new, this, null); + killEffectPane.createDeathEffectPaneContent(listener, item.writable, killEffect, new CommonEditor.SourceTimedConditionsListModel(killEffect)); + pane.add(killEffectPane.effectPane, JideBoxLayout.FIX); - String titleKillSourceConditions = "Actor Conditions applied to the source: "; - killSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererKillSourceConditions = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetKillSourceConditions = (value)->selectedKillEffectCondition = value; - BasicLambdaWithReturn selectedGetKillSourceConditions = ()->selectedKillEffectCondition ; - BasicLambda selectedResetKillSourceConditions = ()->selectedKillEffectCondition = null; - BasicLambdaWithArg updatePaneKillSourceConditions = (editorPane) -> updateKillSourceTimedConditionEditorPane(editorPane, selectedKillEffectCondition, listener); - var resultKillSourceConditions = UiUtils.getCollapsibleItemList(listener, - killSourceConditionsModel, - selectedResetKillSourceConditions, - selectedSetKillSourceConditions, - selectedGetKillSourceConditions, - (x) -> {}, - updatePaneKillSourceConditions, - item.writable, - Common.TimedActorConditionEffect::new, - cellRendererKillSourceConditions, - titleKillSourceConditions, - (x) -> null); - killSourceConditionsList = resultKillSourceConditions.list; - CollapsiblePanel killSourceConditionsPane = resultKillSourceConditions.collapsiblePanel; - if (item.kill_effect == null || item.kill_effect.conditions_source == null || item.kill_effect.conditions_source.isEmpty()) { - killSourceConditionsPane.collapse(); - } - killEffectPane.add(killSourceConditionsPane, JideBoxLayout.FIX); - - if (item.kill_effect == null) { - killEffectPane.collapse(); - } - pane.add(killEffectPane, JideBoxLayout.FIX); - - - hitReceivedEffectPane = new CollapsiblePanel("Effect on every hit received: "); - hitReceivedEffectPane.setLayout(new JideBoxLayout(hitReceivedEffectPane, JideBoxLayout.PAGE_AXIS)); + Common.HitReceivedEffect hitReceivedEffect; if (item.hit_received_effect == null) { hitReceivedEffect = new Common.HitReceivedEffect(); } else { hitReceivedEffect = item.hit_received_effect; } - hitReceivedHPMin = addIntegerField(hitReceivedEffectPane, "Player HP bonus min: ", hitReceivedEffect.hp_boost_min, true, item.writable, listener); - hitReceivedHPMax = addIntegerField(hitReceivedEffectPane, "Player HP bonus max: ", hitReceivedEffect.hp_boost_max, true, item.writable, listener); - hitReceivedAPMin = addIntegerField(hitReceivedEffectPane, "Player AP bonus min: ", hitReceivedEffect.ap_boost_min, true, item.writable, listener); - hitReceivedAPMax = addIntegerField(hitReceivedEffectPane, "Player AP bonus max: ", hitReceivedEffect.ap_boost_max, true, item.writable, listener); - String roleHitReceivedTarget = "Attacker"; - hitReceivedHPMinTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " HP bonus min: ", hitReceivedEffect.target.hp_boost_min, true, item.writable, listener); - hitReceivedHPMaxTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " HP bonus max: ", hitReceivedEffect.target.hp_boost_max, true, item.writable, listener); - hitReceivedAPMinTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " AP bonus min: ", hitReceivedEffect.target.ap_boost_min, true, item.writable, listener); - hitReceivedAPMaxTarget = addIntegerField(hitReceivedEffectPane, roleHitReceivedTarget + " AP bonus max: ", hitReceivedEffect.target.ap_boost_max, true, item.writable, listener); - - String titleHitReceivedSourceConditions = "Actor Conditions applied to the player: "; - hitReceivedSourceConditionsModel = new SourceTimedConditionsListModel(killEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererHitReceivedSourceConditions = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetHitReceivedSourceConditions = (value)->selectedHitReceivedEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition ; - BasicLambda selectedResetHitReceivedSourceConditions = ()->selectedHitReceivedEffectSourceCondition = null; - BasicLambdaWithArg updatePaneHitReceivedSourceConditions = (editorPane) -> updateHitReceivedSourceTimedConditionEditorPane(editorPane, selectedHitReceivedEffectSourceCondition, listener); - var resultHitReceivedSourceConditions = UiUtils.getCollapsibleItemList(listener, - hitReceivedSourceConditionsModel, - selectedResetHitReceivedSourceConditions, - selectedSetHitReceivedSourceConditions, - selectedGetHitReceivedSourceConditions, - (x) -> {}, - updatePaneHitReceivedSourceConditions, - item.writable, - Common.TimedActorConditionEffect::new, - cellRendererHitReceivedSourceConditions, - titleHitReceivedSourceConditions, - (x) -> null); - hitReceivedSourceConditionsList = resultHitReceivedSourceConditions.list; - CollapsiblePanel hitReceivedSourceConditionsPane = resultHitReceivedSourceConditions.collapsiblePanel; - if (item.hit_received_effect == null || item.hit_received_effect.conditions_source == null || item.hit_received_effect.conditions_source.isEmpty()) { - hitReceivedSourceConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedSourceConditionsPane, JideBoxLayout.FIX); - - String titleHitReceivedTargetConditions = "Actor Conditions applied to the attacker: "; - hitReceivedTargetConditionsModel = new TargetTimedConditionsListModel(hitReceivedEffect); - CommonEditor.TimedConditionsCellRenderer cellRendererHitReceivedTargetConditions = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetHitReceivedTargetConditions = (value)->selectedHitReceivedEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition ; - BasicLambda selectedResetHitReceivedTargetConditions = ()->selectedHitReceivedEffectTargetCondition = null; - BasicLambdaWithArg updatePaneHitReceivedTargetConditions = (editorPane) -> updateHitReceivedTargetTimedConditionEditorPane(editorPane, selectedHitReceivedEffectTargetCondition, listener); - var resultHitReceivedTargetConditions = UiUtils.getCollapsibleItemList(listener, - hitReceivedTargetConditionsModel, - selectedResetHitReceivedTargetConditions, - selectedSetHitReceivedTargetConditions, - selectedGetHitReceivedTargetConditions, - (x) -> {}, - updatePaneHitReceivedTargetConditions, - item.writable, - Common.TimedActorConditionEffect::new, - cellRendererHitReceivedTargetConditions, - titleHitReceivedTargetConditions, - (x) -> null); - hitReceivedTargetConditionsList = resultHitReceivedTargetConditions.list; - CollapsiblePanel hitReceivedTargetConditionsPane = resultHitReceivedTargetConditions.collapsiblePanel; - if (item.hit_received_effect == null || item.hit_received_effect.conditions_target == null || item.hit_received_effect.conditions_target.isEmpty()) { - hitReceivedTargetConditionsPane.collapse(); - } - hitReceivedEffectPane.add(hitReceivedTargetConditionsPane, JideBoxLayout.FIX); - - if (item.hit_received_effect == null) { - hitReceivedEffectPane.collapse(); - } - pane.add(hitReceivedEffectPane, JideBoxLayout.FIX); + if (hitReceivedEffectPane == null) + hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, null, null); + hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, item.writable, hitReceivedEffect, new CommonEditor.SourceTimedConditionsListModel(hitReceivedEffect), new CommonEditor.TargetTimedConditionsListModel(hitReceivedEffect)); + pane.add(killEffectPane.effectPane, JideBoxLayout.FIX); if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { equipEffectPane.setVisible(false); - hitEffectPane.setVisible(false); - killEffectPane.setVisible(false); + hitEffectPane.effectPane.setVisible(false); + killEffectPane.effectPane.setVisible(false); } else if (item.category.action_type == ItemCategory.ActionType.use) { equipEffectPane.setVisible(false); - hitEffectPane.setVisible(false); - killEffectPane.setVisible(true); - killEffectPane.setTitle(useLabel); - killEffectPane.revalidate(); - killEffectPane.repaint(); + hitEffectPane.effectPane.setVisible(false); + killEffectPane.effectPane.setVisible(true); + killEffectPane.effectPane.setTitle(useLabel); + killEffectPane.effectPane.revalidate(); + killEffectPane.effectPane.repaint(); } else if (item.category.action_type == ItemCategory.ActionType.equip) { equipEffectPane.setVisible(true); - hitEffectPane.setVisible(true); - killEffectPane.setVisible(true); - killEffectPane.setTitle(killLabel); - killEffectPane.revalidate(); - killEffectPane.repaint(); + hitEffectPane.effectPane.setVisible(true); + killEffectPane.effectPane.setVisible(true); + killEffectPane.effectPane.setTitle(killLabel); + killEffectPane.effectPane.revalidate(); + killEffectPane.effectPane.repaint(); } } - public void updateHitSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitSourceConditionBox != null) { - removeElementListener(hitSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item) target).writable; - Project proj = ((Item) target).getProject(); - - hitSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitSourceConditionClear, JideBoxLayout.FIX); - hitSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitSourceConditionApply, JideBoxLayout.FIX); - hitSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitSourceConditionApply); - radioEffectGroup.add(hitSourceConditionClear); - radioEffectGroup.add(hitSourceConditionImmunity); - - hitSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitSourceConditionTimed, JideBoxLayout.FIX); - hitSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitSourceConditionTimed); - radioDurationGroup.add(hitSourceConditionForever); - - updateHitSourceTimedConditionWidgets(condition); - - hitSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionClear, hitSourceConditionClear.isSelected()); - } - }); - hitSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionApply, hitSourceConditionApply.isSelected()); - } - }); - hitSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionImmunity, hitSourceConditionImmunity.isSelected()); - } - }); - - hitSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionTimed, hitSourceConditionTimed.isSelected()); - } - }); - hitSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitSourceConditionForever, hitSourceConditionForever.isSelected()); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitSourceConditionClear.setSelected(clear); - hitSourceConditionApply.setSelected(!clear && !immunity); - hitSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitSourceConditionImmunity.setSelected(immunity); - - hitSourceConditionTimed.setSelected(!forever); - hitSourceConditionTimed.setEnabled(!clear); - hitSourceConditionDuration.setEnabled(!clear && !forever); - hitSourceConditionForever.setSelected(forever); - hitSourceConditionForever.setEnabled(!clear); - } - - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitTargetConditionBox != null) { - removeElementListener(hitTargetConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item) target).writable; - Project proj = ((Item) target).getProject(); - - hitTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitTargetConditionClear, JideBoxLayout.FIX); - hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitTargetConditionApply); - radioEffectGroup.add(hitTargetConditionClear); - radioEffectGroup.add(hitTargetConditionImmunity); - - hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitTargetConditionTimed); - radioDurationGroup.add(hitTargetConditionForever); - - updateHitTargetTimedConditionWidgets(condition); - - hitTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, hitTargetConditionClear.isSelected()); - } - }); - hitTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, hitTargetConditionApply.isSelected()); - } - }); - hitTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, hitTargetConditionImmunity.isSelected()); - } - }); - - hitTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, hitTargetConditionTimed.isSelected()); - } - }); - hitTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, hitTargetConditionForever.isSelected()); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitTargetConditionClear.setSelected(clear); - hitTargetConditionApply.setSelected(!clear && !immunity); - hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitTargetConditionImmunity.setSelected(immunity); - - hitTargetConditionTimed.setSelected(!forever); - hitTargetConditionTimed.setEnabled(!clear); - hitTargetConditionDuration.setEnabled(!clear && !forever); - hitTargetConditionForever.setSelected(forever); - hitTargetConditionForever.setEnabled(!clear); - } - - public void updateKillSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (killSourceConditionBox != null) { - removeElementListener(killSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item) target).writable; - Project proj = ((Item) target).getProject(); - - killSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - killSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - killSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(killSourceConditionClear, JideBoxLayout.FIX); - killSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(killSourceConditionApply, JideBoxLayout.FIX); - killSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - killSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(killSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(killSourceConditionApply); - radioEffectGroup.add(killSourceConditionClear); - radioEffectGroup.add(killSourceConditionImmunity); - - killSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(killSourceConditionTimed, JideBoxLayout.FIX); - killSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - killSourceConditionForever = new JRadioButton("Forever"); - pane.add(killSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(killSourceConditionTimed); - radioDurationGroup.add(killSourceConditionForever); - - updateKillSourceTimedConditionWidgets(condition); - - killSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionClear, killSourceConditionClear.isSelected()); - } - }); - killSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionApply, killSourceConditionApply.isSelected()); - } - }); - killSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionImmunity, killSourceConditionImmunity.isSelected()); - } - }); - - killSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionTimed, killSourceConditionTimed.isSelected()); - } - }); - killSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(killSourceConditionForever, killSourceConditionForever.isSelected()); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateKillSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - killSourceConditionClear.setSelected(clear); - killSourceConditionApply.setSelected(!clear && !immunity); - killSourceConditionMagnitude.setEnabled(!clear && !immunity); - killSourceConditionImmunity.setSelected(immunity); - - killSourceConditionTimed.setSelected(!forever); - killSourceConditionTimed.setEnabled(!clear); - killSourceConditionDuration.setEnabled(!clear && !forever); - killSourceConditionForever.setSelected(forever); - killSourceConditionForever.setEnabled(!clear); - } - public void updateEquipConditionEditorPane(JPanel pane, Common.ActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (equipConditionBox != null) { @@ -790,233 +257,8 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public void updateHitReceivedSourceTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedSourceConditionBox != null) { - removeElementListener(hitReceivedSourceConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item) target).writable; - Project proj = ((Item) target).getProject(); - - hitReceivedSourceConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedSourceConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedSourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedSourceConditionClear, JideBoxLayout.FIX); - hitReceivedSourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedSourceConditionApply, JideBoxLayout.FIX); - hitReceivedSourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedSourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedSourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedSourceConditionApply); - radioEffectGroup.add(hitReceivedSourceConditionClear); - radioEffectGroup.add(hitReceivedSourceConditionImmunity); - - hitReceivedSourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedSourceConditionTimed, JideBoxLayout.FIX); - hitReceivedSourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedSourceConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedSourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedSourceConditionTimed); - radioDurationGroup.add(hitReceivedSourceConditionForever); - - updateHitReceivedSourceTimedConditionWidgets(condition); - - hitReceivedSourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionClear, hitReceivedSourceConditionClear.isSelected()); - } - }); - hitReceivedSourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionApply, hitReceivedSourceConditionApply.isSelected()); - } - }); - hitReceivedSourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionImmunity, hitReceivedSourceConditionImmunity.isSelected()); - } - }); - - hitReceivedSourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionTimed, hitReceivedSourceConditionTimed.isSelected()); - } - }); - hitReceivedSourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedSourceConditionForever, hitReceivedSourceConditionForever.isSelected()); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedSourceTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitReceivedSourceConditionClear.setSelected(clear); - hitReceivedSourceConditionApply.setSelected(!clear && !immunity); - hitReceivedSourceConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedSourceConditionImmunity.setSelected(immunity); - - hitReceivedSourceConditionTimed.setSelected(!forever); - hitReceivedSourceConditionTimed.setEnabled(!clear); - hitReceivedSourceConditionDuration.setEnabled(!clear && !forever); - hitReceivedSourceConditionForever.setSelected(forever); - hitReceivedSourceConditionForever.setEnabled(!clear); - } - - public void updateHitReceivedTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener) { - pane.removeAll(); - if (hitReceivedTargetConditionBox != null) { - removeElementListener(hitReceivedTargetConditionBox); - } - if (condition == null) { - pane.revalidate(); - pane.repaint(); - return; - } - - boolean writable = ((Item) target).writable; - Project proj = ((Item) target).getProject(); - - hitReceivedTargetConditionBox = addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); - hitReceivedTargetConditionChance = addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - hitReceivedTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitReceivedTargetConditionClear, JideBoxLayout.FIX); - hitReceivedTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitReceivedTargetConditionApply, JideBoxLayout.FIX); - hitReceivedTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, 1, false, writable, listener); - hitReceivedTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitReceivedTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitReceivedTargetConditionApply); - radioEffectGroup.add(hitReceivedTargetConditionClear); - radioEffectGroup.add(hitReceivedTargetConditionImmunity); - - hitReceivedTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitReceivedTargetConditionTimed, JideBoxLayout.FIX); - hitReceivedTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, listener); - hitReceivedTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitReceivedTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitReceivedTargetConditionTimed); - radioDurationGroup.add(hitReceivedTargetConditionForever); - - updateHitReceivedTargetTimedConditionWidgets(condition); - - hitReceivedTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionClear, hitReceivedTargetConditionClear.isSelected()); - } - }); - hitReceivedTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionApply, hitReceivedTargetConditionApply.isSelected()); - } - }); - hitReceivedTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionImmunity, hitReceivedTargetConditionImmunity.isSelected()); - } - }); - - hitReceivedTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionTimed, hitReceivedTargetConditionTimed.isSelected()); - } - }); - hitReceivedTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitReceivedTargetConditionForever, hitReceivedTargetConditionForever.isSelected()); - } - }); - - pane.revalidate(); - pane.repaint(); - } - - public void updateHitReceivedTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitReceivedTargetConditionClear.setSelected(clear); - hitReceivedTargetConditionApply.setSelected(!clear && !immunity); - hitReceivedTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitReceivedTargetConditionImmunity.setSelected(immunity); - - hitReceivedTargetConditionTimed.setSelected(!forever); - hitReceivedTargetConditionTimed.setEnabled(!clear); - hitReceivedTargetConditionDuration.setEnabled(!clear && !forever); - hitReceivedTargetConditionForever.setSelected(forever); - hitReceivedTargetConditionForever.setEnabled(!clear); - } - - - public static class SourceTimedConditionsListModel extends OrderedListenerListModel { - public SourceTimedConditionsListModel(Common.DeathEffect effect) { - super(effect); - } - - @Override - protected List getItems() { - return source.conditions_source; - } - - @Override - protected void setItems(List items) { - source.conditions_source = items; - } - } - - public static class TargetTimedConditionsListModel extends OrderedListenerListModel { - public TargetTimedConditionsListModel(Common.HitEffect effect) { - super(effect); - } - - @Override - protected List getItems() { - return source.conditions_target; - } - - @Override - protected void setItems(List items) { - source.conditions_target = items; - } - } - - public static class ConditionsListModel extends OrderedListenerListModel { - public ConditionsListModel(Item.EquipEffect equipEffect) { + public static class EquipConditionsListModel extends OrderedListenerListModel { + public EquipConditionsListModel(Item.EquipEffect equipEffect) { super(equipEffect); } @@ -1031,7 +273,6 @@ public class ItemEditor extends JSONElementEditor { } } - public static boolean isNull(Item.EquipEffect effect) { if (effect.conditions != null) return false; if (effect.critical_multiplier != null) return false; @@ -1051,42 +292,6 @@ public class ItemEditor extends JSONElementEditor { return true; } - - public static boolean isNull(Common.HitEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - - public static boolean isNull(Common.DeathEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - return true; - } - - public static boolean isNull(Common.HitReceivedEffect effect) { - if (effect.ap_boost_min != null) return false; - if (effect.ap_boost_max != null) return false; - if (effect.hp_boost_min != null) return false; - if (effect.hp_boost_max != null) return false; - if (effect.target.ap_boost_min != null) return false; - if (effect.target.ap_boost_max != null) return false; - if (effect.target.hp_boost_min != null) return false; - if (effect.target.hp_boost_max != null) return false; - if (effect.conditions_source != null) return false; - if (effect.conditions_target != null) return false; - return true; - } - - public class ItemFieldUpdater implements FieldUpdateListener { @Override @@ -1158,34 +363,34 @@ public class ItemEditor extends JSONElementEditor { if (item.category == null || item.category.action_type == null || item.category.action_type == ItemCategory.ActionType.none) { equipEffectPane.setVisible(false); item.equip_effect = null; - hitEffectPane.setVisible(false); + hitEffectPane.effectPane.setVisible(false); item.hit_effect = null; - killEffectPane.setVisible(false); + killEffectPane.effectPane.setVisible(false); item.kill_effect = null; - hitReceivedEffectPane.setVisible(false); + hitReceivedEffectPane.effectPane.setVisible(false); item.hit_received_effect = null; ItemEditor.this.revalidate(); ItemEditor.this.repaint(); } else if (item.category.action_type == ItemCategory.ActionType.use) { equipEffectPane.setVisible(false); item.equip_effect = null; - hitEffectPane.setVisible(false); + hitEffectPane.effectPane.setVisible(false); item.hit_effect = null; - killEffectPane.setVisible(true); + killEffectPane.effectPane.setVisible(true); updateKill = true; - hitReceivedEffectPane.setVisible(false); + hitReceivedEffectPane.effectPane.setVisible(false); item.hit_received_effect = null; - killEffectPane.setTitle(useLabel); + killEffectPane.effectPane.setTitle(useLabel); ItemEditor.this.revalidate(); ItemEditor.this.repaint(); } else if (item.category.action_type == ItemCategory.ActionType.equip) { equipEffectPane.setVisible(true); - hitEffectPane.setVisible(true); - killEffectPane.setVisible(true); + hitEffectPane.effectPane.setVisible(true); + killEffectPane.effectPane.setVisible(true); updateKill = true; - hitReceivedEffectPane.setVisible(true); + hitReceivedEffectPane.effectPane.setVisible(true); updateEquip = true; - killEffectPane.setTitle(killLabel); + killEffectPane.effectPane.setTitle(killLabel); ItemEditor.this.revalidate(); ItemEditor.this.repaint(); } @@ -1261,339 +466,14 @@ public class ItemEditor extends JSONElementEditor { selectedEquipEffectCondition.magnitude = (Integer) equipConditionMagnitude.getValue(); equipConditionMagnitude.setEnabled(true); equipConditionsModel.itemChanged(selectedEquipEffectCondition); - } else if (source == hitHPMin) { - hitEffect.hp_boost_min = (Integer) value; + } else if (hitEffectPane.valueChanged(source, value, item)) { updatePrice = true; updateHit = true; - } else if (source == hitHPMax) { - hitEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitAPMin) { - hitEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitAPMax) { - hitEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateHit = true; - } else if (source == hitSourceConditionsList) { - updateHit = true; - } else if (source == hitSourceConditionBox) { - updateConditionEffect((ActorCondition)value, item, selectedHitEffectSourceCondition, hitSourceConditionsModel); - updateHit = true; - } else if (source == hitSourceConditionClear && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = null; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionApply && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = (Integer) hitSourceConditionMagnitude.getValue(); - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionImmunity && (Boolean) value) { - selectedHitEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectSourceCondition.duration = hitSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionMagnitude) { - selectedHitEffectSourceCondition.magnitude = (Integer) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionTimed && (Boolean) value) { - selectedHitEffectSourceCondition.duration = (Integer) hitSourceConditionDuration.getValue(); - if (selectedHitEffectSourceCondition.duration == null || selectedHitEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectSourceCondition.duration = 1; - } - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionForever && (Boolean) value) { - selectedHitEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitSourceTimedConditionWidgets(selectedHitEffectSourceCondition); - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionDuration) { - selectedHitEffectSourceCondition.duration = (Integer) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitSourceConditionChance) { - selectedHitEffectSourceCondition.chance = (Double) value; - hitSourceConditionsModel.itemChanged(selectedHitEffectSourceCondition); - updateHit = true; - } else if (source == hitTargetConditionsList) { - updateHit = true; - } else if (source == hitTargetConditionBox) { - updateConditionEffect((ActorCondition)value, item, selectedHitEffectTargetCondition, hitTargetConditionsModel); - updateHit = true; - } else if (source == hitTargetConditionClear && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionApply && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionImmunity && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionMagnitude) { - selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionTimed && (Boolean) value) { - selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionForever && (Boolean) value) { - selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionDuration) { - selectedHitEffectTargetCondition.duration = (Integer) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionChance) { - selectedHitEffectTargetCondition.chance = (Double) value; - hitTargetConditionsModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == killHPMin) { - killEffect.hp_boost_min = (Integer) value; + } else if (killEffectPane.valueChanged(source, value, item)) { updatePrice = true; updateKill = true; - } else if (source == killHPMax) { - killEffect.hp_boost_max = (Integer) value; + } else if (hitReceivedEffectPane.valueChanged(source, value, item)) { updatePrice = true; - updateKill = true; - } else if (source == killAPMin) { - killEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killAPMax) { - killEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateKill = true; - } else if (source == killSourceConditionsList) { - updateKill = true; - } else if (source == killSourceConditionBox) { - updateConditionEffect((ActorCondition) value, item, selectedKillEffectCondition, killSourceConditionsModel); - updateKill = true; - } else if (source == killSourceConditionClear && (Boolean) value) { - selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedKillEffectCondition.duration = null; - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionApply && (Boolean) value) { - selectedKillEffectCondition.magnitude = (Integer) killSourceConditionMagnitude.getValue(); - selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionImmunity && (Boolean) value) { - selectedKillEffectCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedKillEffectCondition.duration = killSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionMagnitude) { - selectedKillEffectCondition.magnitude = (Integer) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionTimed && (Boolean) value) { - selectedKillEffectCondition.duration = (Integer) killSourceConditionDuration.getValue(); - if (selectedKillEffectCondition.duration == null || selectedKillEffectCondition.duration == ActorCondition.DURATION_NONE) { - selectedKillEffectCondition.duration = 1; - } - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionForever && (Boolean) value) { - selectedKillEffectCondition.duration = ActorCondition.DURATION_FOREVER; - updateKillSourceTimedConditionWidgets(selectedKillEffectCondition); - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionDuration) { - selectedKillEffectCondition.duration = (Integer) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == killSourceConditionChance) { - selectedKillEffectCondition.chance = (Double) value; - killSourceConditionsModel.itemChanged(selectedKillEffectCondition); - updateKill = true; - } else if (source == hitReceivedHPMin) { - hitReceivedEffect.hp_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMax) { - hitReceivedEffect.hp_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMin) { - hitReceivedEffect.ap_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMax) { - hitReceivedEffect.ap_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMinTarget) { - hitReceivedEffect.target.hp_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedHPMaxTarget) { - hitReceivedEffect.target.hp_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMinTarget) { - hitReceivedEffect.target.ap_boost_min = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedAPMaxTarget) { - hitReceivedEffect.target.ap_boost_max = (Integer) value; - updatePrice = true; - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionBox) { - updateConditionEffect((ActorCondition) value, item, selectedHitReceivedEffectSourceCondition, hitReceivedSourceConditionsModel); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionClear && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = null; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionApply && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) hitReceivedSourceConditionMagnitude.getValue(); - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectSourceCondition.duration = hitReceivedSourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionMagnitude) { - selectedHitReceivedEffectSourceCondition.magnitude = (Integer) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionTimed && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) hitReceivedSourceConditionDuration.getValue(); - if (selectedHitReceivedEffectSourceCondition.duration == null || selectedHitReceivedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectSourceCondition.duration = 1; - } - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionForever && (Boolean) value) { - selectedHitReceivedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedSourceTimedConditionWidgets(selectedHitReceivedEffectSourceCondition); - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionDuration) { - selectedHitReceivedEffectSourceCondition.duration = (Integer) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedSourceConditionChance) { - selectedHitReceivedEffectSourceCondition.chance = (Double) value; - hitReceivedSourceConditionsModel.itemChanged(selectedHitReceivedEffectSourceCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionsList) { - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionBox) { - updateConditionEffect((ActorCondition) value, item, selectedHitReceivedEffectTargetCondition, hitReceivedTargetConditionsModel); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionClear && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = null; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionApply && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) hitReceivedTargetConditionMagnitude.getValue(); - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionImmunity && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitReceivedEffectTargetCondition.duration = hitReceivedTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionMagnitude) { - selectedHitReceivedEffectTargetCondition.magnitude = (Integer) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionTimed && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) hitReceivedTargetConditionDuration.getValue(); - if (selectedHitReceivedEffectTargetCondition.duration == null || selectedHitReceivedEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitReceivedEffectTargetCondition.duration = 1; - } - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionForever && (Boolean) value) { - selectedHitReceivedEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitReceivedTargetTimedConditionWidgets(selectedHitReceivedEffectTargetCondition); - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionDuration) { - selectedHitReceivedEffectTargetCondition.duration = (Integer) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); - updateHitReceived = true; - } else if (source == hitReceivedTargetConditionChance) { - selectedHitReceivedEffectTargetCondition.chance = (Double) value; - hitReceivedTargetConditionsModel.itemChanged(selectedHitReceivedEffectTargetCondition); updateHitReceived = true; } @@ -1605,24 +485,24 @@ public class ItemEditor extends JSONElementEditor { } } if (updateHit) { - if (isNull(hitEffect)) { + if (hitEffectPane.effect.isNull()) { item.hit_effect = null; } else { - item.hit_effect = hitEffect; + item.hit_effect = hitEffectPane.effect; } } if (updateKill) { - if (isNull(killEffect)) { + if (killEffectPane.effect.isNull()) { item.kill_effect = null; } else { - item.kill_effect = killEffect; + item.kill_effect = killEffectPane.effect; } } if (updateHitReceived) { - if (isNull(hitReceivedEffect)) { + if (hitReceivedEffectPane.effect.isNull()) { item.hit_received_effect = null; } else { - item.hit_received_effect = hitReceivedEffect; + item.hit_received_effect = hitReceivedEffectPane.effect; } } if (updatePrice && !manualPriceBox.isSelected()) { @@ -1637,10 +517,7 @@ public class ItemEditor extends JSONElementEditor { ATContentStudio.frame.editorChanged(ItemEditor.this); } updateJsonViewText(item.toJsonString()); - } - - } } From 652da07cc83b86a29ba55fbc0d755649a5423e67 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 16:30:49 +0200 Subject: [PATCH 78/94] change warning message when no action type can be determined for an item when writing --- src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 30b9480..365aa65 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -388,11 +388,7 @@ public class Item extends JSONElement { } else if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.use) { key = "useEffect"; } else { - try { - throw new IllegalArgumentException("Could not create JSON-Map for Item: Failed to determine if the items should be used or equipped."); - } catch (RuntimeException e) { - e.printStackTrace(); - } + System.out.println("Could not create JSON-Map for Item: Failed to determine if the item should be used or equipped."); key = null; } if (key != null) { From 93e44a2b502fbbd342dcf3fc6a38d4c5bde82f1f Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 16:39:46 +0200 Subject: [PATCH 79/94] improve *EffectPane initialisation --- .../ui/gamedataeditors/ItemEditor.java | 12 +++-------- .../ui/gamedataeditors/NPCEditor.java | 21 +++++++------------ 2 files changed, 10 insertions(+), 23 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index b2686c7..d1b2698 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -68,9 +68,9 @@ public class ItemEditor extends JSONElementEditor { private JRadioButton equipConditionImmunity; private JSpinner equipConditionMagnitude; - private CommonEditor.HitEffectPane hitEffectPane; - private CommonEditor.DeathEffectPane killEffectPane; - private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane; + private CommonEditor.HitEffectPane hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); + private CommonEditor.DeathEffectPane killEffectPane = new CommonEditor.DeathEffectPane(killLabel, Common.TimedActorConditionEffect::new, this, null); + private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, null, null); public ItemEditor(Item item) { super(item, item.getDesc(), item.getIcon()); @@ -159,8 +159,6 @@ public class ItemEditor extends JSONElementEditor { } else { hitEffect = item.hit_effect; } - if (hitEffectPane == null) - hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); hitEffectPane.createHitEffectPaneContent(listener, item.writable, hitEffect, new CommonEditor.SourceTimedConditionsListModel(hitEffect), new CommonEditor.TargetTimedConditionsListModel(hitEffect)); pane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); @@ -170,8 +168,6 @@ public class ItemEditor extends JSONElementEditor { } else { killEffect = item.kill_effect; } - if (killEffectPane == null) - killEffectPane = new CommonEditor.DeathEffectPane(killLabel, Common.TimedActorConditionEffect::new, this, null); killEffectPane.createDeathEffectPaneContent(listener, item.writable, killEffect, new CommonEditor.SourceTimedConditionsListModel(killEffect)); pane.add(killEffectPane.effectPane, JideBoxLayout.FIX); @@ -181,8 +177,6 @@ public class ItemEditor extends JSONElementEditor { } else { hitReceivedEffect = item.hit_received_effect; } - if (hitReceivedEffectPane == null) - hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, null, null); hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, item.writable, hitReceivedEffect, new CommonEditor.SourceTimedConditionsListModel(hitReceivedEffect), new CommonEditor.TargetTimedConditionsListModel(hitReceivedEffect)); pane.add(killEffectPane.effectPane, JideBoxLayout.FIX); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 32fe94b..1f74ec5 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -53,9 +53,9 @@ public class NPCEditor extends JSONElementEditor { private JSpinner blockChance; private JSpinner dmgRes; - private CommonEditor.HitEffectPane hitEffectPane; - private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane; - private CommonEditor.DeathEffectPane deathEffectPane; + private CommonEditor.HitEffectPane hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); + private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, "NPC", "Attacker"); + private CommonEditor.DeathEffectPane deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", Common.TimedActorConditionEffect::new, this, "Killer"); private JPanel dialogueGraphPane; private DialogueGraphView dialogueGraphView; @@ -149,8 +149,6 @@ public class NPCEditor extends JSONElementEditor { } else { hitEffect = npc.hit_effect; } - if (hitEffectPane == null) - hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new CommonEditor.SourceTimedConditionsListModel(hitEffect), new CommonEditor.TargetTimedConditionsListModel(hitEffect)); combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); @@ -160,8 +158,6 @@ public class NPCEditor extends JSONElementEditor { } else { hitReceivedEffect = npc.hit_received_effect; } - if (hitReceivedEffectPane == null) - hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, "NPC", "Attacker"); hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, new CommonEditor.SourceTimedConditionsListModel(hitReceivedEffect), new CommonEditor.TargetTimedConditionsListModel(hitReceivedEffect)); combatTraitPane.add(hitReceivedEffectPane.effectPane, JideBoxLayout.FIX); @@ -171,10 +167,7 @@ public class NPCEditor extends JSONElementEditor { } else { deathEffect = npc.death_effect; } - if (deathEffectPane == null) - deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", Common.TimedActorConditionEffect::new, this, "Killer"); - deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, deathEffect, new CommonEditor.SourceTimedConditionsListModel(deathEffect) - ); + deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, deathEffect, new CommonEditor.SourceTimedConditionsListModel(deathEffect)); combatTraitPane.add(deathEffectPane.effectPane, JideBoxLayout.FIX); pane.add(combatTraitPane, JideBoxLayout.FIX); @@ -274,11 +267,11 @@ public class NPCEditor extends JSONElementEditor { npc.block_chance = (Integer) value; } else if (source == dmgRes) { npc.damage_resistance = (Integer) value; - } else if(hitEffectPane != null &&hitEffectPane.valueChanged(source, value, npc)) { + } else if(hitEffectPane.valueChanged(source, value, npc)) { updateHit = true; - } else if (hitReceivedEffectPane != null && hitReceivedEffectPane.valueChanged(source, value, npc)) { + } else if (hitReceivedEffectPane.valueChanged(source, value, npc)) { updateHitReceived = true; - } else if (deathEffectPane != null && deathEffectPane.valueChanged(source, value, npc)) { + } else if (deathEffectPane.valueChanged(source, value, npc)) { updateDeath = true; } From 6b74ad5cbecb05db343039118428e338f10ae159 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 16:40:36 +0200 Subject: [PATCH 80/94] fix bug, where some values were not being updated when switching category to a different action type --- .../gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index d1b2698..6610e8b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -374,6 +374,8 @@ public class ItemEditor extends JSONElementEditor { updateKill = true; hitReceivedEffectPane.effectPane.setVisible(false); item.hit_received_effect = null; + updateHitReceived = true; + updateEquip = true; killEffectPane.effectPane.setTitle(useLabel); ItemEditor.this.revalidate(); ItemEditor.this.repaint(); @@ -383,6 +385,7 @@ public class ItemEditor extends JSONElementEditor { killEffectPane.effectPane.setVisible(true); updateKill = true; hitReceivedEffectPane.effectPane.setVisible(true); + updateHitReceived = true; updateEquip = true; killEffectPane.effectPane.setTitle(killLabel); ItemEditor.this.revalidate(); From 3f19ca959bd342af2667343616802ab97c9b3749 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 16:51:29 +0200 Subject: [PATCH 81/94] improve code a bit --- .../ui/gamedataeditors/ItemEditor.java | 60 +++++++++---------- .../ui/gamedataeditors/NPCEditor.java | 44 +++++++------- 2 files changed, 48 insertions(+), 56 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 6610e8b..d334664 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -18,6 +18,9 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; +import java.util.Objects; + +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; public class ItemEditor extends JSONElementEditor { @@ -30,7 +33,7 @@ public class ItemEditor extends JSONElementEditor { private static final String useLabel = "Effect on use: "; - private Common.ActorConditionEffect selectedEquipEffectCondition; + private ActorConditionEffect selectedEquipEffectCondition; private JButton itemIcon; @@ -68,9 +71,9 @@ public class ItemEditor extends JSONElementEditor { private JRadioButton equipConditionImmunity; private JSpinner equipConditionMagnitude; - private CommonEditor.HitEffectPane hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); - private CommonEditor.DeathEffectPane killEffectPane = new CommonEditor.DeathEffectPane(killLabel, Common.TimedActorConditionEffect::new, this, null); - private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, null, null); + private CommonEditor.HitEffectPane hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", TimedActorConditionEffect::new, this, null, null); + private CommonEditor.DeathEffectPane killEffectPane = new CommonEditor.DeathEffectPane(killLabel, TimedActorConditionEffect::new, this, null); + private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", TimedActorConditionEffect::new, this, null, null); public ItemEditor(Item item) { super(item, item.getDesc(), item.getIcon()); @@ -125,8 +128,8 @@ public class ItemEditor extends JSONElementEditor { String titleEquipConditions = "Actor Conditions applied when equipped: "; equipConditionsModel = new EquipConditionsListModel(equipEffect); CommonEditor.ConditionsCellRenderer cellRendererEquipConditions = new CommonEditor.ConditionsCellRenderer(); - BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; - BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; + BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; + BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; BasicLambda selectedResetEquipConditions = ()->selectedEquipEffectCondition = null; BasicLambdaWithArg updatePaneEquipConditions = (editorPane) -> updateEquipConditionEditorPane(editorPane, selectedEquipEffectCondition, listener); var resultEquipConditions = UiUtils.getCollapsibleItemList(listener, @@ -137,7 +140,7 @@ public class ItemEditor extends JSONElementEditor { (x) -> {}, updatePaneEquipConditions, item.writable, - Common.ActorConditionEffect::new, + ActorConditionEffect::new, cellRendererEquipConditions, titleEquipConditions, (x) -> null); @@ -153,31 +156,24 @@ public class ItemEditor extends JSONElementEditor { equipEffectPane.collapse(); } - Common.HitEffect hitEffect; - if (item.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = item.hit_effect; - } - hitEffectPane.createHitEffectPaneContent(listener, item.writable, hitEffect, new CommonEditor.SourceTimedConditionsListModel(hitEffect), new CommonEditor.TargetTimedConditionsListModel(hitEffect)); + HitEffect hitEffect = Objects.requireNonNullElseGet(item.hit_effect, HitEffect::new); + hitEffectPane.createHitEffectPaneContent(listener, item.writable, hitEffect, + new CommonEditor.SourceTimedConditionsListModel(hitEffect), + new CommonEditor.TargetTimedConditionsListModel(hitEffect)); pane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); - Common.DeathEffect killEffect; - if (item.kill_effect == null) { - killEffect = new Common.DeathEffect(); - } else { - killEffect = item.kill_effect; - } - killEffectPane.createDeathEffectPaneContent(listener, item.writable, killEffect, new CommonEditor.SourceTimedConditionsListModel(killEffect)); + DeathEffect killEffect = Objects.requireNonNullElseGet(item.kill_effect, DeathEffect::new); + killEffectPane.createDeathEffectPaneContent(listener, item.writable, killEffect, + new CommonEditor.SourceTimedConditionsListModel(killEffect)); pane.add(killEffectPane.effectPane, JideBoxLayout.FIX); - Common.HitReceivedEffect hitReceivedEffect; - if (item.hit_received_effect == null) { - hitReceivedEffect = new Common.HitReceivedEffect(); - } else { - hitReceivedEffect = item.hit_received_effect; - } - hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, item.writable, hitReceivedEffect, new CommonEditor.SourceTimedConditionsListModel(hitReceivedEffect), new CommonEditor.TargetTimedConditionsListModel(hitReceivedEffect)); + HitReceivedEffect hitReceivedEffect = Objects.requireNonNullElseGet(item.hit_received_effect, + HitReceivedEffect::new); + hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, item.writable, hitReceivedEffect, + new CommonEditor.SourceTimedConditionsListModel( + hitReceivedEffect), + new CommonEditor.TargetTimedConditionsListModel( + hitReceivedEffect)); pane.add(killEffectPane.effectPane, JideBoxLayout.FIX); @@ -203,7 +199,7 @@ public class ItemEditor extends JSONElementEditor { } - public void updateEquipConditionEditorPane(JPanel pane, Common.ActorConditionEffect condition, final FieldUpdateListener listener) { + public void updateEquipConditionEditorPane(JPanel pane, ActorConditionEffect condition, final FieldUpdateListener listener) { pane.removeAll(); if (equipConditionBox != null) { removeElementListener(equipConditionBox); @@ -251,18 +247,18 @@ public class ItemEditor extends JSONElementEditor { pane.repaint(); } - public static class EquipConditionsListModel extends OrderedListenerListModel { + public static class EquipConditionsListModel extends OrderedListenerListModel { public EquipConditionsListModel(Item.EquipEffect equipEffect) { super(equipEffect); } @Override - protected List getItems() { + protected List getItems() { return source.conditions; } @Override - protected void setItems(List conditions) { + protected void setItems(List conditions) { source.conditions = conditions; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 1f74ec5..724a3e1 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -16,6 +16,9 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; +import java.util.Objects; + +import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; public class NPCEditor extends JSONElementEditor { @@ -53,9 +56,9 @@ public class NPCEditor extends JSONElementEditor { private JSpinner blockChance; private JSpinner dmgRes; - private CommonEditor.HitEffectPane hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", Common.TimedActorConditionEffect::new, this, null, null); - private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", Common.TimedActorConditionEffect::new, this, "NPC", "Attacker"); - private CommonEditor.DeathEffectPane deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", Common.TimedActorConditionEffect::new, this, "Killer"); + private CommonEditor.HitEffectPane hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", TimedActorConditionEffect::new, this, null, null); + private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", TimedActorConditionEffect::new, this, "NPC", "Attacker"); + private CommonEditor.DeathEffectPane deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", TimedActorConditionEffect::new, this, "Killer"); private JPanel dialogueGraphPane; private DialogueGraphView dialogueGraphView; @@ -143,31 +146,24 @@ public class NPCEditor extends JSONElementEditor { blockChance = addIntegerField(combatTraitPane, "Block chance: ", npc.block_chance, false, npc.writable, listener); dmgRes = addIntegerField(combatTraitPane, "Damage resistance: ", npc.damage_resistance, false, npc.writable, listener); - Common.HitEffect hitEffect; - if (npc.hit_effect == null) { - hitEffect = new Common.HitEffect(); - } else { - hitEffect = npc.hit_effect; - } - hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, new CommonEditor.SourceTimedConditionsListModel(hitEffect), new CommonEditor.TargetTimedConditionsListModel(hitEffect)); + HitEffect hitEffect = Objects.requireNonNullElseGet(npc.hit_effect, HitEffect::new); + hitEffectPane.createHitEffectPaneContent(listener, npc.writable, hitEffect, + new CommonEditor.SourceTimedConditionsListModel(hitEffect), + new CommonEditor.TargetTimedConditionsListModel(hitEffect)); combatTraitPane.add(hitEffectPane.effectPane, JideBoxLayout.FIX); - Common.HitReceivedEffect hitReceivedEffect; - if (npc.hit_received_effect == null) { - hitReceivedEffect = new Common.HitReceivedEffect(); - } else { - hitReceivedEffect = npc.hit_received_effect; - } - hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, new CommonEditor.SourceTimedConditionsListModel(hitReceivedEffect), new CommonEditor.TargetTimedConditionsListModel(hitReceivedEffect)); + HitReceivedEffect hitReceivedEffect = Objects.requireNonNullElseGet(npc.hit_received_effect, + HitReceivedEffect::new); + hitReceivedEffectPane.createHitReceivedEffectPaneContent(listener, npc.writable, hitReceivedEffect, + new CommonEditor.SourceTimedConditionsListModel( + hitReceivedEffect), + new CommonEditor.TargetTimedConditionsListModel( + hitReceivedEffect)); combatTraitPane.add(hitReceivedEffectPane.effectPane, JideBoxLayout.FIX); - Common.DeathEffect deathEffect; - if (npc.death_effect == null) { - deathEffect = new Common.DeathEffect(); - } else { - deathEffect = npc.death_effect; - } - deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, deathEffect, new CommonEditor.SourceTimedConditionsListModel(deathEffect)); + DeathEffect deathEffect = Objects.requireNonNullElseGet(npc.death_effect, DeathEffect::new); + deathEffectPane.createDeathEffectPaneContent(listener, npc.writable, deathEffect, + new CommonEditor.SourceTimedConditionsListModel(deathEffect)); combatTraitPane.add(deathEffectPane.effectPane, JideBoxLayout.FIX); pane.add(combatTraitPane, JideBoxLayout.FIX); From 281e314815944f8875e501c1c35ce3a533610a0a Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 18:00:47 +0200 Subject: [PATCH 82/94] extract ConditionEffectEditorPane --- .../ui/gamedataeditors/CommonEditor.java | 556 +++++++----------- 1 file changed, 207 insertions(+), 349 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 19b8498..01600b9 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -139,30 +139,17 @@ public class CommonEditor { public static class HitEffectPane> extends DeathEffectPane { /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! - EFFECT effect; + public EFFECT effect; - String applyToTargetHint; - - MODEL hitTargetConditionsListModel; - JList hitTargetConditionsList; - ELEMENT selectedHitEffectTargetCondition; - - Editor.MyComboBox hitTargetConditionBox; - JSpinner hitTargetConditionChance; - JRadioButton hitTargetConditionClear; - JRadioButton hitTargetConditionApply; - JRadioButton hitTargetConditionImmunity; - JSpinner hitTargetConditionMagnitude; - JRadioButton hitTargetConditionTimed; - JRadioButton hitTargetConditionForever; - JSpinner hitTargetConditionDuration; + protected String applyToTargetHint; + private JList hitTargetConditionsList; + private ConditionEffectEditorPane hitTargetConditionPane = new ConditionEffectEditorPane<>(); /* * create a new HitEffectPane with the selections (probably passed in from last time) */ public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { super(title, sourceNewSupplier, editor, applyToHint); - this.selectedHitEffectTargetCondition = selectedHitEffectTargetCondition; if (applyToTargetHint == null || applyToTargetHint == "") { applyToTargetHint = ""; @@ -172,9 +159,9 @@ public class CommonEditor { this.applyToTargetHint = applyToTargetHint; } - void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModelInput, MODEL hitTargetConditionsListModel1) { + void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModelInput, MODEL targetConditionsListModel) { effect = e; - hitTargetConditionsListModel = hitTargetConditionsListModel1; + hitTargetConditionPane.conditionsModel = targetConditionsListModel; createDeathEffectPaneContent(listener, writable, e, sourceConditionsModelInput); } @@ -184,13 +171,13 @@ public class CommonEditor { String titleTarget = "Actor Conditions applied to the target%s: ".formatted(applyToTargetHint); CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetTarget = (value) -> selectedHitEffectTargetCondition = value; - BasicLambdaWithReturn selectedGetTarget = () -> selectedHitEffectTargetCondition; - BasicLambda selectedResetTarget = () -> selectedHitEffectTargetCondition = null; - BasicLambdaWithArg updatePaneTarget = (editorPane) -> updateHitTargetTimedConditionEditorPane( - editorPane, selectedHitEffectTargetCondition, listener, this.editor); + BasicLambdaWithArg selectedSetTarget = (value) -> hitTargetConditionPane.selectedCondition = value; + BasicLambdaWithReturn selectedGetTarget = () -> hitTargetConditionPane.selectedCondition; + BasicLambda selectedResetTarget = () -> hitTargetConditionPane.selectedCondition = null; + BasicLambdaWithArg updatePaneTarget = (editorPane) -> hitTargetConditionPane.updateEffectTimedConditionEditorPane( + editorPane, hitTargetConditionPane.selectedCondition, listener, editor); - var resultTarget = UiUtils.getCollapsibleItemList(listener, hitTargetConditionsListModel, + var resultTarget = UiUtils.getCollapsibleItemList(listener, hitTargetConditionPane.conditionsModel, selectedResetTarget, selectedSetTarget, selectedGetTarget, (x) -> { }, updatePaneTarget, writable, this.conditionSupplier, @@ -203,156 +190,15 @@ public class CommonEditor { effectPane.add(hitTargetConditionsPane, JideBoxLayout.FIX); } - public void updateHitTargetTimedConditionEditorPane(JPanel pane, Common.TimedActorConditionEffect condition, final FieldUpdateListener listener, Editor e) { - pane.removeAll(); - if (hitTargetConditionBox != null) { - e.removeElementListener(hitTargetConditionBox); - } - - boolean writable = e.target.writable; - Project proj = e.target.getProject(); - - hitTargetConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, - writable, listener); - hitTargetConditionChance = Editor.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - hitTargetConditionClear = new JRadioButton("Clear active condition"); - pane.add(hitTargetConditionClear, JideBoxLayout.FIX); - hitTargetConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(hitTargetConditionApply, JideBoxLayout.FIX); - hitTargetConditionMagnitude = addIntegerField(pane, "Magnitude: ", - condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, - 1, false, writable, listener); - hitTargetConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(hitTargetConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(hitTargetConditionApply); - radioEffectGroup.add(hitTargetConditionClear); - radioEffectGroup.add(hitTargetConditionImmunity); - - hitTargetConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(hitTargetConditionTimed, JideBoxLayout.FIX); - hitTargetConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, - listener); - hitTargetConditionForever = new JRadioButton("Forever"); - pane.add(hitTargetConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(hitTargetConditionTimed); - radioDurationGroup.add(hitTargetConditionForever); - - updateHitTargetTimedConditionWidgets(condition); - - hitTargetConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionClear, hitTargetConditionClear.isSelected()); - } - }); - hitTargetConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionApply, hitTargetConditionApply.isSelected()); - } - }); - hitTargetConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionImmunity, hitTargetConditionImmunity.isSelected()); - } - }); - - hitTargetConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionTimed, hitTargetConditionTimed.isSelected()); - } - }); - hitTargetConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(hitTargetConditionForever, hitTargetConditionForever.isSelected()); - } - }); - pane.revalidate(); - pane.repaint(); - } - - public void updateHitTargetTimedConditionWidgets(Common.TimedActorConditionEffect condition) { - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - hitTargetConditionClear.setSelected(clear); - hitTargetConditionApply.setSelected(!clear && !immunity); - hitTargetConditionMagnitude.setEnabled(!clear && !immunity); - hitTargetConditionImmunity.setSelected(immunity); - hitTargetConditionTimed.setSelected(!forever); - hitTargetConditionTimed.setEnabled(!clear); - hitTargetConditionDuration.setEnabled(!clear && !forever); - hitTargetConditionForever.setSelected(forever); - hitTargetConditionForever.setEnabled(!clear); - - } - @Override public boolean valueChanged(JComponent source, Object value, GameDataElement backlink) { - boolean updateHit = super.valueChanged(source, value, backlink); - if (!updateHit) { - if (source == hitTargetConditionsList) { - updateHit = true; - } else if (source == hitTargetConditionBox) { - editor.updateConditionEffect((ActorCondition) value, backlink, selectedHitEffectTargetCondition, - hitTargetConditionsListModel); - } else if (source == hitTargetConditionClear && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = null; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionApply && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = (Integer) hitTargetConditionMagnitude.getValue(); - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionImmunity && (Boolean) value) { - selectedHitEffectTargetCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedHitEffectTargetCondition.duration = hitTargetConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionMagnitude) { - selectedHitEffectTargetCondition.magnitude = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionTimed && (Boolean) value) { - selectedHitEffectTargetCondition.duration = (Integer) hitTargetConditionDuration.getValue(); - if (selectedHitEffectTargetCondition.duration == null || selectedHitEffectTargetCondition.duration == ActorCondition.DURATION_NONE) { - selectedHitEffectTargetCondition.duration = 1; - } - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionForever && (Boolean) value) { - selectedHitEffectTargetCondition.duration = ActorCondition.DURATION_FOREVER; - updateHitTargetTimedConditionWidgets(selectedHitEffectTargetCondition); - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionDuration) { - selectedHitEffectTargetCondition.duration = (Integer) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - updateHit = true; - } else if (source == hitTargetConditionChance) { - selectedHitEffectTargetCondition.chance = (Double) value; - hitTargetConditionsListModel.itemChanged(selectedHitEffectTargetCondition); - } + boolean updateHit = false; + if(super.valueChanged(source, value, backlink)){ + updateHit = true; + } else if (source == hitTargetConditionsList) { + updateHit = true; + } else if (hitTargetConditionPane.valueChanged(source, value, backlink)) { + updateHit = true; } return updateHit; @@ -368,23 +214,14 @@ public class CommonEditor { EFFECT effect; CollapsiblePanel effectPane; - JSpinner effectHPMin; - JSpinner effectHPMax; - JSpinner effectAPMin; - JSpinner effectAPMax; - MODEL sourceConditionsModel; - JList sourceConditionsList; - ELEMENT selectedEffectSourceCondition; + private JSpinner effectHPMin; + private JSpinner effectHPMax; + private JSpinner effectAPMin; + private JSpinner effectAPMax; + private JList sourceConditionsList; + + private ConditionEffectEditorPane sourceConditionPane = new ConditionEffectEditorPane<>(); - Editor.MyComboBox sourceConditionBox; - JSpinner sourceConditionChance; - JRadioButton sourceConditionClear; - JRadioButton sourceConditionApply; - JRadioButton sourceConditionImmunity; - JSpinner sourceConditionMagnitude; - JRadioButton sourceConditionTimed; - JRadioButton sourceConditionForever; - JSpinner sourceConditionDuration; /* * create a new DeatchEffectPane with the selections (probably passed in from last time) @@ -398,7 +235,7 @@ public class CommonEditor { void createDeathEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModel) { effect = e; - this.sourceConditionsModel = sourceConditionsModel; + sourceConditionPane.conditionsModel = sourceConditionsModel; if (applyToHint == null || applyToHint == "") { applyToHint = ""; @@ -427,13 +264,13 @@ public class CommonEditor { protected void addLists(FieldUpdateListener listener, boolean writable) { String titleSource = "Actor Conditions applied to the source%s: ".formatted(applyToHint); TimedConditionsCellRenderer cellRendererSource = new TimedConditionsCellRenderer(); - BasicLambdaWithArg selectedSetSource = (value) -> selectedEffectSourceCondition = value; - BasicLambdaWithReturn selectedGetSource = () -> selectedEffectSourceCondition; - BasicLambda selectedResetSource = () -> selectedEffectSourceCondition = null; - BasicLambdaWithArg updatePaneSource = (editorPane) -> updateEffectSourceTimedConditionEditorPane( - editorPane, selectedEffectSourceCondition, listener, editor); + BasicLambdaWithArg selectedSetSource = (value) -> sourceConditionPane.selectedCondition = value; + BasicLambdaWithReturn selectedGetSource = () -> sourceConditionPane.selectedCondition; + BasicLambda selectedResetSource = () -> sourceConditionPane.selectedCondition = null; + BasicLambdaWithArg updatePaneSource = (editorPane) -> sourceConditionPane.updateEffectTimedConditionEditorPane( + editorPane, sourceConditionPane.selectedCondition, listener, editor); - var resultSource = UiUtils.getCollapsibleItemList(listener, this.sourceConditionsModel, selectedResetSource, + var resultSource = UiUtils.getCollapsibleItemList(listener, sourceConditionPane.conditionsModel, selectedResetSource, selectedSetSource, selectedGetSource, (x) -> { }, updatePaneSource, writable, conditionSupplier, cellRendererSource, titleSource, (x) -> null); sourceConditionsList = resultSource.list; @@ -444,100 +281,6 @@ public class CommonEditor { effectPane.add(sourceConditionsPane, JideBoxLayout.FIX); } - public void updateEffectSourceTimedConditionEditorPane(JPanel pane, ELEMENT condition, final FieldUpdateListener listener, Editor e) { - pane.removeAll(); - if (sourceConditionBox != null) { - e.removeElementListener(sourceConditionBox); - } - - boolean writable = e.target.writable; - Project proj = e.target.getProject(); - - sourceConditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, - listener); - sourceConditionChance = Editor.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); - - sourceConditionClear = new JRadioButton("Clear active condition"); - pane.add(sourceConditionClear, JideBoxLayout.FIX); - sourceConditionApply = new JRadioButton("Apply condition with magnitude"); - pane.add(sourceConditionApply, JideBoxLayout.FIX); - sourceConditionMagnitude = addIntegerField(pane, "Magnitude: ", - condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, - 1, false, writable, listener); - sourceConditionImmunity = new JRadioButton("Give immunity to condition"); - pane.add(sourceConditionImmunity, JideBoxLayout.FIX); - - ButtonGroup radioEffectGroup = new ButtonGroup(); - radioEffectGroup.add(sourceConditionApply); - radioEffectGroup.add(sourceConditionClear); - radioEffectGroup.add(sourceConditionImmunity); - - sourceConditionTimed = new JRadioButton("For a number of rounds"); - pane.add(sourceConditionTimed, JideBoxLayout.FIX); - sourceConditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, - listener); - sourceConditionForever = new JRadioButton("Forever"); - pane.add(sourceConditionForever, JideBoxLayout.FIX); - - ButtonGroup radioDurationGroup = new ButtonGroup(); - radioDurationGroup.add(sourceConditionTimed); - radioDurationGroup.add(sourceConditionForever); - - updateEffectSourceTimedConditionWidgets(condition); - - sourceConditionClear.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionClear, sourceConditionClear.isSelected()); - } - }); - sourceConditionApply.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionApply, sourceConditionApply.isSelected()); - } - }); - sourceConditionImmunity.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionImmunity, sourceConditionImmunity.isSelected()); - } - }); - - sourceConditionTimed.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionTimed, sourceConditionTimed.isSelected()); - } - }); - sourceConditionForever.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent e) { - listener.valueChanged(sourceConditionForever, sourceConditionForever.isSelected()); - } - }); - pane.revalidate(); - pane.repaint(); - } - - - public void updateEffectSourceTimedConditionWidgets(ELEMENT condition) { - boolean immunity = condition.isImmunity(); - boolean clear = condition.isClear(); - boolean forever = condition.isInfinite(); - - sourceConditionClear.setSelected(clear); - sourceConditionApply.setSelected(!clear && !immunity); - sourceConditionMagnitude.setEnabled(!clear && !immunity); - sourceConditionImmunity.setSelected(immunity); - - sourceConditionTimed.setSelected(!forever); - sourceConditionTimed.setEnabled(!clear); - sourceConditionDuration.setEnabled(!clear && !forever); - sourceConditionForever.setSelected(forever); - sourceConditionForever.setEnabled(!clear); - } - public boolean valueChanged(JComponent source, Object value, GameDataElement backlink) { boolean updateHit = false; if (source == effectHPMin) { @@ -554,71 +297,186 @@ public class CommonEditor { updateHit = true; } else if (source == sourceConditionsList) { updateHit = true; - } else if (source == sourceConditionBox) { - if (selectedEffectSourceCondition.condition != null) { - selectedEffectSourceCondition.condition.removeBacklink(backlink); - } - selectedEffectSourceCondition.condition = (ActorCondition) value; - if (selectedEffectSourceCondition.condition != null) { - selectedEffectSourceCondition.condition.addBacklink(backlink); - selectedEffectSourceCondition.condition_id = selectedEffectSourceCondition.condition.id; - } else { - selectedEffectSourceCondition.condition_id = null; - } - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); - } else if (source == sourceConditionClear && (Boolean) value) { - selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedEffectSourceCondition.duration = null; - updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); + } else if (sourceConditionPane.valueChanged(source, value, backlink)){ updateHit = true; - } else if (source == sourceConditionApply && (Boolean) value) { - selectedEffectSourceCondition.magnitude = (Integer) sourceConditionMagnitude.getValue(); - selectedEffectSourceCondition.duration = sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) sourceConditionDuration.getValue(); - if (selectedEffectSourceCondition.duration == null || selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedEffectSourceCondition.duration = 1; - } - updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); - updateHit = true; - } else if (source == sourceConditionImmunity && (Boolean) value) { - selectedEffectSourceCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; - selectedEffectSourceCondition.duration = sourceConditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) sourceConditionDuration.getValue(); - if (selectedEffectSourceCondition.duration == null || selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedEffectSourceCondition.duration = 1; - } - updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); - updateHit = true; - } else if (source == sourceConditionMagnitude) { - selectedEffectSourceCondition.magnitude = (Integer) value; - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); - updateHit = true; - } else if (source == sourceConditionTimed && (Boolean) value) { - selectedEffectSourceCondition.duration = (Integer) sourceConditionDuration.getValue(); - if (selectedEffectSourceCondition.duration == null || selectedEffectSourceCondition.duration == ActorCondition.DURATION_NONE) { - selectedEffectSourceCondition.duration = 1; - } - updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); - updateHit = true; - } else if (source == sourceConditionForever && (Boolean) value) { - selectedEffectSourceCondition.duration = ActorCondition.DURATION_FOREVER; - updateEffectSourceTimedConditionWidgets(selectedEffectSourceCondition); - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); - updateHit = true; - } else if (source == sourceConditionDuration) { - selectedEffectSourceCondition.duration = (Integer) value; - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); - updateHit = true; - } else if (source == sourceConditionChance) { - selectedEffectSourceCondition.chance = (Double) value; - sourceConditionsModel.itemChanged(selectedEffectSourceCondition); } return updateHit; } } + static class ConditionEffectEditorPane> { + ELEMENT selectedCondition; + + MODEL conditionsModel; + Editor.MyComboBox conditionBox; + JSpinner conditionChance; + JRadioButton conditionClear; + JRadioButton conditionApply; + JRadioButton conditionImmunity; + JSpinner conditionMagnitude; + JRadioButton conditionTimed; + JRadioButton conditionForever; + JSpinner conditionDuration; + + public void updateEffectTimedConditionWidgets(ELEMENT condition) { + boolean immunity = condition.isImmunity(); + boolean clear = condition.isClear(); + boolean forever = condition.isInfinite(); + + conditionClear.setSelected(clear); + conditionApply.setSelected(!clear && !immunity); + conditionMagnitude.setEnabled(!clear && !immunity); + conditionImmunity.setSelected(immunity); + conditionTimed.setSelected(!forever); + conditionTimed.setEnabled(!clear); + conditionDuration.setEnabled(!clear && !forever); + conditionForever.setSelected(forever); + conditionForever.setEnabled(!clear); + } + + public void updateEffectTimedConditionEditorPane(JPanel pane, ELEMENT condition, final FieldUpdateListener listener, Editor e) { + pane.removeAll(); + if (conditionBox != null) { + e.removeElementListener(conditionBox); + } + + boolean writable = e.target.writable; + Project proj = e.target.getProject(); + + conditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, + listener); + conditionChance = Editor.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); + + conditionClear = new JRadioButton("Clear active condition"); + pane.add(conditionClear, JideBoxLayout.FIX); + conditionApply = new JRadioButton("Apply condition with magnitude"); + pane.add(conditionApply, JideBoxLayout.FIX); + conditionMagnitude = addIntegerField(pane, "Magnitude: ", + condition.magnitude == null ? null : condition.magnitude >= 0 ? condition.magnitude : 0, + 1, false, writable, listener); + conditionImmunity = new JRadioButton("Give immunity to condition"); + pane.add(conditionImmunity, JideBoxLayout.FIX); + + ButtonGroup radioEffectGroup = new ButtonGroup(); + radioEffectGroup.add(conditionApply); + radioEffectGroup.add(conditionClear); + radioEffectGroup.add(conditionImmunity); + + conditionTimed = new JRadioButton("For a number of rounds"); + pane.add(conditionTimed, JideBoxLayout.FIX); + conditionDuration = addIntegerField(pane, "Duration: ", condition.duration, 1, false, writable, + listener); + conditionForever = new JRadioButton("Forever"); + pane.add(conditionForever, JideBoxLayout.FIX); + + ButtonGroup radioDurationGroup = new ButtonGroup(); + radioDurationGroup.add(conditionTimed); + radioDurationGroup.add(conditionForever); + + updateEffectTimedConditionWidgets(condition); + + conditionClear.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(conditionClear, conditionClear.isSelected()); + } + }); + conditionApply.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(conditionApply, conditionApply.isSelected()); + } + }); + conditionImmunity.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(conditionImmunity, conditionImmunity.isSelected()); + } + }); + + conditionTimed.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(conditionTimed, conditionTimed.isSelected()); + } + }); + conditionForever.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + listener.valueChanged(conditionForever, conditionForever.isSelected()); + } + }); + pane.revalidate(); + pane.repaint(); + } + + public boolean valueChanged(JComponent source, Object value, GameDataElement backlink) { + boolean updateHit = false; + + if (source == conditionBox) { + if (selectedCondition.condition != null) { + selectedCondition.condition.removeBacklink(backlink); + } + selectedCondition.condition = (ActorCondition) value; + if (selectedCondition.condition != null) { + selectedCondition.condition.addBacklink(backlink); + selectedCondition.condition_id = selectedCondition.condition.id; + } else { + selectedCondition.condition_id = null; + } + conditionsModel.itemChanged(selectedCondition); + } else if (source == conditionClear && (Boolean) value) { + selectedCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedCondition.duration = null; + updateEffectTimedConditionWidgets(selectedCondition); + conditionsModel.itemChanged(selectedCondition); + updateHit = true; + } else if (source == conditionApply && (Boolean) value) { + selectedCondition.magnitude = (Integer) conditionMagnitude.getValue(); + selectedCondition.duration = conditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) conditionDuration.getValue(); + if (selectedCondition.duration == null || selectedCondition.duration == ActorCondition.DURATION_NONE) { + selectedCondition.duration = 1; + } + updateEffectTimedConditionWidgets(selectedCondition); + conditionsModel.itemChanged(selectedCondition); + updateHit = true; + } else if (source == conditionImmunity && (Boolean) value) { + selectedCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; + selectedCondition.duration = conditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) conditionDuration.getValue(); + if (selectedCondition.duration == null || selectedCondition.duration == ActorCondition.DURATION_NONE) { + selectedCondition.duration = 1; + } + updateEffectTimedConditionWidgets(selectedCondition); + conditionsModel.itemChanged(selectedCondition); + updateHit = true; + } else if (source == conditionMagnitude) { + selectedCondition.magnitude = (Integer) value; + conditionsModel.itemChanged(selectedCondition); + updateHit = true; + } else if (source == conditionTimed && (Boolean) value) { + selectedCondition.duration = (Integer) conditionDuration.getValue(); + if (selectedCondition.duration == null || selectedCondition.duration == ActorCondition.DURATION_NONE) { + selectedCondition.duration = 1; + } + updateEffectTimedConditionWidgets(selectedCondition); + conditionsModel.itemChanged(selectedCondition); + updateHit = true; + } else if (source == conditionForever && (Boolean) value) { + selectedCondition.duration = ActorCondition.DURATION_FOREVER; + updateEffectTimedConditionWidgets(selectedCondition); + conditionsModel.itemChanged(selectedCondition); + updateHit = true; + } else if (source == conditionDuration) { + selectedCondition.duration = (Integer) value; + conditionsModel.itemChanged(selectedCondition); + updateHit = true; + } else if (source == conditionChance) { + selectedCondition.chance = (Double) value; + conditionsModel.itemChanged(selectedCondition); + } + return updateHit; + } + } //region list-models From 358d855eec4c3527b17f21766fc437b63e50ee29 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 18:11:24 +0200 Subject: [PATCH 83/94] fix number comparison bugs --- .../rpg/atcontentstudio/model/gamedata/Common.java | 12 ++++++++---- .../ui/gamedataeditors/CommonEditor.java | 2 +- .../ui/gamedataeditors/DialogueEditor.java | 12 ++++++------ .../ui/gamedataeditors/ItemEditor.java | 2 +- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 4b9987a..e66a172 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -170,13 +170,14 @@ public final class Common { return cclone; } public boolean isInfinite(){ - return duration != null && duration == ActorCondition.DURATION_FOREVER; + return duration != null && duration.equals(ActorCondition.DURATION_FOREVER); } public boolean isImmunity(){ - return (magnitude == null || magnitude == ActorCondition.MAGNITUDE_CLEAR) && (duration != null && duration > ActorCondition.DURATION_NONE); + return (super.isClear()) && (duration != null && duration > ActorCondition.DURATION_NONE); } - public boolean isClear(){ - return (magnitude == null || magnitude == ActorCondition.MAGNITUDE_CLEAR) && (duration == null || duration == ActorCondition.DURATION_NONE); + @Override + public boolean isClear() { + return (super.isClear()) && (duration == null || duration.equals(ActorCondition.DURATION_NONE)); } } @@ -187,6 +188,9 @@ public final class Common { //Available from linked state public ActorCondition condition = null; + public boolean isClear(){ + return magnitude == null || magnitude.equals(ActorCondition.MAGNITUDE_CLEAR); + } } @SuppressWarnings("rawtypes") diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 01600b9..aae9341 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -68,7 +68,7 @@ public class CommonEditor { Common.ActorConditionEffect effect = (Common.ActorConditionEffect) value; if (effect.condition != null) { - if (effect.magnitude == ActorCondition.MAGNITUDE_CLEAR) { + if (effect.isClear()) { label.setIcon(new OverlayIcon(effect.condition.getIcon(), DefaultIcons.getImmunityIcon())); label.setText("Immune to actor condition " + effect.condition.getDesc()); } else { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index 4b84538..d2e7b33 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -278,12 +278,12 @@ public class DialogueEditor extends JSONElementEditor { if (!immunity) radioGroup.add(rewardConditionClear); if (immunity) { - rewardConditionTimed.setSelected(reward.reward_value == null || (reward.reward_value != ActorCondition.DURATION_FOREVER && reward.reward_value != ActorCondition.MAGNITUDE_CLEAR)); - rewardConditionForever.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.DURATION_FOREVER); - rewardConditionClear.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.MAGNITUDE_CLEAR); + rewardConditionTimed.setSelected(reward.reward_value == null || (!reward.reward_value.equals(ActorCondition.DURATION_FOREVER) && !reward.reward_value.equals(ActorCondition.MAGNITUDE_CLEAR))); + rewardConditionForever.setSelected(reward.reward_value != null && !reward.reward_value.equals(ActorCondition.DURATION_FOREVER)); + rewardConditionClear.setSelected(reward.reward_value != null && !reward.reward_value.equals(ActorCondition.MAGNITUDE_CLEAR)); } else { - rewardConditionTimed.setSelected(reward.reward_value != null && reward.reward_value != ActorCondition.DURATION_FOREVER); - rewardConditionForever.setSelected(reward.reward_value == null || reward.reward_value == ActorCondition.DURATION_FOREVER); + rewardConditionTimed.setSelected(reward.reward_value != null && !reward.reward_value.equals(ActorCondition.DURATION_FOREVER)); + rewardConditionForever.setSelected(reward.reward_value == null || reward.reward_value.equals(ActorCondition.DURATION_FOREVER)); } rewardValue.setEnabled(rewardConditionTimed.isSelected()); @@ -662,7 +662,7 @@ public class DialogueEditor extends JSONElementEditor { label.setIcon(new ImageIcon(DefaultIcons.getObjectLayerIcon())); break; case actorCondition: - boolean rewardClear = reward.reward_value != null && reward.reward_value.intValue() == ActorCondition.MAGNITUDE_CLEAR; + boolean rewardClear = reward.reward_value != null && reward.reward_value.equals(ActorCondition.MAGNITUDE_CLEAR); if (rewardClear) { label.setText("Clear actor condition " + rewardObjDesc); } else { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index d334664..800ca91 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -224,7 +224,7 @@ public class ItemEditor extends JSONElementEditor { radioEffectGroup.add(equipConditionWithMagnitude); radioEffectGroup.add(equipConditionImmunity); - boolean immunity = condition.magnitude == null || condition.magnitude == ActorCondition.MAGNITUDE_CLEAR; + boolean immunity = condition.magnitude == null || condition.magnitude.equals(ActorCondition.MAGNITUDE_CLEAR); equipConditionImmunity.setSelected(immunity); equipConditionWithMagnitude.setSelected(!immunity); equipConditionMagnitude.setEnabled(!immunity); From cd368130507b8300999b6b032d9290b7204a82fb Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 18:40:54 +0200 Subject: [PATCH 84/94] move some things around and make the code sturdier --- .../ui/gamedataeditors/CommonEditor.java | 51 ++++++++++--------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index aae9341..f44c671 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -141,22 +141,22 @@ public class CommonEditor { /// this should just be a convenience field, to access it, without casting. DO NOT SET WITHOUT ALSO SETTING THE FIELD IN THE SUPER-CLASS! public EFFECT effect; - protected String applyToTargetHint; + protected final String applyToTargetHint; private JList hitTargetConditionsList; - private ConditionEffectEditorPane hitTargetConditionPane = new ConditionEffectEditorPane<>(); + private final ConditionEffectEditorPane hitTargetConditionPane ; /* * create a new HitEffectPane with the selections (probably passed in from last time) */ public HitEffectPane(String title, Supplier sourceNewSupplier, Editor editor, String applyToHint, String applyToTargetHint) { super(title, sourceNewSupplier, editor, applyToHint); + hitTargetConditionPane = new ConditionEffectEditorPane<>(editor); if (applyToTargetHint == null || applyToTargetHint == "") { - applyToTargetHint = ""; + this.applyToTargetHint = ""; } else { - applyToTargetHint = " (%s)".formatted(applyToTargetHint); + this.applyToTargetHint = " (%s)".formatted(applyToTargetHint); } - this.applyToTargetHint = applyToTargetHint; } void createHitEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModelInput, MODEL targetConditionsListModel) { @@ -175,7 +175,7 @@ public class CommonEditor { BasicLambdaWithReturn selectedGetTarget = () -> hitTargetConditionPane.selectedCondition; BasicLambda selectedResetTarget = () -> hitTargetConditionPane.selectedCondition = null; BasicLambdaWithArg updatePaneTarget = (editorPane) -> hitTargetConditionPane.updateEffectTimedConditionEditorPane( - editorPane, hitTargetConditionPane.selectedCondition, listener, editor); + editorPane, hitTargetConditionPane.selectedCondition, listener); var resultTarget = UiUtils.getCollapsibleItemList(listener, hitTargetConditionPane.conditionsModel, selectedResetTarget, selectedSetTarget, selectedGetTarget, @@ -206,10 +206,9 @@ public class CommonEditor { } public static class DeathEffectPane> { - protected Supplier conditionSupplier; - protected String title; - protected Editor editor; - protected String applyToHint; + protected final Supplier conditionSupplier; + protected final String title; + protected final String applyToHint; EFFECT effect; @@ -220,7 +219,7 @@ public class CommonEditor { private JSpinner effectAPMax; private JList sourceConditionsList; - private ConditionEffectEditorPane sourceConditionPane = new ConditionEffectEditorPane<>(); + private final ConditionEffectEditorPane sourceConditionPane; /* @@ -229,19 +228,18 @@ public class CommonEditor { public DeathEffectPane(String title, Supplier conditionSupplier, Editor editor, String applyToHint) { this.title = title; this.conditionSupplier = conditionSupplier; - this.editor = editor; - this.applyToHint = applyToHint; + this.sourceConditionPane = new ConditionEffectEditorPane<>(editor); + if (applyToHint == null || applyToHint == "") { + this.applyToHint = ""; + } else { + this.applyToHint = " (%s)".formatted(applyToHint); + } } void createDeathEffectPaneContent(FieldUpdateListener listener, boolean writable, EFFECT e, MODEL sourceConditionsModel) { effect = e; sourceConditionPane.conditionsModel = sourceConditionsModel; - if (applyToHint == null || applyToHint == "") { - applyToHint = ""; - } else { - applyToHint = " (%s)".formatted(applyToHint); - } effectPane = new CollapsiblePanel(title); effectPane.setLayout(new JideBoxLayout(effectPane, JideBoxLayout.PAGE_AXIS)); @@ -268,7 +266,7 @@ public class CommonEditor { BasicLambdaWithReturn selectedGetSource = () -> sourceConditionPane.selectedCondition; BasicLambda selectedResetSource = () -> sourceConditionPane.selectedCondition = null; BasicLambdaWithArg updatePaneSource = (editorPane) -> sourceConditionPane.updateEffectTimedConditionEditorPane( - editorPane, sourceConditionPane.selectedCondition, listener, editor); + editorPane, sourceConditionPane.selectedCondition, listener); var resultSource = UiUtils.getCollapsibleItemList(listener, sourceConditionPane.conditionsModel, selectedResetSource, selectedSetSource, selectedGetSource, (x) -> { @@ -305,6 +303,7 @@ public class CommonEditor { } static class ConditionEffectEditorPane> { + private final Editor editor; ELEMENT selectedCondition; MODEL conditionsModel; @@ -318,6 +317,10 @@ public class CommonEditor { JRadioButton conditionForever; JSpinner conditionDuration; + ConditionEffectEditorPane(Editor editor) { + this.editor = editor; + } + public void updateEffectTimedConditionWidgets(ELEMENT condition) { boolean immunity = condition.isImmunity(); boolean clear = condition.isClear(); @@ -334,16 +337,16 @@ public class CommonEditor { conditionForever.setEnabled(!clear); } - public void updateEffectTimedConditionEditorPane(JPanel pane, ELEMENT condition, final FieldUpdateListener listener, Editor e) { + public void updateEffectTimedConditionEditorPane(JPanel pane, ELEMENT condition, final FieldUpdateListener listener) { pane.removeAll(); if (conditionBox != null) { - e.removeElementListener(conditionBox); + editor.removeElementListener(conditionBox); } - boolean writable = e.target.writable; - Project proj = e.target.getProject(); + boolean writable = editor.target.writable; + Project proj = editor.target.getProject(); - conditionBox = e.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, + conditionBox = editor.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, listener); conditionChance = Editor.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); From c0e24b4cf5d2fe360a1f4d15551bb7218aeec1b7 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 18:45:15 +0200 Subject: [PATCH 85/94] fix bug, where condition buttons are enabled in readonly mode --- DEDUP-TODO.md | 4 +--- .../ui/gamedataeditors/CommonEditor.java | 18 +++++++++++++----- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/DEDUP-TODO.md b/DEDUP-TODO.md index f3c5160..9ea4c9d 100644 --- a/DEDUP-TODO.md +++ b/DEDUP-TODO.md @@ -4,7 +4,5 @@ There are probably a lot of things that could be optimized, which will not be on this list (which will probably also be done, they are just not important enough to track them) - -- check, why for example the "Forever" button is active for not altered entities (ex.: NPC->hitEffect) if they have a condition already there - - apparently that's always been like that... (or at least on the most recent main branch) +- diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index f44c671..18a1d0f 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -321,20 +321,28 @@ public class CommonEditor { this.editor = editor; } - public void updateEffectTimedConditionWidgets(ELEMENT condition) { + public void updateEffectTimedConditionWidgets(ELEMENT condition) { + boolean writable = editor.target.writable; + boolean immunity = condition.isImmunity(); boolean clear = condition.isClear(); boolean forever = condition.isInfinite(); conditionClear.setSelected(clear); conditionApply.setSelected(!clear && !immunity); - conditionMagnitude.setEnabled(!clear && !immunity); conditionImmunity.setSelected(immunity); conditionTimed.setSelected(!forever); - conditionTimed.setEnabled(!clear); - conditionDuration.setEnabled(!clear && !forever); conditionForever.setSelected(forever); - conditionForever.setEnabled(!clear); + + conditionDuration.setEnabled(!clear && !forever && writable); + + conditionClear.setEnabled(writable); + conditionApply.setEnabled(writable); + conditionMagnitude.setEnabled(!clear && !immunity && writable); + + conditionImmunity.setEnabled(writable); + conditionTimed.setEnabled(!clear && writable); + conditionForever.setEnabled(!clear && writable); } public void updateEffectTimedConditionEditorPane(JPanel pane, ELEMENT condition, final FieldUpdateListener listener) { From f9f1caafc6e5d0436f944b1b67876c13fa627917 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 18:57:53 +0200 Subject: [PATCH 86/94] extract some code --- .../ui/gamedataeditors/CommonEditor.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 18a1d0f..8203071 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -445,18 +445,14 @@ public class CommonEditor { } else if (source == conditionApply && (Boolean) value) { selectedCondition.magnitude = (Integer) conditionMagnitude.getValue(); selectedCondition.duration = conditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) conditionDuration.getValue(); - if (selectedCondition.duration == null || selectedCondition.duration == ActorCondition.DURATION_NONE) { - selectedCondition.duration = 1; - } + setDurationToDefaultIfNone(); updateEffectTimedConditionWidgets(selectedCondition); conditionsModel.itemChanged(selectedCondition); updateHit = true; } else if (source == conditionImmunity && (Boolean) value) { selectedCondition.magnitude = ActorCondition.MAGNITUDE_CLEAR; selectedCondition.duration = conditionForever.isSelected() ? ActorCondition.DURATION_FOREVER : (Integer) conditionDuration.getValue(); - if (selectedCondition.duration == null || selectedCondition.duration == ActorCondition.DURATION_NONE) { - selectedCondition.duration = 1; - } + setDurationToDefaultIfNone(); updateEffectTimedConditionWidgets(selectedCondition); conditionsModel.itemChanged(selectedCondition); updateHit = true; @@ -466,9 +462,7 @@ public class CommonEditor { updateHit = true; } else if (source == conditionTimed && (Boolean) value) { selectedCondition.duration = (Integer) conditionDuration.getValue(); - if (selectedCondition.duration == null || selectedCondition.duration == ActorCondition.DURATION_NONE) { - selectedCondition.duration = 1; - } + setDurationToDefaultIfNone(); updateEffectTimedConditionWidgets(selectedCondition); conditionsModel.itemChanged(selectedCondition); updateHit = true; @@ -487,6 +481,12 @@ public class CommonEditor { } return updateHit; } + + private void setDurationToDefaultIfNone() { + if (selectedCondition.duration == null || selectedCondition.duration == ActorCondition.DURATION_NONE) { + selectedCondition.duration = 1; + } + } } //region list-models From 8f5452b4879ebeccdbca72b9d9b7bb75f446063c Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 19:11:56 +0200 Subject: [PATCH 87/94] add myself to Contributor list --- src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java index aec5e70..6cd6637 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java @@ -50,6 +50,7 @@ public class AboutEditor extends Editor { "Quentin Delvallet
" + "Žižkin
" + "Gonk
" + + "OMGeeky
" + "
" + "This project uses the following libraries:
" + "JSON.simple by Yidong Fang & Chris Nokleberg.
" + From 6c296868c0d228d84759497ff23edaf0c8238c61 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 19:50:35 +0200 Subject: [PATCH 88/94] add null check --- .../rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 8203071..b45e718 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -350,6 +350,11 @@ public class CommonEditor { if (conditionBox != null) { editor.removeElementListener(conditionBox); } + if (condition == null) { + pane.revalidate(); + pane.repaint(); + return; + } boolean writable = editor.target.writable; Project proj = editor.target.getProject(); From 1c83eedd809866f1060ce4e18f53d95c8f0f8a93 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 20:10:18 +0200 Subject: [PATCH 89/94] format --- .idea/codeStyles/Project.xml | 5 ++ .../rpg/atcontentstudio/ATContentStudio.java | 10 ++-- .../model/GameDataElement.java | 37 ++++++------- .../rpg/atcontentstudio/model/Project.java | 6 ++- .../rpg/atcontentstudio/model/Workspace.java | 40 +++++++------- .../model/bookmarks/BookmarkEntry.java | 8 ++- .../model/gamedata/ActorCondition.java | 8 +-- .../model/gamedata/Common.java | 54 ++++++++++++------- .../model/gamedata/Dialogue.java | 8 +-- .../model/gamedata/Droplist.java | 8 +-- .../model/gamedata/GameDataCategory.java | 3 +- .../atcontentstudio/model/gamedata/Item.java | 13 ++--- .../model/gamedata/ItemCategory.java | 8 +-- .../model/gamedata/JSONElement.java | 2 +- .../atcontentstudio/model/gamedata/NPC.java | 12 ++--- .../atcontentstudio/model/gamedata/Quest.java | 8 +-- .../model/gamedata/QuestStage.java | 8 +-- .../atcontentstudio/model/maps/KeyArea.java | 3 +- .../model/maps/ReplaceArea.java | 3 +- .../rpg/atcontentstudio/ui/AboutEditor.java | 6 ++- .../gpl/rpg/atcontentstudio/ui/Editor.java | 29 +++++----- .../atcontentstudio/ui/NotificationsPane.java | 1 - .../ui/OrderedListenerListModel.java | 1 - .../rpg/atcontentstudio/ui/ProjectsTree.java | 12 +++-- .../atcontentstudio/ui/WorkspaceActions.java | 9 ++-- .../gamedataeditors/ActorConditionEditor.java | 18 +++---- .../ui/gamedataeditors/CommonEditor.java | 15 ++++-- .../ui/gamedataeditors/DialogueEditor.java | 6 ++- .../ui/gamedataeditors/ItemEditor.java | 41 ++++++++------ .../ui/gamedataeditors/NPCEditor.java | 17 +++--- .../ui/gamedataeditors/QuestEditor.java | 37 +++++++------ .../atcontentstudio/ui/map/TMXMapEditor.java | 15 ++++-- .../ui/tools/ItemsTableView.java | 4 +- .../rpg/atcontentstudio/utils/FileUtils.java | 3 +- .../rpg/atcontentstudio/utils/UiUtils.java | 7 +-- 35 files changed, 270 insertions(+), 195 deletions(-) diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 386fbca..3e9de3b 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -1,8 +1,13 @@ + + + diff --git a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java index 30c787d..0afa335 100644 --- a/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java +++ b/src/com/gpl/rpg/atcontentstudio/ATContentStudio.java @@ -152,13 +152,13 @@ public class ATContentStudio { style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";"); style.append("font-size:" + font.getSize() + "pt;"); style.append("background-color: rgb(" + color.getRed() + "," + color.getGreen() + "," + color.getBlue() - + ");"); + + ");"); JEditorPane ep = new JEditorPane("text/html", - "" + "You are not running the latest ATCS version.
" - + "You can get the latest version (" + lastLine + ") by clicking the link below.
" - + "" + DOWNLOAD_URL + "
" + "
" - + ""); + "" + "You are not running the latest ATCS version.
" + + "You can get the latest version (" + lastLine + ") by clicking the link below.
" + + "" + DOWNLOAD_URL + "
" + "
" + + ""); ep.setEditable(false); ep.setBorder(null); diff --git a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java index 65f5fae..584ee1e 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/GameDataElement.java @@ -203,18 +203,19 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable { public abstract List attemptSave(); - /** - * Checks if the current state indicates that parsing/linking should be skipped. - * @return true if the operation should be skipped, false otherwise - */ - protected boolean shouldSkipParseOrLink() { + /** + * Checks if the current state indicates that parsing/linking should be skipped. + * + * @return true if the operation should be skipped, false otherwise + */ + protected boolean shouldSkipParseOrLink() { if (shouldSkipParse()) return true; if (this.state == State.linked) { - //Already linked. - return true; - } - return false; - } + //Already linked. + return true; + } + return false; + } protected boolean shouldSkipParse() { if (this.state == State.created || this.state == State.modified || this.state == State.saved) { @@ -225,12 +226,12 @@ public abstract class GameDataElement implements ProjectTreeNode, Serializable { } /** - * Ensures the element is parsed if needed based on its current state. - */ - protected void ensureParseIfNeeded() { - if (this.state == State.init) { - //Not parsed yet. - this.parse(); - } - } + * Ensures the element is parsed if needed based on its current state. + */ + protected void ensureParseIfNeeded() { + if (this.state == State.init) { + //Not parsed yet. + this.parse(); + } + } } diff --git a/src/com/gpl/rpg/atcontentstudio/model/Project.java b/src/com/gpl/rpg/atcontentstudio/model/Project.java index baea51c..8ae3fe0 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/Project.java +++ b/src/com/gpl/rpg/atcontentstudio/model/Project.java @@ -1105,13 +1105,15 @@ public class Project implements ProjectTreeNode, Serializable { // } Map, List> writtenFilesPerDataType = new LinkedHashMap, List>(); List writtenFiles; - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.actorConditions, alteredContent.gameData.actorConditions, baseContent.gameData.actorConditions, ActorCondition.class, tmpJsonDataDir); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.actorConditions, alteredContent.gameData.actorConditions, baseContent.gameData.actorConditions, ActorCondition.class, + tmpJsonDataDir); writtenFilesPerDataType.put(ActorCondition.class, writtenFiles); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.dialogues, alteredContent.gameData.dialogues, baseContent.gameData.dialogues, Dialogue.class, tmpJsonDataDir); writtenFilesPerDataType.put(Dialogue.class, writtenFiles); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.droplists, alteredContent.gameData.droplists, baseContent.gameData.droplists, Droplist.class, tmpJsonDataDir); writtenFilesPerDataType.put(Droplist.class, writtenFiles); - writtenFiles = writeDataDeltaForDataType(createdContent.gameData.itemCategories, alteredContent.gameData.itemCategories, baseContent.gameData.itemCategories, ItemCategory.class, tmpJsonDataDir); + writtenFiles = writeDataDeltaForDataType(createdContent.gameData.itemCategories, alteredContent.gameData.itemCategories, baseContent.gameData.itemCategories, ItemCategory.class, + tmpJsonDataDir); writtenFilesPerDataType.put(ItemCategory.class, writtenFiles); writtenFiles = writeDataDeltaForDataType(createdContent.gameData.items, alteredContent.gameData.items, baseContent.gameData.items, Item.class, tmpJsonDataDir); writtenFilesPerDataType.put(Item.class, writtenFiles); diff --git a/src/com/gpl/rpg/atcontentstudio/model/Workspace.java b/src/com/gpl/rpg/atcontentstudio/model/Workspace.java index a1d485f..1dcae03 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/Workspace.java +++ b/src/com/gpl/rpg/atcontentstudio/model/Workspace.java @@ -44,7 +44,7 @@ public class Workspace implements ProjectTreeNode, Serializable { workspaceRoot.mkdir(); } catch (SecurityException e) { Notification.addError("Error creating workspace directory: " - + e.getMessage()); + + e.getMessage()); e.printStackTrace(); } } @@ -55,12 +55,12 @@ public class Workspace implements ProjectTreeNode, Serializable { settingsFile.createNewFile(); } catch (IOException e) { Notification.addError("Error creating workspace datafile: " - + e.getMessage()); + + e.getMessage()); e.printStackTrace(); } } Notification.addSuccess("New workspace created: " - + workspaceRoot.getAbsolutePath()); + + workspaceRoot.getAbsolutePath()); save(); } @@ -169,26 +169,26 @@ public class Workspace implements ProjectTreeNode, Serializable { public static void createProject(final String projectName, final File gameSourceFolder, final Project.ResourceSet sourceSet) { WorkerDialog.showTaskMessage("Creating project " + projectName + "...", - ATContentStudio.frame, new Runnable() { + ATContentStudio.frame, new Runnable() { @Override public void run() { if (activeWorkspace.projectsName.contains(projectName)) { Notification.addError("A project named " - + projectName - + " already exists in this workspace."); + + projectName + + " already exists in this workspace."); return; } Project p = new Project(activeWorkspace, projectName, - gameSourceFolder, sourceSet); + gameSourceFolder, sourceSet); activeWorkspace.projects.add(p); activeWorkspace.projectsName.add(projectName); activeWorkspace.projectsOpenByName.put(projectName, - p.open); + p.open); activeWorkspace.knownMapSourcesFolders .add(gameSourceFolder); p.notifyCreated(); Notification.addSuccess("Project " + projectName - + " successfully created"); + + " successfully created"); saveActive(); } }); @@ -210,19 +210,19 @@ public class Workspace implements ProjectTreeNode, Serializable { public static void openProject(final ClosedProject cp) { WorkerDialog.showTaskMessage("Opening project " + cp.name + "...", - ATContentStudio.frame, new Runnable() { + ATContentStudio.frame, new Runnable() { @Override public void run() { int index = activeWorkspace.projects.indexOf(cp); if (index < 0) { Notification .addError("Cannot open unknown project " - + cp.name); + + cp.name); return; } cp.childrenRemoved(new ArrayList()); Project p = Project.fromFolder(activeWorkspace, - new File(activeWorkspace.baseFolder, cp.name)); + new File(activeWorkspace.baseFolder, cp.name)); p.open(); activeWorkspace.projects.set(index, p); activeWorkspace.projectsOpenByName.put(p.name, true); @@ -246,14 +246,14 @@ public class Workspace implements ProjectTreeNode, Serializable { } else { Notification .addError("Failed to open project " - + projectName - + ". Removing it from workspace (not from filesystem though)."); + + projectName + + ". Removing it from workspace (not from filesystem though)."); projectsFailed.add(projectName); } } else { Notification.addError("Unable to find project " - + projectName - + "'s root folder. Removing it from workspace"); + + projectName + + "'s root folder. Removing it from workspace"); projectsFailed.add(projectName); } } else { @@ -299,10 +299,10 @@ public class Workspace implements ProjectTreeNode, Serializable { activeWorkspace.projectsName.remove(cp.name); if (delete(new File(activeWorkspace.baseFolder, cp.name))) { Notification.addSuccess("Closed project " + cp.name - + " successfully deleted."); + + " successfully deleted."); } else { Notification.addError("Error while deleting closed project " - + cp.name + ". Files may remain in the workspace."); + + cp.name + ". Files may remain in the workspace."); } saveActive(); } @@ -314,10 +314,10 @@ public class Workspace implements ProjectTreeNode, Serializable { activeWorkspace.projectsName.remove(p.name); if (delete(p.baseFolder)) { Notification.addSuccess("Project " + p.name - + " successfully deleted."); + + " successfully deleted."); } else { Notification.addError("Error while deleting project " + p.name - + ". Files may remain in the workspace."); + + ". Files may remain in the workspace."); } saveActive(); } diff --git a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java index 1827e20..a18498d 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java +++ b/src/com/gpl/rpg/atcontentstudio/model/bookmarks/BookmarkEntry.java @@ -91,7 +91,13 @@ public class BookmarkEntry implements BookmarkNode { if (text.length() > 60) { text = text.substring(0, 57) + "..."; } - return ((GameDataElement) bookmarkedElement).getDataType().toString() + "/" + ((Quest) ((QuestStage) bookmarkedElement).parent).id + "#" + ((QuestStage) bookmarkedElement).progress + ":" + text; + return ((GameDataElement) bookmarkedElement).getDataType().toString() + + "/" + + ((Quest) ((QuestStage) bookmarkedElement).parent).id + + "#" + + ((QuestStage) bookmarkedElement).progress + + ":" + + text; } else { return ((GameDataElement) bookmarkedElement).getDataType().toString() + "/" + ((GameDataElement) bookmarkedElement).getDesc(); } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java index 2643a4f..9ae2ee1 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ActorCondition.java @@ -222,10 +222,10 @@ public class ActorCondition extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); if (this.icon_id != null) { String spritesheetId = this.icon_id.split(":")[0]; if (getProject().getSpritesheet(spritesheetId) == null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index e66a172..4a967d5 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -10,7 +10,7 @@ import java.util.Map; public final class Common { - public static void actorConditionElementChanged(List list, GameDataElement oldOne, GameDataElement newOne,GameDataElement backlink){ + public static void actorConditionElementChanged(List list, GameDataElement oldOne, GameDataElement newOne, GameDataElement backlink) { if (list != null) { for (T c : list) { if (c.condition == oldOne) { @@ -22,6 +22,7 @@ public final class Common { } } + //region link common stuff public static void linkConditions(List conditions, Project proj, GameDataElement backlink) { if (conditions != null) { @@ -31,19 +32,20 @@ public final class Common { } } } - public static void linkEffects(HitEffect effect, Project proj, GameDataElement backlink){ + + public static void linkEffects(HitEffect effect, Project proj, GameDataElement backlink) { linkEffects((DeathEffect) effect, proj, backlink); - if (effect != null) - { + if (effect != null) { linkConditions(effect.conditions_target, proj, backlink); } } - public static void linkEffects(DeathEffect effect, Project proj, GameDataElement backlink){ - if (effect != null) - { + + public static void linkEffects(DeathEffect effect, Project proj, GameDataElement backlink) { + if (effect != null) { linkConditions(effect.conditions_source, proj, backlink); } } + public static void linkIcon(Project proj, String iconId, GameDataElement backlink) { if (iconId != null) { String spritesheetId = iconId.split(":")[0]; @@ -63,6 +65,7 @@ public final class Common { else parent.put("max", defaultValue); } } + public static void writeMinMaxToMap(Map parent, String key, Integer min, Integer max, int defaultValue) { if (min != null || max != null) { Map minMaxMap = new LinkedHashMap(); @@ -70,6 +73,7 @@ public final class Common { writeMinMaxToMap(minMaxMap, min, max, defaultValue); } } + public static void writeDescriptionToMap(Map parent, String description) { if (description != null) parent.put("description", description); } @@ -77,12 +81,14 @@ public final class Common { public static void writeIconToMap(Map parent, String icon_id) { if (icon_id != null) parent.put("iconID", icon_id); } + public static void writeHitReceivedEffectToMap(Map parent, HitReceivedEffect effect) { - if(effect != null){ + if (effect != null) { writeHitEffectToMap(parent, effect); writeBasicEffectObjectToMap(effect.target, parent, "increaseAttackerCurrentHP", "increaseAttackerCurrentAP"); } } + public static void writeHitReceivedEffectToMap(Map parent, HitReceivedEffect effect, String key) { if (effect != null) { Map effectJson = new LinkedHashMap(); @@ -90,12 +96,14 @@ public final class Common { writeHitReceivedEffectToMap(effectJson, effect); } } + public static void writeHitEffectToMap(Map parent, HitEffect effect) { - if(effect != null){ + if (effect != null) { writeDeathEffectToMap(parent, effect); writeTimedActorConditionEffectObjectToMap(effect.conditions_target, parent, "conditionsTarget"); } } + public static void writeHitEffectToMap(Map parent, HitEffect effect, String key) { if (effect != null) { Map effectJson = new LinkedHashMap(); @@ -103,10 +111,12 @@ public final class Common { writeHitEffectToMap(effectJson, effect); } } + public static void writeDeathEffectToMap(Map parent, DeathEffect effect) { writeBasicEffectObjectToMap(effect, parent, "increaseCurrentHP", "increaseCurrentAP"); writeTimedActorConditionEffectObjectToMap(effect.conditions_source, parent, "conditionsSource"); } + public static void writeDeathEffectToMap(Map parent, DeathEffect effect, String key) { if (effect != null) { Map effectJson = new LinkedHashMap(); @@ -154,6 +164,7 @@ public final class Common { parent.put("chance", JSONElement.printJsonChance(condition.chance)); } } + //endregion public static class TimedActorConditionEffect extends ActorConditionEffect { //Available from parsed state @@ -169,12 +180,15 @@ public final class Common { cclone.duration = this.duration; return cclone; } - public boolean isInfinite(){ + + public boolean isInfinite() { return duration != null && duration.equals(ActorCondition.DURATION_FOREVER); } - public boolean isImmunity(){ + + public boolean isImmunity() { return (super.isClear()) && (duration != null && duration > ActorCondition.DURATION_NONE); } + @Override public boolean isClear() { return (super.isClear()) && (duration == null || duration.equals(ActorCondition.DURATION_NONE)); @@ -188,7 +202,8 @@ public final class Common { //Available from linked state public ActorCondition condition = null; - public boolean isClear(){ + + public boolean isClear() { return magnitude == null || magnitude.equals(ActorCondition.MAGNITUDE_CLEAR); } } @@ -287,9 +302,10 @@ public final class Common { public static class DeathEffect extends BasicEffect { //Available from parsed state public List conditions_source = null; + @Override - public boolean isNull(){ - if(!super.isNull()) return false; + public boolean isNull() { + if (!super.isNull()) return false; if (conditions_source != null) return false; return true; } @@ -298,9 +314,10 @@ public final class Common { public static class HitEffect extends DeathEffect { //Available from parsed state public List conditions_target = null; + @Override - public boolean isNull(){ - if(!super.isNull()) return false; + public boolean isNull() { + if (!super.isNull()) return false; if (conditions_target != null) return false; return true; } @@ -309,9 +326,10 @@ public final class Common { public static class HitReceivedEffect extends Common.HitEffect { //Available from parsed state public BasicEffect target = new BasicEffect(); + @Override - public boolean isNull(){ - if(!super.isNull()) return false; + public boolean isNull() { + if (!super.isNull()) return false; if (!target.isNull()) return false; return true; } diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java index 657217f..754f0bc 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Dialogue.java @@ -205,10 +205,10 @@ public class Dialogue extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking dialogue " + id + ". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java index 900b80c..fa60326 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Droplist.java @@ -128,10 +128,10 @@ public class Droplist extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking droplist " + id + ". No parent project found."); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java index 3b1edd3..3b6b769 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/GameDataCategory.java @@ -220,7 +220,8 @@ public class GameDataCategory extends ArrayList implem break; } } - events.add(new SaveEvent(SaveEvent.Type.alsoSave, node, true, "There are " + containedIds.get(node.id) + " elements with this ID in this category. Change the conflicting IDs before saving.")); + events.add(new SaveEvent(SaveEvent.Type.alsoSave, node, true, + "There are " + containedIds.get(node.id) + " elements with this ID in this category. Change the conflicting IDs before saving.")); } } if (checkImpactedCategory && impactedCategory != null) { diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java index 365aa65..032b91a 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Item.java @@ -206,10 +206,10 @@ public class Item extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item " + id + ". No parent project found."); @@ -381,7 +381,7 @@ public class Item extends JSONElement { } writeHitEffectToMap(itemJson, this.hit_effect, "hitEffect"); writeHitReceivedEffectToMap(itemJson, this.hit_received_effect, "hitReceivedEffect"); - + String key; if (this.category != null && this.category.action_type != null && this.category.action_type == ItemCategory.ActionType.equip) { key = "killEffect"; @@ -438,7 +438,8 @@ public class Item extends JSONElement { public int calculateEquipCost(boolean isWeapon) { final int costBC = (int) (3 * Math.pow(Math.max(0, zeroForNull(equip_effect.increase_block_chance)), 2.5) + 28 * zeroForNull(equip_effect.increase_block_chance)); - final int costAC = (int) (0.4 * Math.pow(Math.max(0, zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6 * Math.pow(Math.abs(Math.min(0, zeroForNull(equip_effect.increase_attack_chance))), 2.7)); + final int costAC = (int) (0.4 * Math.pow(Math.max(0, zeroForNull(equip_effect.increase_attack_chance)), 2.5) - 6 * Math.pow( + Math.abs(Math.min(0, zeroForNull(equip_effect.increase_attack_chance))), 2.7)); final int costAP = isWeapon ? (int) (0.2 * Math.pow(10.0f / zeroForNull(equip_effect.increase_attack_cost), 8) - 25 * zeroForNull(equip_effect.increase_attack_cost)) : -3125 * zeroForNull(equip_effect.increase_attack_cost); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java index 1b9fe82..bc8dd33 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/ItemCategory.java @@ -171,10 +171,10 @@ public class ItemCategory extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java index fdc9502..b8b1966 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/JSONElement.java @@ -21,7 +21,7 @@ public abstract class JSONElement extends GameDataElement { @SuppressWarnings("rawtypes") public void parse() { - if (shouldSkipParse()) { + if (shouldSkipParse()) { return; } JSONParser parser = new JSONParser(); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java index 3dec0fe..632d879 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/NPC.java @@ -12,7 +12,6 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; -import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -187,10 +186,10 @@ public class NPC extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); Project proj = getProject(); if (proj == null) { Notification.addError("Error linking item " + id + ". No parent project found."); @@ -345,7 +344,8 @@ public class NPC extends JSONElement { avgCrit = (double) (critical_skill / 100.0) * critical_multiplier; } double avgAttackHP = attacksPerTurn * ((double) (attack_chance != null ? attack_chance : 0) / 100.0) * avgDamagePotential * (1 + avgCrit); - double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double) (block_chance != null ? block_chance : 0) / 100.0))) + (EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0)); + double avgDefenseHP = ((max_hp != null ? max_hp : 1) * (1 + ((double) (block_chance != null ? block_chance : 0) / 100.0))) + + (EXP_FACTOR_DAMAGERESISTANCE * (damage_resistance != null ? damage_resistance : 0)); double attackConditionBonus = 0; if (hit_effect != null && hit_effect.conditions_target != null && hit_effect.conditions_target.size() > 0) { attackConditionBonus = 50; diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java index 6a2a79a..77ad5b7 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Quest.java @@ -112,10 +112,10 @@ public class Quest extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); for (QuestStage stage : stages) { stage.link(); diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java index f8133ca..2130bd5 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/QuestStage.java @@ -59,10 +59,10 @@ public class QuestStage extends JSONElement { @Override public void link() { - if (shouldSkipParseOrLink()) { - return; - } - ensureParseIfNeeded(); + if (shouldSkipParseOrLink()) { + return; + } + ensureParseIfNeeded(); //Nothing to link to :D this.state = State.linked; diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java index f19525a..c370b47 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/KeyArea.java @@ -101,7 +101,8 @@ public class KeyArea extends MapObject { public void updateNameFromRequirementChange() { if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { - name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); + name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString( + requirement.required_value)); } else if (oldSchoolRequirement) { int i = 0; String futureName = requirement.type.toString() + "#" + Integer.toString(i); diff --git a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java index 4438c69..edd8cd3 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java +++ b/src/com/gpl/rpg/atcontentstudio/model/maps/ReplaceArea.java @@ -102,7 +102,8 @@ public class ReplaceArea extends MapObject { //Don't use yet ! public void updateNameFromRequirementChange() { if (oldSchoolRequirement && Requirement.RequirementType.questProgress.equals(requirement.type) && (requirement.negated == null || !requirement.negated)) { - name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString(requirement.required_value)); + name = (requirement.negated != null && requirement.negated) ? "NOT " : "" + requirement.required_obj_id + ":" + ((requirement.required_value == null) ? "" : Integer.toString( + requirement.required_value)); } else if (oldSchoolRequirement) { int i = 0; String futureName = requirement.type.toString() + "#" + Integer.toString(i); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java index 6cd6637..49c5e8e 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/AboutEditor.java @@ -152,12 +152,14 @@ public class AboutEditor extends Editor { editorTabsHolder.add("Welcome", getInfoPane(WELCOME_STRING, "text/html")); editorTabsHolder.add("JSON.simple License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JSON.simple.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("RSyntaxTextArea License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/RSyntaxTextArea.License.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("RSyntaxTextArea License", + getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/RSyntaxTextArea.License.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("JIDE Common Layer License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.JIDE.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("libtiled-java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.libtiled.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("prefuse License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/license-prefuse.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("BeanShell License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.LGPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); - editorTabsHolder.add("SipHash for Java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.siphash-zackehh.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); + editorTabsHolder.add("SipHash for Java License", + getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.siphash-zackehh.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("jsoup License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.jsoup.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("General PO Parser License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.GPLv3.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); editorTabsHolder.add("Minify.java License", getInfoPane(new Scanner(ATContentStudio.class.getResourceAsStream("/LICENSE.minify.txt"), "UTF-8").useDelimiter("\\A").next(), "text/text")); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java index 1fbd519..bbdaee6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/Editor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/Editor.java @@ -189,6 +189,7 @@ public abstract class Editor extends JPanel implements ProjectElementListener { }); return tfField; } + public static T addTextComponent(JPanel pane, String label, boolean editable, final FieldUpdateListener listener, T tfField, boolean specialNewLinesHandling, boolean scrollable) { JPanel tfPane = new JPanel(); tfPane.setLayout(new JideBoxLayout(tfPane, JideBoxLayout.LINE_AXIS, 6)); @@ -196,9 +197,9 @@ public abstract class Editor extends JPanel implements ProjectElementListener { tfPane.add(tfLabel, JideBoxLayout.FIX); tfField.setEditable(editable); JComponent component; - if (scrollable){ + if (scrollable) { component = new JScrollPane(tfField); - }else{ + } else { component = tfField; } tfPane.add(component, JideBoxLayout.VARY); @@ -218,21 +219,21 @@ public abstract class Editor extends JPanel implements ProjectElementListener { @Override public void removeUpdate(DocumentEvent e) { String text = tfField.getText(); - if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + if (specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); listener.valueChanged(tfField, text); } @Override public void insertUpdate(DocumentEvent e) { String text = tfField.getText(); - if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + if (specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); listener.valueChanged(tfField, text); } @Override public void changedUpdate(DocumentEvent e) { String text = tfField.getText(); - if(specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); + if (specialNewLinesHandling) text = text.replaceAll("\n", Matcher.quoteReplacement("\n")); listener.valueChanged(tfField, text); } }); @@ -291,11 +292,12 @@ public abstract class Editor extends JPanel implements ProjectElementListener { }); return spinner; } + public static JSpinner addIntegerField(JPanel pane, String label, Integer initialValue, Integer defaultValue, boolean allowNegatives, boolean editable, final FieldUpdateListener listener) { int value = initialValue != null ? initialValue : defaultValue; - int minimum = allowNegatives ? Integer.MIN_VALUE : 0; + int minimum = allowNegatives ? Integer.MIN_VALUE : 0; int maximum = Integer.MAX_VALUE; - return addNumberField(pane, label, editable, listener, minimum, maximum, 1, value, defaultValue); + return addNumberField(pane, label, editable, listener, minimum, maximum, 1, value, defaultValue); } @@ -361,7 +363,10 @@ public abstract class Editor extends JPanel implements ProjectElementListener { entryTypeBox.setEnabled(editable); tfPane.add(entryTypeBox, JideBoxLayout.FIX); /////////////////////////////////////////////////////////////////////////////////////////////////// make sure "chance" is between 1 and 100. If lower than 1 get 1. If higher than 100, get chance/maxChance * 100... Then do the same with defaultChance, in case no value exist. - final SpinnerNumberModel percentModel = new SpinnerNumberModel(initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 / defaultMaxChance)), 1, 100, 1); + final SpinnerNumberModel percentModel = new SpinnerNumberModel( + initialValue != null ? ((chance > 1 ? chance : 1) < 100 ? chance : (chance * 100 / maxChance)) : ((defaultChance > 1 ? defaultChance : 1) < 100 ? defaultChance : (defaultChance * 100 / + defaultMaxChance)), + 1, 100, 1); final SpinnerNumberModel ratioChanceModel = new SpinnerNumberModel(initialValue != null ? chance : defaultChance, 1, Integer.MAX_VALUE, 1); final JSpinner chanceSpinner = new JSpinner(currentFormIsRatio ? ratioChanceModel : percentModel); @@ -1105,10 +1110,10 @@ public abstract class Editor extends JPanel implements ProjectElementListener { } - public > void updateConditionEffect(ActorCondition value, - GameDataElement backlink, - E selectedHitEffectTargetCondition, - T hitTargetConditionsModel) { + public > void updateConditionEffect(ActorCondition value, + GameDataElement backlink, + E selectedHitEffectTargetCondition, + T hitTargetConditionsModel) { if (selectedHitEffectTargetCondition.condition != null) { selectedHitEffectTargetCondition.condition.removeBacklink(backlink); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java index 3606b76..4cd2f8b 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/NotificationsPane.java @@ -5,7 +5,6 @@ import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.NotificationListener; import javax.swing.*; -import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.awt.*; import java.util.LinkedHashMap; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java index 65c8e3e..f2c2a84 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/OrderedListenerListModel.java @@ -1,6 +1,5 @@ package com.gpl.rpg.atcontentstudio.ui; -import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.util.ArrayList; import java.util.Collection; diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java b/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java index 7b2513a..ffeab2f 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ProjectsTree.java @@ -624,19 +624,25 @@ public class ProjectsTree extends JPanel { public void insertNode(TreePath node) { for (TreeModelListener l : listeners) { - l.treeNodesInserted(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath().getPath(), new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()})); + l.treeNodesInserted(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath().getPath(), + new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, + new Object[]{node.getLastPathComponent()})); } } public void changeNode(TreePath node) { for (TreeModelListener l : listeners) { - l.treeNodesChanged(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()})); + l.treeNodesChanged(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), + new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, + new Object[]{node.getLastPathComponent()})); } } public void removeNode(TreePath node) { for (TreeModelListener l : listeners) { - l.treeNodesRemoved(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, new Object[]{node.getLastPathComponent()})); + l.treeNodesRemoved(new TreeModelEvent(node.getLastPathComponent(), node.getParentPath(), + new int[]{((ProjectTreeNode) node.getParentPath().getLastPathComponent()).getIndex((ProjectTreeNode) node.getLastPathComponent())}, + new Object[]{node.getLastPathComponent()})); } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java index a2072f0..b797632 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/WorkspaceActions.java @@ -65,11 +65,13 @@ public class WorkspaceActions { public ATCSAction deleteProject = new ATCSAction("Delete project", "Deletes the project, and all created/altered data, from disk") { public void actionPerformed(ActionEvent e) { if (selectedNode instanceof Project) { - if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { + if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", + JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { Workspace.deleteProject((Project) selectedNode); } } else if (selectedNode instanceof ClosedProject) { - if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { + if (JOptionPane.showConfirmDialog(ATContentStudio.frame, "Are you sure you wish to delete this project ?\nAll files created for it will be deleted too...", "Delete this project ?", + JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { Workspace.deleteProject((ClosedProject) selectedNode); } } @@ -380,7 +382,8 @@ public class WorkspaceActions { public ATCSAction exitATCS = new ATCSAction("Exit", "Closes the program") { public void actionPerformed(ActionEvent e) { if (Workspace.activeWorkspace.needsSaving()) { - int answer = JOptionPane.showConfirmDialog(ATContentStudio.frame, "There are unsaved changes in your workspace.\nExiting ATCS will discard these changes.\nDo you really want to exit?", "Unsaved changes. Confirm exit.", JOptionPane.YES_NO_OPTION); + int answer = JOptionPane.showConfirmDialog(ATContentStudio.frame, "There are unsaved changes in your workspace.\nExiting ATCS will discard these changes.\nDo you really want to exit?", + "Unsaved changes. Confirm exit.", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { System.exit(0); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java index 03348f0..bba83be 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ActorConditionEditor.java @@ -89,7 +89,7 @@ public class ActorConditionEditor extends JSONElementEditor { } else { roundEffect = new ActorCondition.RoundEffect(); } - roundVisualField = addEnumValueBox(roundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), roundEffect.visual_effect, ac.writable, listener);//addTextField(roundEffectPane, "Visual effect ID: ", roundEffect.visual_effect, ac.writable, listener); + roundVisualField = addEnumValueBox(roundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), roundEffect.visual_effect, ac.writable, listener); roundHpMinField = addIntegerField(roundEffectPane, "HP Bonus Min: ", roundEffect.hp_boost_min, true, ac.writable, listener); roundHpMaxField = addIntegerField(roundEffectPane, "HP Bonus Max: ", roundEffect.hp_boost_max, true, ac.writable, listener); roundApMinField = addIntegerField(roundEffectPane, "AP Bonus Min: ", roundEffect.ap_boost_min, true, ac.writable, listener); @@ -106,7 +106,7 @@ public class ActorConditionEditor extends JSONElementEditor { } else { fullRoundEffect = new ActorCondition.RoundEffect(); } - fullRoundVisualField = addEnumValueBox(fullRoundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), fullRoundEffect.visual_effect, ac.writable, listener);//addTextField(fullRoundEffectPane, "Visual effect ID: ", fullRoundEffect.visual_effect, ac.writable, listener); + fullRoundVisualField = addEnumValueBox(fullRoundEffectPane, "Visual effect ID:", ActorCondition.VisualEffectID.values(), fullRoundEffect.visual_effect, ac.writable, listener); fullRoundHpMinField = addIntegerField(fullRoundEffectPane, "HP Bonus min: ", fullRoundEffect.hp_boost_min, true, ac.writable, listener); fullRoundHpMaxField = addIntegerField(fullRoundEffectPane, "HP Bonus max: ", fullRoundEffect.hp_boost_max, true, ac.writable, listener); fullRoundApMinField = addIntegerField(fullRoundEffectPane, "AP Bonus min: ", fullRoundEffect.ap_boost_min, true, ac.writable, listener); @@ -505,18 +505,17 @@ public class ActorConditionEditor extends JSONElementEditor { } private boolean isEmpty(ActorCondition.RoundEffect round_effect) { - return round_effect == null || ( - round_effect.visual_effect == null && + return round_effect == null || + (round_effect.visual_effect == null && round_effect.hp_boost_min == null && round_effect.hp_boost_max == null && round_effect.ap_boost_min == null && - round_effect.ap_boost_max == null - ); + round_effect.ap_boost_max == null); } private boolean isEmpty(ActorCondition.AbilityEffect ability_effect) { - return ability_effect == null || ( - ability_effect.max_hp_boost == null && + return ability_effect == null || + (ability_effect.max_hp_boost == null && ability_effect.max_ap_boost == null && ability_effect.increase_move_cost == null && ability_effect.increase_use_cost == null && @@ -527,8 +526,7 @@ public class ActorConditionEditor extends JSONElementEditor { ability_effect.increase_damage_max == null && ability_effect.increase_critical_skill == null && ability_effect.increase_block_chance == null && - ability_effect.increase_damage_resistance == null - ); + ability_effect.increase_damage_resistance == null); } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index b45e718..8090851 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -48,7 +48,12 @@ public class CommonEditor { } else { label.setIcon(new ImageIcon(effect.condition.getIcon())); label.setText( - effect.chance + "% chances to give actor condition " + effect.condition.getDesc() + " x" + effect.magnitude + (forever ? " forever" : " for " + effect.duration + " rounds")); + effect.chance + + "% chances to give actor condition " + + effect.condition.getDesc() + + " x" + + effect.magnitude + + (forever ? " forever" : " for " + effect.duration + " rounds")); } } else { label.setText("New, undefined actor condition effect."); @@ -143,7 +148,7 @@ public class CommonEditor { protected final String applyToTargetHint; private JList hitTargetConditionsList; - private final ConditionEffectEditorPane hitTargetConditionPane ; + private final ConditionEffectEditorPane hitTargetConditionPane; /* * create a new HitEffectPane with the selections (probably passed in from last time) @@ -193,7 +198,7 @@ public class CommonEditor { @Override public boolean valueChanged(JComponent source, Object value, GameDataElement backlink) { boolean updateHit = false; - if(super.valueChanged(source, value, backlink)){ + if (super.valueChanged(source, value, backlink)) { updateHit = true; } else if (source == hitTargetConditionsList) { updateHit = true; @@ -295,7 +300,7 @@ public class CommonEditor { updateHit = true; } else if (source == sourceConditionsList) { updateHit = true; - } else if (sourceConditionPane.valueChanged(source, value, backlink)){ + } else if (sourceConditionPane.valueChanged(source, value, backlink)) { updateHit = true; } return updateHit; @@ -360,7 +365,7 @@ public class CommonEditor { Project proj = editor.target.getProject(); conditionBox = editor.addActorConditionBox(pane, proj, "Actor Condition: ", condition.condition, writable, - listener); + listener); conditionChance = Editor.addDoubleField(pane, "Chance: ", condition.chance, writable, listener); conditionClear = new JRadioButton("Clear active condition"); diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java index d2e7b33..71044f0 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/DialogueEditor.java @@ -234,7 +234,8 @@ public class DialogueEditor extends JSONElementEditor { case changeMapFilter: rewardMap = addMapBox(pane, ((Dialogue) target).getProject(), "Map Name: ", reward.map, writable, listener); rewardObjId = null; - rewardObjIdCombo = addEnumValueBox(pane, "Color Filter", TMXMap.ColorFilter.values(), reward.reward_obj_id != null ? TMXMap.ColorFilter.valueOf(reward.reward_obj_id) : TMXMap.ColorFilter.none, writable, listener); + rewardObjIdCombo = addEnumValueBox(pane, "Color Filter", TMXMap.ColorFilter.values(), + reward.reward_obj_id != null ? TMXMap.ColorFilter.valueOf(reward.reward_obj_id) : TMXMap.ColorFilter.none, writable, listener); rewardObj = null; rewardValue = null; break; @@ -278,7 +279,8 @@ public class DialogueEditor extends JSONElementEditor { if (!immunity) radioGroup.add(rewardConditionClear); if (immunity) { - rewardConditionTimed.setSelected(reward.reward_value == null || (!reward.reward_value.equals(ActorCondition.DURATION_FOREVER) && !reward.reward_value.equals(ActorCondition.MAGNITUDE_CLEAR))); + rewardConditionTimed.setSelected( + reward.reward_value == null || (!reward.reward_value.equals(ActorCondition.DURATION_FOREVER) && !reward.reward_value.equals(ActorCondition.MAGNITUDE_CLEAR))); rewardConditionForever.setSelected(reward.reward_value != null && !reward.reward_value.equals(ActorCondition.DURATION_FOREVER)); rewardConditionClear.setSelected(reward.reward_value != null && !reward.reward_value.equals(ActorCondition.MAGNITUDE_CLEAR)); } else { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java index 800ca91..4a27929 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/ItemEditor.java @@ -4,9 +4,14 @@ import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.gamedata.ActorCondition; +import com.gpl.rpg.atcontentstudio.model.gamedata.Item; +import com.gpl.rpg.atcontentstudio.model.gamedata.ItemCategory; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; +import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; +import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.utils.BasicLambda; import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithReturn; @@ -97,7 +102,8 @@ public class ItemEditor extends JSONElementEditor { typeBox = addEnumValueBox(pane, "Type: ", Item.DisplayType.values(), item.display_type, item.writable, listener); manualPriceBox = addIntegerBasedCheckBox(pane, "Has manual price", item.has_manual_price, item.writable, listener); baseManualPrice = item.base_market_cost; - baseCostField = addIntegerField(pane, "Base market cost: ", (item.has_manual_price != null && item.has_manual_price == 1) ? item.base_market_cost : item.computePrice(), false, item.writable, listener); + baseCostField = addIntegerField(pane, "Base market cost: ", (item.has_manual_price != null && item.has_manual_price == 1) ? item.base_market_cost : item.computePrice(), false, item.writable, + listener); if (!manualPriceBox.isSelected()) { baseCostField.setEnabled(false); } @@ -128,22 +134,23 @@ public class ItemEditor extends JSONElementEditor { String titleEquipConditions = "Actor Conditions applied when equipped: "; equipConditionsModel = new EquipConditionsListModel(equipEffect); CommonEditor.ConditionsCellRenderer cellRendererEquipConditions = new CommonEditor.ConditionsCellRenderer(); - BasicLambdaWithArg selectedSetEquipConditions = (value)->selectedEquipEffectCondition = value; - BasicLambdaWithReturn selectedGetEquipConditions = ()->selectedEquipEffectCondition ; - BasicLambda selectedResetEquipConditions = ()->selectedEquipEffectCondition = null; + BasicLambdaWithArg selectedSetEquipConditions = (value) -> selectedEquipEffectCondition = value; + BasicLambdaWithReturn selectedGetEquipConditions = () -> selectedEquipEffectCondition; + BasicLambda selectedResetEquipConditions = () -> selectedEquipEffectCondition = null; BasicLambdaWithArg updatePaneEquipConditions = (editorPane) -> updateEquipConditionEditorPane(editorPane, selectedEquipEffectCondition, listener); var resultEquipConditions = UiUtils.getCollapsibleItemList(listener, - equipConditionsModel, - selectedResetEquipConditions, - selectedSetEquipConditions, - selectedGetEquipConditions, - (x) -> {}, - updatePaneEquipConditions, - item.writable, - ActorConditionEffect::new, - cellRendererEquipConditions, - titleEquipConditions, - (x) -> null); + equipConditionsModel, + selectedResetEquipConditions, + selectedSetEquipConditions, + selectedGetEquipConditions, + (x) -> { + }, + updatePaneEquipConditions, + item.writable, + ActorConditionEffect::new, + cellRendererEquipConditions, + titleEquipConditions, + (x) -> null); equipConditionsList = resultEquipConditions.list; CollapsiblePanel equipConditionsPane = resultEquipConditions.collapsiblePanel; if (item.equip_effect == null || item.equip_effect.conditions == null || item.equip_effect.conditions.isEmpty()) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java index 724a3e1..dfda8e2 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/NPCEditor.java @@ -3,9 +3,13 @@ package com.gpl.rpg.atcontentstudio.ui.gamedataeditors; import com.gpl.rpg.atcontentstudio.ATContentStudio; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; -import com.gpl.rpg.atcontentstudio.model.gamedata.*; +import com.gpl.rpg.atcontentstudio.model.gamedata.Dialogue; +import com.gpl.rpg.atcontentstudio.model.gamedata.Droplist; +import com.gpl.rpg.atcontentstudio.model.gamedata.NPC; import com.gpl.rpg.atcontentstudio.model.sprites.Spritesheet; -import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.ui.CollapsiblePanel; +import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; import com.gpl.rpg.atcontentstudio.ui.gamedataeditors.dialoguetree.DialogueGraphView; import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; @@ -15,7 +19,6 @@ import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; -import java.util.List; import java.util.Objects; import static com.gpl.rpg.atcontentstudio.model.gamedata.Common.*; @@ -57,7 +60,8 @@ public class NPCEditor extends JSONElementEditor { private JSpinner dmgRes; private CommonEditor.HitEffectPane hitEffectPane = new CommonEditor.HitEffectPane("Effect on every hit: ", TimedActorConditionEffect::new, this, null, null); - private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", TimedActorConditionEffect::new, this, "NPC", "Attacker"); + private CommonEditor.HitRecievedEffectPane hitReceivedEffectPane = new CommonEditor.HitRecievedEffectPane("Effect on every hit received: ", TimedActorConditionEffect::new, this, "NPC", + "Attacker"); private CommonEditor.DeathEffectPane deathEffectPane = new CommonEditor.DeathEffectPane("Effect when killed: ", TimedActorConditionEffect::new, this, "Killer"); private JPanel dialogueGraphPane; @@ -170,7 +174,6 @@ public class NPCEditor extends JSONElementEditor { } - public class NPCFieldUpdater implements FieldUpdateListener { @Override @@ -263,7 +266,7 @@ public class NPCEditor extends JSONElementEditor { npc.block_chance = (Integer) value; } else if (source == dmgRes) { npc.damage_resistance = (Integer) value; - } else if(hitEffectPane.valueChanged(source, value, npc)) { + } else if (hitEffectPane.valueChanged(source, value, npc)) { updateHit = true; } else if (hitReceivedEffectPane.valueChanged(source, value, npc)) { updateHitReceived = true; @@ -289,7 +292,7 @@ public class NPCEditor extends JSONElementEditor { if (deathEffectPane.effect.isNull()) { npc.death_effect = null; } else { - npc.death_effect = deathEffectPane. effect; + npc.death_effect = deathEffectPane.effect; } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java index 9a352a0..ef9f26f 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/QuestEditor.java @@ -5,7 +5,9 @@ import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.ProjectTreeNode; import com.gpl.rpg.atcontentstudio.model.gamedata.Quest; import com.gpl.rpg.atcontentstudio.model.gamedata.QuestStage; -import com.gpl.rpg.atcontentstudio.ui.*; +import com.gpl.rpg.atcontentstudio.ui.FieldUpdateListener; +import com.gpl.rpg.atcontentstudio.ui.IntegerBasedCheckBox; +import com.gpl.rpg.atcontentstudio.ui.OrderedListenerListModel; import com.gpl.rpg.atcontentstudio.utils.BasicLambda; import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithArg; import com.gpl.rpg.atcontentstudio.utils.BasicLambdaWithReturn; @@ -13,11 +15,7 @@ import com.gpl.rpg.atcontentstudio.utils.UiUtils; import com.jidesoft.swing.JideBoxLayout; import javax.swing.*; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.ListSelectionListener; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; @@ -64,23 +62,24 @@ public class QuestEditor extends JSONElementEditor { String title = "Quest stages: "; StagesCellRenderer cellRenderer = new StagesCellRenderer(); stagesListModel = new StagesListModel(quest); - BasicLambdaWithArg selectedSet = (value)->selectedStage = value; - BasicLambdaWithReturn selectedGet = ()->selectedStage ; - BasicLambda selectedReset = ()->selectedStage = null; + BasicLambdaWithArg selectedSet = (value) -> selectedStage = value; + BasicLambdaWithReturn selectedGet = () -> selectedStage; + BasicLambda selectedReset = () -> selectedStage = null; BasicLambdaWithArg updatePane = (editorPane) -> updateStageEditorPane(editorPane, selectedStage, listener); var result = UiUtils.getCollapsibleItemList(listener, - stagesListModel, - selectedReset, - selectedSet, - selectedGet, - (x) -> {}, - updatePane, - quest.writable, - () -> new QuestStage(quest), - cellRenderer, - title, - (x) -> null); + stagesListModel, + selectedReset, + selectedSet, + selectedGet, + (x) -> { + }, + updatePane, + quest.writable, + () -> new QuestStage(quest), + cellRenderer, + title, + (x) -> null); stagesList = result.list; if (quest.stages == null || quest.stages.isEmpty()) { diff --git a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java index 825aaf6..f83dd17 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/map/TMXMapEditor.java @@ -1541,7 +1541,9 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe @Override public void actionPerformed(ActionEvent e) { if (map.needsSaving()) { - int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You have unsaved changes in ATCS.\nYou'd better save your changes in ATCS before opening this map with the external editor.\nDo you want to save before opening the file?", "Save before opening?", JOptionPane.YES_NO_CANCEL_OPTION); + int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, + "You have unsaved changes in ATCS.\nYou'd better save your changes in ATCS before opening this map with the external editor.\nDo you want to save before opening the file?", + "Save before opening?", JOptionPane.YES_NO_CANCEL_OPTION); if (confirm == JOptionPane.CANCEL_OPTION) return; if (confirm == JOptionPane.YES_OPTION) { map.save(); @@ -1559,7 +1561,9 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe @Override public void actionPerformed(ActionEvent e) { if (map.needsSaving()) { - int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You modified this map in ATCS. All ATCS-made changes will be lost if you confirm.\n On the other hand, if you save using ATCS, all external changes will be lost.\n Do you want to reload?", "Confirm reload?", JOptionPane.OK_CANCEL_OPTION); + int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, + "You modified this map in ATCS. All ATCS-made changes will be lost if you confirm.\n On the other hand, if you save using ATCS, all external changes will be lost.\n Do you want to reload?", + "Confirm reload?", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.CANCEL_OPTION) return; } reload.setEnabled(false); @@ -1581,11 +1585,14 @@ public class TMXMapEditor extends Editor implements TMXMap.MapChangedOnDiskListe public void actionPerformed(ActionEvent e) { if (map.state != TMXMap.State.saved) { if (map.changedOnDisk) { - int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, "You modified this map in an external tool. All external changes will be lost if you confirm.\n On the other hand, if you reload in ATCS, all ATCS-made changes will be lost.\n Do you want to save?", "Confirm save?", JOptionPane.OK_CANCEL_OPTION); + int confirm = JOptionPane.showConfirmDialog(TMXMapEditor.this, + "You modified this map in an external tool. All external changes will be lost if you confirm.\n On the other hand, if you reload in ATCS, all ATCS-made changes will be lost.\n Do you want to save?", + "Confirm save?", JOptionPane.OK_CANCEL_OPTION); if (confirm == JOptionPane.CANCEL_OPTION) return; File backup = FileUtils.backupFile(map.tmxFile); if (backup != null) { - JOptionPane.showMessageDialog(TMXMapEditor.this, "The externally-modified file was backed up as " + backup.getAbsolutePath(), "File backed up", JOptionPane.INFORMATION_MESSAGE); + JOptionPane.showMessageDialog(TMXMapEditor.this, "The externally-modified file was backed up as " + backup.getAbsolutePath(), "File backed up", + JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(TMXMapEditor.this, "The externally-modified file could not be backed up.", "File backup failed", JOptionPane.ERROR_MESSAGE); } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java b/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java index 5227f89..4ac87b4 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/tools/ItemsTableView.java @@ -307,7 +307,9 @@ public class ItemsTableView extends ElementTableView { case 22: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.ap_boost_max : null;//"On hit recv - AP max"; case 23: - return (!canUse && item.hit_received_effect != null && item.hit_received_effect.conditions_source != null) ? item.hit_received_effect.conditions_source.size() : null;//"On hit recv - # conditions"; + return (!canUse && + item.hit_received_effect != null && + item.hit_received_effect.conditions_source != null) ? item.hit_received_effect.conditions_source.size() : null;//"On hit recv - # conditions"; case 24: return (!canUse && item.hit_received_effect != null) ? item.hit_received_effect.hp_boost_min : null;//"On hit recv - Tgt HP min"; case 25: diff --git a/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java index b4ce56d..11959bd 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/FileUtils.java @@ -147,7 +147,8 @@ public class FileUtils { case Windows: System.err.println("Trying the Windows way with mklink"); try { - Runtime.getRuntime().exec("cmd.exe /C mklink " + (targetFile.isDirectory() ? "/J " : "") + "\"" + linkFile.getAbsolutePath() + "\" \"" + targetFile.getAbsolutePath() + "\""); + Runtime.getRuntime().exec( + "cmd.exe /C mklink " + (targetFile.isDirectory() ? "/J " : "") + "\"" + linkFile.getAbsolutePath() + "\" \"" + targetFile.getAbsolutePath() + "\""); } catch (IOException e1) { e1.printStackTrace(); } diff --git a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java index bfda654..ab16767 100644 --- a/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java +++ b/src/com/gpl/rpg/atcontentstudio/utils/UiUtils.java @@ -17,7 +17,8 @@ public class UiUtils { public CollapsiblePanel collapsiblePanel; public JList list; } - public static JPanel createRefreshButtonPane(ActionListener reloadButtonEditor){ + + public static JPanel createRefreshButtonPane(ActionListener reloadButtonEditor) { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new JideBoxLayout(buttonPane, JideBoxLayout.LINE_AXIS)); JButton reloadButton = new JButton("Refresh graph"); @@ -64,8 +65,8 @@ public class UiUtils { moveDownBtn.setEnabled(false); } else { deleteBtn.setEnabled(true); - moveUpBtn.setEnabled(list.getSelectedIndex() > 0); - moveDownBtn.setEnabled(list.getSelectedIndex() < (listModel.getSize() - 1)); + moveUpBtn.setEnabled(list.getSelectedIndex() > 0); + moveDownBtn.setEnabled(list.getSelectedIndex() < (listModel.getSize() - 1)); } updateEditorPane.doIt(editorPane); From 0eddd25292bfe480e382efbde50396d4da255bd8 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 20:29:43 +0200 Subject: [PATCH 90/94] delete inspectionProfile --- .idea/inspectionProfiles/duplicates.xml | 1684 ----------------------- 1 file changed, 1684 deletions(-) delete mode 100644 .idea/inspectionProfiles/duplicates.xml diff --git a/.idea/inspectionProfiles/duplicates.xml b/.idea/inspectionProfiles/duplicates.xml deleted file mode 100644 index 4915121..0000000 --- a/.idea/inspectionProfiles/duplicates.xml +++ /dev/null @@ -1,1684 +0,0 @@ - - - - \ No newline at end of file From 1cbcd5b6611a9c8dba8af9398cb692f719201d42 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Tue, 24 Jun 2025 20:36:59 +0200 Subject: [PATCH 91/94] remove finished todo list --- DEDUP-TODO.md | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 DEDUP-TODO.md diff --git a/DEDUP-TODO.md b/DEDUP-TODO.md deleted file mode 100644 index 9ea4c9d..0000000 --- a/DEDUP-TODO.md +++ /dev/null @@ -1,8 +0,0 @@ -# TODOs I still have before I can create a PR -## this is not a List of things i should do, but what HAS to be done. - -There are probably a lot of things that could be optimized, which will not be on this list -(which will probably also be done, they are just not important enough to track them) - -- - From 24e1e526ce2ece31b850f4caf225490780b9529f Mon Sep 17 00:00:00 2001 From: OMGeeky <> Date: Thu, 3 Jul 2025 20:05:00 +0200 Subject: [PATCH 92/94] refactor to keep compatibility with old java version (openjdk-11 tested) --- .../atcontentstudio/ui/ListenerListModel.java | 34 ++++++++++++++----- .../ui/gamedataeditors/CommonEditor.java | 30 ++++++++-------- 2 files changed, 42 insertions(+), 22 deletions(-) diff --git a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java index a90ad3a..c9128c6 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/ListenerListModel.java @@ -13,18 +13,36 @@ public interface ListenerListModel extends ListModel { } default void notifyListeners(Object source, ChangeType event, int index0, int index1) { - int eventCode = switch (event) { - case CHANGED -> ListDataEvent.CONTENTS_CHANGED; - case ADDED -> ListDataEvent.INTERVAL_ADDED; - case REMOVED -> ListDataEvent.INTERVAL_REMOVED; - }; + int eventCode; + switch (event) { + case CHANGED: + eventCode = ListDataEvent.CONTENTS_CHANGED; + break; + case ADDED: + eventCode = ListDataEvent.INTERVAL_ADDED; + break; + case REMOVED: + eventCode = ListDataEvent.INTERVAL_REMOVED; + break; + default: + throw new IllegalArgumentException(); + } for (ListDataListener l : getListeners()) { ListDataEvent e = new ListDataEvent(source, eventCode, index0, index1); switch (event) { - case CHANGED -> l.contentsChanged(e); - case ADDED -> l.intervalAdded(e); - case REMOVED -> l.intervalRemoved(e); + case CHANGED: { + l.contentsChanged(e); + break; + } + case ADDED: { + l.intervalAdded(e); + break; + } + case REMOVED: { + l.intervalRemoved(e); + break; + } } } } diff --git a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java index 8090851..02e9926 100644 --- a/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java +++ b/src/com/gpl/rpg/atcontentstudio/ui/gamedataeditors/CommonEditor.java @@ -28,7 +28,8 @@ public class CommonEditor { @Override public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel label) { + if (c instanceof JLabel) { + JLabel label = (JLabel) c; Common.TimedActorConditionEffect effect = (Common.TimedActorConditionEffect) value; if (effect.condition != null) { @@ -69,7 +70,8 @@ public class CommonEditor { @Override public Component getListCellRendererComponent(@SuppressWarnings("rawtypes") JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - if (c instanceof JLabel label) { + if (c instanceof JLabel) { + JLabel label = (JLabel) c; Common.ActorConditionEffect effect = (Common.ActorConditionEffect) value; if (effect.condition != null) { @@ -108,13 +110,13 @@ public class CommonEditor { @Override protected void addFields(FieldUpdateListener listener, boolean writable) { super.addFields(listener, writable); - hitReceivedEffectHPMinTarget = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToTargetHint), + hitReceivedEffectHPMinTarget = addIntegerField(effectPane, String.format("HP bonus min%s: ", applyToTargetHint), effect.target.hp_boost_min, true, writable, listener); - hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToTargetHint), + hitReceivedEffectHPMaxTarget = addIntegerField(effectPane, String.format("HP bonus max%s: ", applyToTargetHint), effect.target.hp_boost_max, true, writable, listener); - hitReceivedEffectAPMinTarget = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToTargetHint), + hitReceivedEffectAPMinTarget = addIntegerField(effectPane, String.format("AP bonus min%s: ", applyToTargetHint), effect.target.ap_boost_min, true, writable, listener); - hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToTargetHint), + hitReceivedEffectAPMaxTarget = addIntegerField(effectPane, String.format("AP bonus max%s: ", applyToTargetHint), effect.target.ap_boost_max, true, writable, listener); } @@ -160,7 +162,7 @@ public class CommonEditor { if (applyToTargetHint == null || applyToTargetHint == "") { this.applyToTargetHint = ""; } else { - this.applyToTargetHint = " (%s)".formatted(applyToTargetHint); + this.applyToTargetHint = String.format(" (%s)", applyToTargetHint); } } @@ -174,7 +176,7 @@ public class CommonEditor { protected void addLists(FieldUpdateListener listener, boolean writable) { super.addLists(listener, writable); - String titleTarget = "Actor Conditions applied to the target%s: ".formatted(applyToTargetHint); + String titleTarget = String.format("Actor Conditions applied to the target%s: ", applyToTargetHint); CommonEditor.TimedConditionsCellRenderer cellRendererTarget = new CommonEditor.TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetTarget = (value) -> hitTargetConditionPane.selectedCondition = value; BasicLambdaWithReturn selectedGetTarget = () -> hitTargetConditionPane.selectedCondition; @@ -237,7 +239,7 @@ public class CommonEditor { if (applyToHint == null || applyToHint == "") { this.applyToHint = ""; } else { - this.applyToHint = " (%s)".formatted(applyToHint); + this.applyToHint = String.format(" (%s)", applyToHint); } } @@ -254,18 +256,18 @@ public class CommonEditor { } protected void addFields(FieldUpdateListener listener, boolean writable) { - effectHPMin = addIntegerField(effectPane, "HP bonus min%s: ".formatted(applyToHint), effect.hp_boost_min, + effectHPMin = addIntegerField(effectPane, String.format("HP bonus min%s: ", applyToHint), effect.hp_boost_min, true, writable, listener); - effectHPMax = addIntegerField(effectPane, "HP bonus max%s: ".formatted(applyToHint), effect.hp_boost_max, + effectHPMax = addIntegerField(effectPane, String.format("HP bonus max%s: ", applyToHint), effect.hp_boost_max, true, writable, listener); - effectAPMin = addIntegerField(effectPane, "AP bonus min%s: ".formatted(applyToHint), effect.ap_boost_min, + effectAPMin = addIntegerField(effectPane, String.format("AP bonus min%s: ", applyToHint), effect.ap_boost_min, true, writable, listener); - effectAPMax = addIntegerField(effectPane, "AP bonus max%s: ".formatted(applyToHint), effect.ap_boost_max, + effectAPMax = addIntegerField(effectPane, String.format("AP bonus max%s: ", applyToHint), effect.ap_boost_max, true, writable, listener); } protected void addLists(FieldUpdateListener listener, boolean writable) { - String titleSource = "Actor Conditions applied to the source%s: ".formatted(applyToHint); + String titleSource = String.format("Actor Conditions applied to the source%s: ", applyToHint); TimedConditionsCellRenderer cellRendererSource = new TimedConditionsCellRenderer(); BasicLambdaWithArg selectedSetSource = (value) -> sourceConditionPane.selectedCondition = value; BasicLambdaWithReturn selectedGetSource = () -> sourceConditionPane.selectedCondition; From 090584dbcc942f210fbbe7f0292cc7f992c5cfba Mon Sep 17 00:00:00 2001 From: OMGeeky <> Date: Sun, 13 Jul 2025 02:25:01 +0200 Subject: [PATCH 93/94] add warning about icon --- src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java index 4a967d5..66847da 100644 --- a/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java +++ b/src/com/gpl/rpg/atcontentstudio/model/gamedata/Common.java @@ -1,5 +1,6 @@ package com.gpl.rpg.atcontentstudio.model.gamedata; +import com.gpl.rpg.atcontentstudio.Notification; import com.gpl.rpg.atcontentstudio.model.GameDataElement; import com.gpl.rpg.atcontentstudio.model.Project; @@ -49,6 +50,10 @@ public final class Common { public static void linkIcon(Project proj, String iconId, GameDataElement backlink) { if (iconId != null) { String spritesheetId = iconId.split(":")[0]; + if (proj.getSpritesheet(spritesheetId) == null) { + Notification.addError("Error Spritesheet " + spritesheetId + ". has no backlink. (" + iconId + ")"); + return; + } proj.getSpritesheet(spritesheetId).addBacklink(backlink); } } From 3ceee2e9e60a85fbed8bf3d735307ab7ffcd5b4b Mon Sep 17 00:00:00 2001 From: "Nut.andor" Date: Thu, 17 Jul 2025 20:49:36 +0200 Subject: [PATCH 94/94] decrease version to avoid swing issue --- .idea/misc.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index 4944549..1e030a1 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,4 @@ - + \ No newline at end of file