Checkstyle fix

This commit is contained in:
Jindra Petřík
2025-04-13 14:13:27 +02:00
parent 859a2f8bdb
commit b1c5f9d0c6
85 changed files with 2486 additions and 2340 deletions
@@ -21,112 +21,116 @@ import java.util.Map;
/**
* Converts Flash player version to SWF version and vice versa.
*
* @author JPEXS
*/
public class FlashPlayerVersion {
private static final Map<String, Integer> flashPlayerToSwfVersion = new HashMap<>();
private static final Map<String, Integer> airToSwfVersion = new HashMap<>();
private static final Map<Integer, String> swfVersionToFlashPlayer = new HashMap<>();
private static final Map<Integer, String> swfVersionToAir = new HashMap<>();
static {
flashPlayerToSwfVersion.put("9.0", 9); //9.0.115.0
flashPlayerToSwfVersion.put("10.0", 10);
flashPlayerToSwfVersion.put("10.1", 10);
flashPlayerToSwfVersion.put("10.2", 11);
flashPlayerToSwfVersion.put("10.3", 12);
flashPlayerToSwfVersion.put("11.0", 13);
flashPlayerToSwfVersion.put("11.1", 14);
flashPlayerToSwfVersion.put("11.2", 15);
flashPlayerToSwfVersion.put("11.3", 16);
flashPlayerToSwfVersion.put("11.4", 17);
flashPlayerToSwfVersion.put("11.5", 18);
flashPlayerToSwfVersion.put("11.6", 19);
flashPlayerToSwfVersion.put("11.7", 20);
flashPlayerToSwfVersion.put("11.8", 21);
flashPlayerToSwfVersion.put("11.9", 22);
flashPlayerToSwfVersion.put("12.0", 23);
flashPlayerToSwfVersion.put("13.0", 24);
flashPlayerToSwfVersion.put("14.0", 25);
flashPlayerToSwfVersion.put("15.0", 26);
flashPlayerToSwfVersion.put("16.0", 27);
flashPlayerToSwfVersion.put("17.0", 28);
flashPlayerToSwfVersion.put("18.0", 29);
flashPlayerToSwfVersion.put("19.0", 30);
flashPlayerToSwfVersion.put("20.0", 31);
flashPlayerToSwfVersion.put("21.0", 32);
flashPlayerToSwfVersion.put("22.0", 33);
flashPlayerToSwfVersion.put("23.0", 34);
flashPlayerToSwfVersion.put("24.0", 35);
flashPlayerToSwfVersion.put("25.0", 36);
flashPlayerToSwfVersion.put("26.0", 37);
flashPlayerToSwfVersion.put("27.0", 38);
flashPlayerToSwfVersion.put("28.0", 39);
flashPlayerToSwfVersion.put("29.0", 40);
flashPlayerToSwfVersion.put("30.0", 41);
flashPlayerToSwfVersion.put("31.0", 42);
flashPlayerToSwfVersion.put("32.0", 43);
flashPlayerToSwfVersion.put("33.0", 44);
flashPlayerToSwfVersion.put("33.1", 44);
flashPlayerToSwfVersion.put("50.0", 50);
flashPlayerToSwfVersion.put("51.0", 51);
airToSwfVersion.put("1.5", 10);
airToSwfVersion.put("2.0", 10);
airToSwfVersion.put("2.6", 11);
airToSwfVersion.put("2.7", 12);
airToSwfVersion.put("3.0", 13);
airToSwfVersion.put("3.1", 14);
airToSwfVersion.put("3.2", 15);
airToSwfVersion.put("3.3", 16);
airToSwfVersion.put("3.4", 17);
airToSwfVersion.put("3.5", 18);
airToSwfVersion.put("3.6", 19);
airToSwfVersion.put("3.7", 20);
airToSwfVersion.put("3.8", 21);
airToSwfVersion.put("3.9", 22);
airToSwfVersion.put("4.0", 23);
airToSwfVersion.put("13.0", 24);
airToSwfVersion.put("14.0", 25);
airToSwfVersion.put("15.0", 26);
airToSwfVersion.put("16.0", 27);
airToSwfVersion.put("17.0", 28);
airToSwfVersion.put("18.0", 29);
airToSwfVersion.put("19.0", 30);
airToSwfVersion.put("20.0", 31);
airToSwfVersion.put("21.0", 32);
airToSwfVersion.put("22.0", 33);
airToSwfVersion.put("23.0", 34);
airToSwfVersion.put("24.0", 35);
airToSwfVersion.put("25.0", 36);
airToSwfVersion.put("26.0", 37);
airToSwfVersion.put("27.0", 38);
airToSwfVersion.put("28.0", 39);
airToSwfVersion.put("29.0", 40);
airToSwfVersion.put("30.0", 41);
airToSwfVersion.put("31.0", 42);
airToSwfVersion.put("32.0", 43);
airToSwfVersion.put("33.0", 44);
airToSwfVersion.put("33.1", 44);
airToSwfVersion.put("50.0", 50);
airToSwfVersion.put("51.0", 51);
for (String flashPlayer : flashPlayerToSwfVersion.keySet()) {
int swfVersion = flashPlayerToSwfVersion.get(flashPlayer);
if (!swfVersionToFlashPlayer.containsKey(swfVersion)) {
swfVersionToFlashPlayer.put(swfVersion, flashPlayer);
}
}
for (String air : airToSwfVersion.keySet()) {
int swfVersion = airToSwfVersion.get(air);
if (!swfVersionToAir.containsKey(swfVersion)) {
swfVersionToAir.put(swfVersion, air);
}
}
flashPlayerToSwfVersion.put("9.0", 9); //9.0.115.0
flashPlayerToSwfVersion.put("10.0", 10);
flashPlayerToSwfVersion.put("10.1", 10);
flashPlayerToSwfVersion.put("10.2", 11);
flashPlayerToSwfVersion.put("10.3", 12);
flashPlayerToSwfVersion.put("11.0", 13);
flashPlayerToSwfVersion.put("11.1", 14);
flashPlayerToSwfVersion.put("11.2", 15);
flashPlayerToSwfVersion.put("11.3", 16);
flashPlayerToSwfVersion.put("11.4", 17);
flashPlayerToSwfVersion.put("11.5", 18);
flashPlayerToSwfVersion.put("11.6", 19);
flashPlayerToSwfVersion.put("11.7", 20);
flashPlayerToSwfVersion.put("11.8", 21);
flashPlayerToSwfVersion.put("11.9", 22);
flashPlayerToSwfVersion.put("12.0", 23);
flashPlayerToSwfVersion.put("13.0", 24);
flashPlayerToSwfVersion.put("14.0", 25);
flashPlayerToSwfVersion.put("15.0", 26);
flashPlayerToSwfVersion.put("16.0", 27);
flashPlayerToSwfVersion.put("17.0", 28);
flashPlayerToSwfVersion.put("18.0", 29);
flashPlayerToSwfVersion.put("19.0", 30);
flashPlayerToSwfVersion.put("20.0", 31);
flashPlayerToSwfVersion.put("21.0", 32);
flashPlayerToSwfVersion.put("22.0", 33);
flashPlayerToSwfVersion.put("23.0", 34);
flashPlayerToSwfVersion.put("24.0", 35);
flashPlayerToSwfVersion.put("25.0", 36);
flashPlayerToSwfVersion.put("26.0", 37);
flashPlayerToSwfVersion.put("27.0", 38);
flashPlayerToSwfVersion.put("28.0", 39);
flashPlayerToSwfVersion.put("29.0", 40);
flashPlayerToSwfVersion.put("30.0", 41);
flashPlayerToSwfVersion.put("31.0", 42);
flashPlayerToSwfVersion.put("32.0", 43);
flashPlayerToSwfVersion.put("33.0", 44);
flashPlayerToSwfVersion.put("33.1", 44);
flashPlayerToSwfVersion.put("50.0", 50);
flashPlayerToSwfVersion.put("51.0", 51);
airToSwfVersion.put("1.5", 10);
airToSwfVersion.put("2.0", 10);
airToSwfVersion.put("2.6", 11);
airToSwfVersion.put("2.7", 12);
airToSwfVersion.put("3.0", 13);
airToSwfVersion.put("3.1", 14);
airToSwfVersion.put("3.2", 15);
airToSwfVersion.put("3.3", 16);
airToSwfVersion.put("3.4", 17);
airToSwfVersion.put("3.5", 18);
airToSwfVersion.put("3.6", 19);
airToSwfVersion.put("3.7", 20);
airToSwfVersion.put("3.8", 21);
airToSwfVersion.put("3.9", 22);
airToSwfVersion.put("4.0", 23);
airToSwfVersion.put("13.0", 24);
airToSwfVersion.put("14.0", 25);
airToSwfVersion.put("15.0", 26);
airToSwfVersion.put("16.0", 27);
airToSwfVersion.put("17.0", 28);
airToSwfVersion.put("18.0", 29);
airToSwfVersion.put("19.0", 30);
airToSwfVersion.put("20.0", 31);
airToSwfVersion.put("21.0", 32);
airToSwfVersion.put("22.0", 33);
airToSwfVersion.put("23.0", 34);
airToSwfVersion.put("24.0", 35);
airToSwfVersion.put("25.0", 36);
airToSwfVersion.put("26.0", 37);
airToSwfVersion.put("27.0", 38);
airToSwfVersion.put("28.0", 39);
airToSwfVersion.put("29.0", 40);
airToSwfVersion.put("30.0", 41);
airToSwfVersion.put("31.0", 42);
airToSwfVersion.put("32.0", 43);
airToSwfVersion.put("33.0", 44);
airToSwfVersion.put("33.1", 44);
airToSwfVersion.put("50.0", 50);
airToSwfVersion.put("51.0", 51);
for (String flashPlayer : flashPlayerToSwfVersion.keySet()) {
int swfVersion = flashPlayerToSwfVersion.get(flashPlayer);
if (!swfVersionToFlashPlayer.containsKey(swfVersion)) {
swfVersionToFlashPlayer.put(swfVersion, flashPlayer);
}
}
for (String air : airToSwfVersion.keySet()) {
int swfVersion = airToSwfVersion.get(air);
if (!swfVersionToAir.containsKey(swfVersion)) {
swfVersionToAir.put(swfVersion, air);
}
}
}
/**
* Gets Flash player version by SWF version
*
* @param swfVersion SWF version
* @return Flash player version or null if not found
*/
@@ -136,9 +140,10 @@ public class FlashPlayerVersion {
}
return swfVersionToFlashPlayer.get(swfVersion);
}
/**
* Gets SWF version by Flash player version.
*
* @param flashPlayerVersion Flash player version
* @return SWF version or -1 if not found
*/
@@ -148,10 +153,10 @@ public class FlashPlayerVersion {
}
return flashPlayerToSwfVersion.get(flashPlayerVersion);
}
/**
* Gets Air version by SWF version
*
* @param swfVersion SWF version
* @return Air version or null if not found
*/
@@ -161,9 +166,10 @@ public class FlashPlayerVersion {
}
return swfVersionToFlashPlayer.get(swfVersion);
}
/**
* Gets SWF version by Air version.
*
* @param air Air version
* @return SWF version or -1 if not found
*/
@@ -463,7 +463,6 @@ public class ScriptPack extends AS3ClassTreeItem {
/**
* Converts the script pack to source.
*
* @param swfVersion SWF version
* @param abcIndex Abc indexing
* @param writer Writer
* @param traits Traits
@@ -2566,17 +2566,15 @@ public class AVM2Code implements Cloneable {
list = AVM2Graph.translateViaGraph(swfVersion, spe.getData(), callStack, abcIndex, path, this, abc, body, isStatic, scriptIndex, classIndex, localRegs, scopeStack, localRegNames, localRegTypes, fullyQualifiedNames, staticOperation, localRegAssignmentIps, thisHasDefaultToPrimitive);
}
if (initTraits != null) {
Map<Integer, Traits> initClassMultinames = new LinkedHashMap<>();
if (initializerType == GraphTextWriter.TRAIT_SCRIPT_INITIALIZER) {
if (initializerType == GraphTextWriter.TRAIT_SCRIPT_INITIALIZER) {
for (int c : initTraitClasses) {
initClassMultinames.put(abc.instance_info.get(c).name_index, abc.class_info.get(c).static_traits);
}
}
initClassMultinames.put(-1, initTraits);
loopi:
for (int i = 0; i < list.size(); i++) {
GraphTargetItem ti = list.get(i);
@@ -2604,16 +2602,16 @@ public class AVM2Code implements Cloneable {
}
}
}
/*
TODO: All this requires a better care for instance attributes,
for example using the assigned values only when it is referenced by const.
*/
*/
if ((ti instanceof InitPropertyAVM2Item) || (ti instanceof SetPropertyAVM2Item)) {
int multinameIndex = 0;
GraphTargetItem value = null;
GraphTargetItem obj = null;
if (ti instanceof InitPropertyAVM2Item) {
if (ti instanceof InitPropertyAVM2Item) {
multinameIndex = ((InitPropertyAVM2Item) ti).propertyName.multinameIndex;
value = ((InitPropertyAVM2Item) ti).value;
obj = ((InitPropertyAVM2Item) ti).object;
@@ -2624,7 +2622,7 @@ public class AVM2Code implements Cloneable {
obj = ((SetPropertyAVM2Item) ti).object;
}
Multiname m = abc.constants.getMultiname(multinameIndex);
Multiname om = null;
if (obj instanceof GetPropertyAVM2Item) {
om = abc.constants.getMultiname(((FullMultinameAVM2Item) ((GetPropertyAVM2Item) obj).propertyName).multinameIndex);
@@ -2632,7 +2630,7 @@ public class AVM2Code implements Cloneable {
if (obj instanceof GetLexAVM2Item) {
om = ((GetLexAVM2Item) obj).propertyName;
}
for (int classMultiname : initClassMultinames.keySet()) {
Traits ts = initClassMultinames.get(classMultiname);
Multiname cm = classMultiname == -1 ? null : abc.constants.getMultiname(classMultiname);
@@ -2642,55 +2640,55 @@ public class AVM2Code implements Cloneable {
if (tm != null && tm.equals(m) && (classMultiname == -1 || Objects.equals(om, cm))) {
if ((t instanceof TraitSlotConst)) {
//if (((TraitSlotConst) t).isConst() || initializerType == GraphTextWriter.TRAIT_CLASS_INITIALIZER || initializerType == GraphTextWriter.TRAIT_SCRIPT_INITIALIZER)
{
TraitSlotConst tsc = (TraitSlotConst) t;
if (value != null && !convertData.assignedValues.containsKey(tsc)) {
//{
TraitSlotConst tsc = (TraitSlotConst) t;
if (value != null && !convertData.assignedValues.containsKey(tsc)) {
if (!isStatic) {
Set<GraphTargetItem> subItems = value.getAllSubItemsRecursively();
subItems.add(value);
List<Multiname> laterMultinames = new ArrayList<>();
for (int k = j + 1; k < initTraits.traits.size(); k++) {
int tMultinameIndex = initTraits.traits.get(k).name_index;
if (tMultinameIndex > 0) {
Multiname tMultiname = abc.constants.getMultiname(tMultinameIndex);
laterMultinames.add(tMultiname);
}
if (!isStatic) {
Set<GraphTargetItem> subItems = value.getAllSubItemsRecursively();
subItems.add(value);
List<Multiname> laterMultinames = new ArrayList<>();
for (int k = j + 1; k < initTraits.traits.size(); k++) {
int tMultinameIndex = initTraits.traits.get(k).name_index;
if (tMultinameIndex > 0) {
Multiname tMultiname = abc.constants.getMultiname(tMultinameIndex);
laterMultinames.add(tMultiname);
}
for (GraphTargetItem item : subItems) {
}
for (GraphTargetItem item : subItems) {
//if later slot is referenced, we must add it in constructor instead of direct assignment
if (item instanceof GetPropertyAVM2Item) {
Multiname multiName = abc.constants.getMultiname(((FullMultinameAVM2Item) ((GetPropertyAVM2Item) item).propertyName).multinameIndex);
if (laterMultinames.contains(multiName)) {
continue loopi;
}
}
if (item instanceof GetLexAVM2Item) {
Multiname multiName = ((GetLexAVM2Item) item).propertyName;
if (laterMultinames.contains(multiName)) {
continue loopi;
}
}
if (item instanceof LocalRegAVM2Item) { //it is surely in constructor block, not in slot/const
//if later slot is referenced, we must add it in constructor instead of direct assignment
if (item instanceof GetPropertyAVM2Item) {
Multiname multiName = abc.constants.getMultiname(((FullMultinameAVM2Item) ((GetPropertyAVM2Item) item).propertyName).multinameIndex);
if (laterMultinames.contains(multiName)) {
continue loopi;
}
}
}
if (item instanceof GetLexAVM2Item) {
Multiname multiName = ((GetLexAVM2Item) item).propertyName;
if (laterMultinames.contains(multiName)) {
continue loopi;
}
}
if (item instanceof LocalRegAVM2Item) { //it is surely in constructor block, not in slot/const
continue loopi;
}
}
if (value instanceof NewFunctionAVM2Item) {
NewFunctionAVM2Item f = (NewFunctionAVM2Item) value;
f.functionName = tsc.getName(abc).getName(abc.constants, fullyQualifiedNames, true, true);
}
AssignedValue av = new AssignedValue(classMultiname == -1 ? ti : null, value, initializerType, methodIndex);
convertData.assignedValues.put(tsc, av);
if (!isStatic) {
list.remove(i);
i--;
}
continue loopi;
}
if (value instanceof NewFunctionAVM2Item) {
NewFunctionAVM2Item f = (NewFunctionAVM2Item) value;
f.functionName = tsc.getName(abc).getName(abc.constants, fullyQualifiedNames, true, true);
}
AssignedValue av = new AssignedValue(classMultiname == -1 ? ti : null, value, initializerType, methodIndex);
convertData.assignedValues.put(tsc, av);
if (!isStatic) {
list.remove(i);
i--;
}
continue loopi;
}
//}
break;
}
}
@@ -2728,7 +2726,7 @@ public class AVM2Code implements Cloneable {
}
}
if (initializerType == GraphTextWriter.TRAIT_CLASS_INITIALIZER || initializerType == GraphTextWriter.TRAIT_SCRIPT_INITIALIZER) {
Map<GraphTargetItem, AssignedValue> commandToAssigned = new IdentityHashMap<>();
Map<GraphTargetItem, TraitSlotConst> commandToTrait = new IdentityHashMap<>();
@@ -700,7 +700,7 @@ public class FastAVM2List implements Collection<AVM2InstructionItem> {
/**
* Converts to array.
*
* @param the array into which the elements of this collection are to be
* @param a the array into which the elements of this collection are to be
* stored, if it is big enough; otherwise, a new array of the same runtime
* type is allocated for this purpose.
* @param <T> Type
@@ -39,7 +39,7 @@ import java.util.List;
*
* @author JPEXS
*/
public class ConvertF4Ins extends InstructionDefinition implements CoerceOrConvertTypeIns{
public class ConvertF4Ins extends InstructionDefinition implements CoerceOrConvertTypeIns {
/**
* Constructor
@@ -65,7 +65,7 @@ public class ConvertF4Ins extends InstructionDefinition implements CoerceOrConve
lda.operandStack.push(new Float4(f, f, f, f));
return true;
}
@Override
public int getStackPopCount(AVM2Instruction ins, ABC abc) {
return 1;
@@ -75,12 +75,12 @@ public class ConvertF4Ins extends InstructionDefinition implements CoerceOrConve
public int getStackPushCount(AVM2Instruction ins, ABC abc) {
return 1;
}
@Override
public void translate(AVM2LocalData localData, TranslateStack stack, AVM2Instruction ins, List<GraphTargetItem> output, String path) {
stack.push(new ConvertAVM2Item(ins, localData.lineStartInstruction, stack.pop(), getTargetType(localData.getConstants(), ins)));
}
@Override
public GraphTargetItem getTargetType(AVM2ConstantPool constants, AVM2Instruction ins) {
return new TypeItem("float4");
@@ -41,7 +41,6 @@ public class TraitSlotConstAVM2Item extends AVM2Item {
private final int methodIndex;
private final int traitIndex;
/**
*
* @param instruction
@@ -58,7 +57,7 @@ public class TraitSlotConstAVM2Item extends AVM2Item {
public TraitSlotConstAVM2Item(
GraphSourceItem instruction,
GraphSourceItem lineStartIns,
TraitSlotConst trait,
TraitSlotConst trait,
GraphTargetItem assignedValue,
boolean isStatic,
int scriptIndex,
@@ -66,7 +65,7 @@ public class TraitSlotConstAVM2Item extends AVM2Item {
int initializer,
int methodIndex,
int traitIndex
) {
) {
super(instruction, lineStartIns, PRECEDENCE_PRIMARY);
this.trait = trait;
this.assignedValue = assignedValue;
@@ -80,28 +79,28 @@ public class TraitSlotConstAVM2Item extends AVM2Item {
@Override
public GraphTextWriter appendTo(GraphTextWriter writer, LocalData localData) throws InterruptedException {
writer.endMethod();
writer.endTrait();
int h = traitIndex;
if (initializer != GraphTextWriter.TRAIT_SCRIPT_INITIALIZER) {
h = localData.abc.getGlobalTraitId(TraitType.METHOD , isStatic, classIndex, traitIndex);
h = localData.abc.getGlobalTraitId(TraitType.METHOD, isStatic, classIndex, traitIndex);
}
writer.startTrait(h);
ConvertData cd = new ConvertData();
cd.assignedValues.put(trait, new AssignedValue(null, assignedValue, initializer, methodIndex));
boolean insideInterface = classIndex > -1 ? localData.abc.instance_info.get(classIndex).isInterface() : false;
boolean insideInterface = classIndex > -1 ? localData.abc.instance_info.get(classIndex).isInterface() : false;
trait.toString(
localData.swfVersion,
localData.abcIndex,
DottedChain.EMPTY /*??*/,
null,
null,
cd,
"trait " + trait.getName(localData.abc),
localData.abc,
isStatic,
localData.exportMode,
"trait " + trait.getName(localData.abc),
localData.abc,
isStatic,
localData.exportMode,
scriptIndex,
classIndex,
writer,
@@ -110,9 +109,9 @@ public class TraitSlotConstAVM2Item extends AVM2Item {
insideInterface
);
writer.endTrait();
writer.startTrait(initializer);
writer.startMethod(methodIndex, null);
writer.startMethod(methodIndex, null);
return writer;
}
@@ -124,17 +123,17 @@ public class TraitSlotConstAVM2Item extends AVM2Item {
@Override
public GraphTargetItem returnType() {
return null;
}
}
@Override
public boolean needsSemicolon() {
return false;
}
}
@Override
public boolean hasSingleNewLineAround() {
return true;
}
}
@Override
public boolean handlesNewLine() {
@@ -143,5 +142,5 @@ public class TraitSlotConstAVM2Item extends AVM2Item {
public TraitSlotConst getTrait() {
return trait;
}
}
}
@@ -134,23 +134,28 @@ public class ASM3Parser {
}
}
private static void expected(ParsedSymbol s, int type, String expStr, int line) throws IOException, AVM2ParseException {
if (s.type != type) {
throw new AVM2ParseException(expStr + " expected", line);
}
}
private static int getInteger(ParsedSymbol s, int line) throws AVM2ParseException {
return getInteger(s, line, false);
}
private static int getInteger(ParsedSymbol s, int line, boolean orNull) throws AVM2ParseException {
String expected = "integer" + (orNull ? " or null" : "") + " expected";
if (s.type != ParsedSymbol.TYPE_NUMBER) {
throw new AVM2ParseException(expected, line);
}
String nval = (String) s.value;
if (
nval.endsWith("d")
|| nval.endsWith("m")
if (nval.endsWith("d")
|| nval.endsWith("m")
|| nval.contains("e")
|| nval.contains("E")
|| nval.contains(".")
) {
|| nval.contains(".")) {
throw new AVM2ParseException(expected, line);
}
if (nval.endsWith("i") || nval.endsWith("u")) {
@@ -158,21 +163,19 @@ public class ASM3Parser {
}
return Integer.parseInt(nval);
}
private static long getUInteger(ParsedSymbol s, int line, boolean orNull) throws AVM2ParseException {
String expected = "unsigned integer" + (orNull ? " or null" : "") + " expected";
if (s.type != ParsedSymbol.TYPE_NUMBER) {
throw new AVM2ParseException(expected, line);
}
String nval = (String) s.value;
if (
nval.endsWith("d")
|| nval.endsWith("m")
if (nval.endsWith("d")
|| nval.endsWith("m")
|| nval.contains("e")
|| nval.contains("E")
|| nval.contains(".")
) {
|| nval.contains(".")) {
throw new AVM2ParseException(expected, line);
}
if (nval.endsWith("i") || nval.endsWith("u")) {
@@ -184,51 +187,44 @@ public class ASM3Parser {
}
return result;
}
private static float getFloat(ParsedSymbol s, int line, boolean orNull) throws AVM2ParseException {
String expected = "float" + (orNull ? " or null" : "") + " expected";
if (s.type != ParsedSymbol.TYPE_NUMBER) {
throw new AVM2ParseException(expected, line);
}
String nval = (String) s.value;
if (
nval.endsWith("d")
|| nval.endsWith("m")
) {
if (nval.endsWith("d")
|| nval.endsWith("m")) {
throw new AVM2ParseException(expected, line);
}
if (
nval.endsWith("i")
if (nval.endsWith("i")
|| nval.endsWith("u")
|| nval.endsWith("f")
) {
|| nval.endsWith("f")) {
nval = nval.substring(0, nval.length() - 1);
}
return Float.parseFloat(nval);
}
private static Decimal128 getDecimal(ParsedSymbol s, int line, boolean orNull) throws AVM2ParseException {
String expected = "decimal" + (orNull ? " or null" : "") + " expected";
if (s.type != ParsedSymbol.TYPE_NUMBER) {
throw new AVM2ParseException(expected, line);
}
String nval = (String) s.value;
if (
nval.endsWith("i")
if (nval.endsWith("i")
|| nval.endsWith("u")
|| nval.endsWith("d")
|| nval.endsWith("m")
) {
|| nval.endsWith("m")) {
nval = nval.substring(0, nval.length() - 1);
}
return new Decimal128(nval);
}
private static double getDouble(ParsedSymbol s, int line, boolean orNull) throws AVM2ParseException {
String expected = "double" + (orNull ? " or null" : "") + " expected";
if (s.type != ParsedSymbol.TYPE_NUMBER) {
@@ -242,13 +238,7 @@ public class ASM3Parser {
nval = nval.substring(0, nval.length() - 1);
}
return Double.parseDouble(nval);
}
private static void expected(ParsedSymbol s, int type, String expStr, int line) throws IOException, AVM2ParseException {
if (s.type != type) {
throw new AVM2ParseException(expStr + " expected", line);
}
}
}
private static void parseTraitParams(ABC abc, Flasm3Lexer lexer, Trait t) throws IOException, AVM2ParseException {
ParsedSymbol symb;
@@ -331,6 +321,7 @@ public class ASM3Parser {
/**
* Parses a class.
*
* @param abc ABC
* @param reader Reader
* @param constants Constant pool
@@ -454,6 +445,7 @@ public class ASM3Parser {
/**
* Parses a slot or const.
*
* @param abc ABC
* @param reader Reader
* @param constants Constant pool
@@ -467,7 +459,6 @@ public class ASM3Parser {
return parseSlotConst(abc, lexer, constants, tsc);
}
private static int parseNumberContext(Flasm3Lexer lexer) throws AVM2ParseException, IOException {
ParsedSymbol s = lexer.lex();
expected(s, ParsedSymbol.TYPE_KEYWORD_NUMBERCONTEXT, "NumberContext", lexer.yyline());
@@ -493,7 +484,7 @@ public class ASM3Parser {
default:
throw new AVM2ParseException("Usage expected - one of: Number, decimal, double, int or uint", lexer.yyline());
}
int rounding = NumberContext.ROUND_HALF_UP;
int rounding = NumberContext.ROUND_HALF_UP;
int precision = 34;
if (usage == NumberContext.USE_NUMBER || usage == NumberContext.USE_DECIMAL) {
expected(ParsedSymbol.TYPE_COMMA, ",", lexer);
@@ -521,7 +512,7 @@ public class ASM3Parser {
rounding = NumberContext.ROUND_FLOOR;
break;
default:
throw new AVM2ParseException("Rounding expected - one of: CEILING, UP, HALF_UP, HALF_EVEN, HALF_DOWN, DOWN, FLOOR", lexer.yyline());
throw new AVM2ParseException("Rounding expected - one of: CEILING, UP, HALF_UP, HALF_EVEN, HALF_DOWN, DOWN, FLOOR", lexer.yyline());
}
s = lexer.lex();
if (s.type == ParsedSymbol.TYPE_COMMA) {
@@ -537,7 +528,7 @@ public class ASM3Parser {
expected(ParsedSymbol.TYPE_PARENT_CLOSE, ")", lexer);
return new NumberContext(usage, precision, rounding).toParam();
}
private static int parseNamespaceSet(AVM2ConstantPool constants, Flasm3Lexer lexer) throws AVM2ParseException, IOException {
List<Integer> namespaceList = new ArrayList<>();
ParsedSymbol s = lexer.lex();
@@ -545,7 +536,7 @@ public class ASM3Parser {
if (s.type == ParsedSymbol.TYPE_KEYWORD_UNKNOWN) {
expected(ParsedSymbol.TYPE_PARENT_OPEN, "(", lexer);
s = lexer.lex();
int index = (int)getUInteger(s, lexer.yyline(), false);
int index = (int) getUInteger(s, lexer.yyline(), false);
expected(ParsedSymbol.TYPE_PARENT_CLOSE, ")", lexer);
return index;
}
@@ -591,7 +582,7 @@ public class ASM3Parser {
case ParsedSymbol.TYPE_KEYWORD_UNKNOWN:
expected(ParsedSymbol.TYPE_PARENT_OPEN, "(", lexer);
ParsedSymbol s = lexer.lex();
int unkId = (int)getUInteger(s, kind, false);
int unkId = (int) getUInteger(s, kind, false);
expected(ParsedSymbol.TYPE_PARENT_CLOSE, ")", lexer);
return unkId;
case ParsedSymbol.TYPE_KEYWORD_NULL:
@@ -656,7 +647,7 @@ public class ASM3Parser {
case ParsedSymbol.TYPE_KEYWORD_UNKNOWN:
expected(ParsedSymbol.TYPE_PARENT_OPEN, "(", lexer);
s = lexer.lex();
int unkId = (int)getUInteger(s, kind, false);
int unkId = (int) getUInteger(s, kind, false);
expected(ParsedSymbol.TYPE_PARENT_CLOSE, ")", lexer);
return unkId;
case ParsedSymbol.TYPE_KEYWORD_NULL:
@@ -788,6 +779,7 @@ public class ASM3Parser {
/**
* Parses value.
*
* @param constants Constant pool
* @param lexer Lexer
* @return Value kind
@@ -834,7 +826,7 @@ public class ASM3Parser {
value_index = constants.getDoubleId(getDouble(value, lexer.yyline(), true), true);
}
expected(ParsedSymbol.TYPE_PARENT_CLOSE, ")", lexer);
break;
break;
case ParsedSymbol.TYPE_KEYWORD_FLOAT:
value_kind = ValueKind.CONSTANT_DecimalOrFloat;
expected(ParsedSymbol.TYPE_PARENT_OPEN, "(", lexer);
@@ -858,16 +850,16 @@ public class ASM3Parser {
value = lexer.lex();
float f2 = getFloat(value, lexer.yyline(), true);
expected(ParsedSymbol.TYPE_COMMA, ",", lexer);
value = lexer.lex();
value = lexer.lex();
float f3 = getFloat(value, lexer.yyline(), true);
expected(ParsedSymbol.TYPE_COMMA, ",", lexer);
value = lexer.lex();
value = lexer.lex();
float f4 = getFloat(value, lexer.yyline(), true);
Float4 fval = new Float4(f1, f2, f3, f4);
value_index = constants.getFloat4Id(fval, true);
}
expected(ParsedSymbol.TYPE_PARENT_CLOSE, ")", lexer);
break;
break;
case ParsedSymbol.TYPE_NUMBER:
String nval = (String) type.value;
if (nval.endsWith("m")) {
@@ -884,14 +876,14 @@ public class ASM3Parser {
value_index = constants.getDoubleId(Double.parseDouble(nval), true);
break;
}
if (nval.endsWith("u")) {
nval = nval.substring(0, nval.length() - 1);
}
if (nval.endsWith("i")) {
nval = nval.substring(0, nval.length() - 1);
}
}
value_kind = ValueKind.CONSTANT_Int;
value_index = constants.getIntId(Integer.parseInt(nval), true);
break;
@@ -996,6 +988,7 @@ public class ASM3Parser {
/**
* Parses code.
*
* @param abc ABC
* @param reader Reader
* @param trait Trait
@@ -1012,6 +1005,7 @@ public class ASM3Parser {
/**
* Parses code.
*
* @param abc ABC
* @param reader Reader
* @param trait Trait
@@ -1094,7 +1088,7 @@ public class ASM3Parser {
parseTraitParams(abc, lexer, trait);
expected(ParsedSymbol.TYPE_KEYWORD_DISPID, "dispid", lexer);
symb = lexer.lex();
tm.disp_id = (int)getUInteger(symb, lexer.yyline(), false);
tm.disp_id = (int) getUInteger(symb, lexer.yyline(), false);
break;
case ParsedSymbol.TYPE_KEYWORD_FUNCTION:
@@ -1141,25 +1135,25 @@ public class ASM3Parser {
if (symb.type == ParsedSymbol.TYPE_KEYWORD_MAXSTACK) {
symb = lexer.lex();
body.max_stack = (int)getUInteger(symb, lexer.yyline(), false);
body.max_stack = (int) getUInteger(symb, lexer.yyline(), false);
continue;
}
if (symb.type == ParsedSymbol.TYPE_KEYWORD_LOCALCOUNT) {
symb = lexer.lex();
body.max_regs = (int)getUInteger(symb, lexer.yyline(), false);
body.max_regs = (int) getUInteger(symb, lexer.yyline(), false);
continue;
}
if (symb.type == ParsedSymbol.TYPE_KEYWORD_INITSCOPEDEPTH) {
symb = lexer.lex();
body.init_scope_depth = (int)getUInteger(symb, lexer.yyline(), false);
body.init_scope_depth = (int) getUInteger(symb, lexer.yyline(), false);
continue;
}
if (symb.type == ParsedSymbol.TYPE_KEYWORD_MAXSCOPEDEPTH) {
symb = lexer.lex();
body.max_scope_depth = (int)getUInteger(symb, lexer.yyline(), false);
body.max_scope_depth = (int) getUInteger(symb, lexer.yyline(), false);
continue;
}
@@ -1317,7 +1311,7 @@ public class ASM3Parser {
if (parsedOperand.type == ParsedSymbol.TYPE_KEYWORD_UNKNOWN) {
expected(ParsedSymbol.TYPE_PARENT_OPEN, "(", lexer);
ParsedSymbol indexSymb = lexer.lex();
int unkIndex = (int)getUInteger(indexSymb, lexer.yyline(), false);
int unkIndex = (int) getUInteger(indexSymb, lexer.yyline(), false);
expected(ParsedSymbol.TYPE_PARENT_CLOSE, ")", lexer);
operandsList.add(unkIndex);
continue;
@@ -1354,7 +1348,7 @@ public class ASM3Parser {
if (parsedOperand.type == ParsedSymbol.TYPE_KEYWORD_NULL) {
operandsList.add(0);
} else {
} else {
int intVal = getInteger(parsedOperand, lexer.yyline(), true);
int iid = constants.getIntId(intVal, false);
if (iid == -1) {
@@ -1402,7 +1396,7 @@ public class ASM3Parser {
case AVM2Code.DAT_DECIMAL_INDEX:
if (parsedOperand.type == ParsedSymbol.TYPE_KEYWORD_NULL) {
operandsList.add(0);
} else{
} else {
Decimal128 decimalVal = getDecimal(parsedOperand, lexer.yyline(), true);
int did = constants.getDecimalId(decimalVal, false);
if (did == -1) {
@@ -1504,7 +1498,7 @@ public class ASM3Parser {
operandsList.add(0);
}
} else if (parsedOperand.type == ParsedSymbol.TYPE_NUMBER) { //old syntax
int patCount = (int)getUInteger(parsedOperand, lexer.yyline(), false);
int patCount = (int) getUInteger(parsedOperand, lexer.yyline(), false);
operandsList.add(patCount);
for (int c = 0; c <= patCount; c++) {
@@ -1547,7 +1541,7 @@ public class ASM3Parser {
break;
default:
if (parsedOperand.type == ParsedSymbol.TYPE_NUMBER) {
int val = getInteger(parsedOperand, lexer.yyline());
int val = getInteger(parsedOperand, lexer.yyline());
operandsList.add(val);
} else {
throw new AVM2ParseException("Integer expected", lexer.yyline());
@@ -164,6 +164,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generate a new unique id
*
* @return Unique id
*/
public String uniqId() {
@@ -173,6 +174,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Resolve type.
*
* @param localData Local data
* @param item Item
* @param abcIndex ABC indexing
@@ -220,7 +222,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
}
}
}*/
ABC abc = abcIndex.getSelectedAbc();
AVM2ConstantPool constants = abc.constants;
AbcIndexing.ClassIndex ci = abcIndex.findClass(new TypeItem(dname), abc, localData != null ? localData.scriptIndex : null);
@@ -306,6 +308,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Converts list of source items to list of instructions
*
* @param items List of source items
* @return List of instructions
*/
@@ -362,10 +365,9 @@ public class AVM2SourceGenerator implements SourceGenerator {
}
AVM2Instruction ajmp = null;
if (onFalse != null) {
if (onTrueCmds.isEmpty() ||
!((onTrueCmds.get(onTrueCmds.size() - 1) instanceof ContinueItem)
|| (onTrueCmds.get(onTrueCmds.size() - 1) instanceof BreakItem))
) {
if (onTrueCmds.isEmpty()
|| !((onTrueCmds.get(onTrueCmds.size() - 1) instanceof ContinueItem)
|| (onTrueCmds.get(onTrueCmds.size() - 1) instanceof BreakItem))) {
ajmp = ins(AVM2Instructions.Jump, 0);
onTrue.add(ajmp);
}
@@ -420,6 +422,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generate for (each) in loop.
*
* @param localData Local data
* @param loop Loop
* @param collection Collection
@@ -510,6 +513,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets register variables.
*
* @param localData Local data
* @return Register variables
*/
@@ -519,6 +523,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Sets register variables.
*
* @param localData Local data
* @param value Value
*/
@@ -528,6 +533,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Sets in function.
*
* @param localData Local data
* @param value Value
*/
@@ -537,6 +543,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets in function.
*
* @param localData Local data
* @return In function
*/
@@ -546,6 +553,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Checks if in method.
*
* @param localData Local data
* @return True if in method
*/
@@ -555,6 +563,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Sets in method.
*
* @param localData Local data
* @param value Value
*/
@@ -564,6 +573,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets for in level.
*
* @param localData Local data
* @return For in level
*/
@@ -573,6 +583,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Sets for in level.
*
* @param localData Local data
* @param value Value
*/
@@ -582,6 +593,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets temp register.
*
* @param localData Local data
* @return Temp register
*/
@@ -599,6 +611,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Constructor.
*
* @param abc ABC
*/
public AVM2SourceGenerator(AbcIndexing abc) {
@@ -608,9 +621,9 @@ public class AVM2SourceGenerator implements SourceGenerator {
/*public ABC getABC() {
return abc;
}*/
/**
* Generate class.
*
* @param importedClasses Imported classes
* @param cinitVariables Cinit variables
* @param cinitNeedsActivation Cinit needs activation
@@ -638,14 +651,13 @@ public class AVM2SourceGenerator implements SourceGenerator {
public void generateClass(List<DottedChain> importedClasses, List<AssignableAVM2Item> cinitVariables, boolean cinitNeedsActivation, List<GraphTargetItem> cinit, List<NamespaceItem> openedNamespaces, int namespace, int initScope, DottedChain pkg, ClassInfo classInfo, InstanceInfo instanceInfo, SourceGeneratorLocalData localData, boolean isInterface, String baseClassName, String superName, GraphTargetItem extendsVal, List<GraphTargetItem> implementsStr, GraphTargetItem iinit, List<AssignableAVM2Item> iinitVariables, boolean iinitNeedsActivation, List<GraphTargetItem> commands, Reference<Integer> class_index) throws AVM2ParseException, CompilationException {
List<GraphTargetItem> traitItems = new ArrayList<>();
for (GraphTargetItem it : commands) {
if ((it instanceof SlotAVM2Item)
if ((it instanceof SlotAVM2Item)
|| (it instanceof ConstAVM2Item)
|| (it instanceof ClassAVM2Item)
|| (it instanceof InterfaceAVM2Item)
|| (it instanceof MethodAVM2Item)
|| (it instanceof GetterAVM2Item)
|| (it instanceof SetterAVM2Item)
) {
|| (it instanceof SetterAVM2Item)) {
traitItems.add(it);
}
}
@@ -657,8 +669,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
extendsVal = new TypeItem(DottedChain.OBJECT);
}
ParsedSymbol s = null;
if (Configuration.handleSkinPartsAutomatically.get()) {
Map<String, Boolean> skinParts = new HashMap<>();
@@ -796,7 +807,6 @@ public class AVM2SourceGenerator implements SourceGenerator {
int cinit_index = method(null, true, str(""), false, false, false, new ArrayList<>(), pkg, cinitNeedsActivation, cinitVariables, initScope + (implementsStr.isEmpty() ? 0 : 1), false, 0, isInterface ? null : baseClassName, superName, false, localData, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), commands, TypeItem.UNBOUNDED);
MethodBody cinitBody = abcIndex.getSelectedAbc().findBody(cinit_index);
for (int i = 0; i < cinitVariables.size(); i++) {
AssignableAVM2Item an = cinitVariables.get(i);
if (an instanceof UnresolvedAVM2Item) {
@@ -815,7 +825,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
}
}
}
//List<AVM2Instruction> cinitcode = new ArrayList<>();
List<AVM2Instruction> initcode = new ArrayList<>();
for (GraphTargetItem ti : commands) {
@@ -850,16 +860,15 @@ public class AVM2SourceGenerator implements SourceGenerator {
cinitcode.addAll(toInsList(val.toSource(localData, this)));
cinitcode.add(ins(isConst ? AVM2Instructions.InitProperty : AVM2Instructions.SetProperty, traitName(ns, tname)));
}
*/
*/
if (!isStatic && val != null) {
//do not init basic values, that can be stored in trait
if (!(val instanceof IntegerValueAVM2Item)
if (!(val instanceof IntegerValueAVM2Item)
&& !(val instanceof DoubleValueAVM2Item)
&& !(val instanceof StringAVM2Item)
&& !(val instanceof BooleanAVM2Item)
&& !(val instanceof NullAVM2Item)
&& !(val instanceof UndefinedAVM2Item)
) {
&& !(val instanceof StringAVM2Item)
&& !(val instanceof BooleanAVM2Item)
&& !(val instanceof NullAVM2Item)
&& !(val instanceof UndefinedAVM2Item)) {
val = handleAndOrCoerce(val, type);
initcode.add(ins(AVM2Instructions.GetLocal0));
localData.isStatic = false;
@@ -895,6 +904,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates class.
*
* @param namespace Namespace
* @param ci Class info
* @param ii Instance info
@@ -955,6 +965,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets trait name.
*
* @param namespace Namespace
* @param var Variable
* @return Multiname index
@@ -965,6 +976,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets type name.
*
* @param localData Local data
* @param type Type
* @return Multiname index
@@ -1000,6 +1012,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets identifier from name.
*
* @param name Name
* @return Identifier
*/
@@ -1012,6 +1025,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets namespace.
*
* @param nsKind Namespace kind
* @param name Name
* @return Namespace index
@@ -1022,6 +1036,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets string
*
* @param name Name
* @return String index
*/
@@ -1031,6 +1046,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets property name.
*
* @param name Name
* @return Multiname index
*/
@@ -1044,6 +1060,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets free register.
*
* @param localData Local data
* @return Register
*/
@@ -1058,6 +1075,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Kills register.
*
* @param localData Local data
* @param i Register
* @return True if register was killed
@@ -1096,7 +1114,8 @@ public class AVM2SourceGenerator implements SourceGenerator {
newlocalData.returnType = retType;
localData = newlocalData;
localData.activationReg = 0; int[] param_types = new int[paramTypes.size()];
localData.activationReg = 0;
int[] param_types = new int[paramTypes.size()];
ValueKind[] optional = new ValueKind[paramValues.size()];
//int[] param_names = new int[paramNames.size()];
for (int i = 0; i < paramTypes.size(); i++) {
@@ -1114,10 +1133,12 @@ public class AVM2SourceGenerator implements SourceGenerator {
MethodInfo mi = new MethodInfo(param_types, constructor ? 0 : typeName(localData, retType), name_index, 0, optional, new int[0]/*no param_names*/);
return abcIndex.getSelectedAbc().addMethodInfo(mi);
}
/**
* Gets method.
* @param replaceMethodIndex Which method info to replace. Null = create new.
*
* @param replaceMethodIndex Which method info to replace. Null = create
* new.
* @param isStatic Is static
* @param name_index Name index
* @param subMethod Sub method
@@ -1273,11 +1294,11 @@ public class AVM2SourceGenerator implements SourceGenerator {
if ((round == 1) && (m.matches())) {
String regIndexStr = m.group(1);
int regIndex = Integer.parseInt(regIndexStr);
boolean alreadyExistsWithDifferentName = regIndex < registerNames.size()
boolean alreadyExistsWithDifferentName = regIndex < registerNames.size()
&& !registerNames.get(regIndex).equals(UNUSED)
&& !registerNames.get(regIndex).equals(varName);
if (alreadyExistsWithDifferentName) {
addNew = true;
} else {
@@ -1293,7 +1314,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
} else if (round == 2 && !m.matches()) { //in second round the rest
addNew = true;
}
if (addNew) {
if (addNew) {
//search for some unused indices first:
int newRegIndex = -1;
for (int j = 0; j < registerNames.size(); j++) {
@@ -1442,11 +1463,11 @@ public class AVM2SourceGenerator implements SourceGenerator {
}
MethodInfo mi = new MethodInfo(param_types, constructor ? 0 : typeName(localData, retType), name_index, 0, optional, new int[0]/*no param_names*/);
if (replaceMethodIndex != null) {
mi = abcIndex.getSelectedAbc().method_info.get(replaceMethodIndex);
}
if (hasArguments) {
mi.setFlagNeed_Arguments();
}
@@ -1633,6 +1654,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets value kind.
*
* @param ns Namespace
* @param type Type
* @param val Value
@@ -1707,6 +1729,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates traits phase 2.
*
* @param importedClasses Imported classes
* @param pkg Package
* @param items Items
@@ -1766,6 +1789,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates traits phase 3.
*
* @param items Items
* @param traits Traits
* @param localData Local data
@@ -1839,6 +1863,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets super interface name.
*
* @param localData Local data
* @param un Unresolved item
* @return Multiname index
@@ -1861,6 +1886,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates metadata
*
* @param metadata Metadata
* @param abc ABC
* @return Metadata indices
@@ -1893,6 +1919,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates traits phase 4.
*
* @param importedClasses Imported classes
* @param openedNamespaces Opened namespaces
* @param methodInitScope Method init scope
@@ -2005,14 +2032,14 @@ public class AVM2SourceGenerator implements SourceGenerator {
((TraitFunction) traits[k]).method_info = methodHeader(false, methodName(false/*?*/, localData.pkg, fai.functionName, fai.pkg, null, null, ""), false, isInterface, fai.isNative, new ArrayList<>(), localData.pkg, fai.needsActivation, fai.subvariables, methodInitScope, fai.hasRest, fai.line, className, superName, false, localData, fai.paramTypes, fai.paramNames, fai.paramValues, fai.body, fai.retType);
}
}
abcIndex.refreshSelected();
for (int k = 0; k < items.size(); k++) {
GraphTargetItem item = items.get(k);
if (traits[k] == null) {
continue;
}
}
if ((item instanceof MethodAVM2Item) || (item instanceof GetterAVM2Item) || (item instanceof SetterAVM2Item)) {
MethodAVM2Item mai = (MethodAVM2Item) item;
if (!isScriptTraits && mai.isStatic() != generateStatic) {
@@ -2081,6 +2108,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates traits phase 1.
*
* @param importedClasses Imported classes
* @param openedNamespaces Opened namespaces
* @param className Class name
@@ -2247,6 +2275,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates script info.
*
* @param sinitVariables Script initializer variables
* @param sinitNeedsActivation Script initializer needs activation
* @param importedClasses Imported classes
@@ -2263,14 +2292,13 @@ public class AVM2SourceGenerator implements SourceGenerator {
public void generateScriptInfo(List<AssignableAVM2Item> sinitVariables, boolean sinitNeedsActivation, List<DottedChain> importedClasses, List<NamespaceItem> openedNamespaces, int scriptIndex, ScriptInfo scriptInfo, List<List<NamespaceItem>> allOpenedNamespaces, SourceGeneratorLocalData localData, List<GraphTargetItem> commands, int classPos) throws AVM2ParseException, CompilationException {
List<GraphTargetItem> traitsList = new ArrayList<>();
for (GraphTargetItem it : commands) {
if ((it instanceof SlotAVM2Item)
if ((it instanceof SlotAVM2Item)
|| (it instanceof ConstAVM2Item)
|| (it instanceof ClassAVM2Item)
|| (it instanceof InterfaceAVM2Item)
|| (it instanceof MethodAVM2Item)
|| (it instanceof GetterAVM2Item)
|| (it instanceof SetterAVM2Item)
) {
|| (it instanceof SetterAVM2Item)) {
traitsList.add(it);
}
}
@@ -2289,18 +2317,17 @@ public class AVM2SourceGenerator implements SourceGenerator {
MethodBody mb;
//= new MethodBody(abc, new Traits(), new byte[0], new ABCException[0]);
//mb.method_info = abc.addMethodInfo(mi);
// mb.setCode(new AVM2Code());
// mb.setCode(new AVM2Code());
localData.importedClasses = importedClasses;
localData.openedNamespaces = openedNamespaces;
int sinit_index = method(null, true, str(""), false, false, false, new ArrayList<>(), null, sinitNeedsActivation, sinitVariables, 0, false, 0, null, null, false, localData, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), commands, TypeItem.UNBOUNDED);
mb = abcIndex.getSelectedAbc().findBody(sinit_index);
List<AVM2Instruction> mbCode = mb.getCode().code;
/*mbCode.add(ins(AVM2Instructions.GetLocal0));
mbCode.add(ins(AVM2Instructions.PushScope));
*/
*/
int traitScope = 1;
String documentClassStr = localData.documentClass;
@@ -2366,13 +2393,13 @@ public class AVM2SourceGenerator implements SourceGenerator {
}
mbCode.addAll(2, sinitcode); //after getlocal0 pushscope
//abc.addMethodBody(mb);
scriptInfo.init_index = mb.method_info;
localData.pkg = DottedChain.EMPTY;
//localData.registerVars.put("this", 0);
generateTraitsPhase4(new ArrayList<>(), new ArrayList<>(), 1/*??*/, false, null, null, true, localData, traitsList, scriptInfo.traits, traitArr, initScopes, class_index, true);
generateTraitsPhase4(new ArrayList<>(), new ArrayList<>(), 1/*??*/, false, null, null, true, localData, traitsList, scriptInfo.traits, traitArr, initScopes, class_index, true);
mb.markOffsets();
mb.autoFillStats(abc, 1, false);
@@ -2380,6 +2407,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Parent names add names.
*
* @param abc ABC
* @param name_index Name index
* @param indices Indices
@@ -2410,6 +2438,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Gets trait return type.
*
* @param abc ABC
* @param t Trait
* @return Trait return type
@@ -2443,6 +2472,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Searches prototype chain.
*
* @param namespaceSuffix Namespace suffix
* @param otherNs Other namespaces
* @param privateNs Private namespace
@@ -2517,6 +2547,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Parent names.
*
* @param abc ABC
* @param name_index Name index
* @param indices Indices
@@ -2548,6 +2579,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates GetDescendants.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -2604,6 +2636,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates XMLFilter.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -2672,7 +2705,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
ret.addAll(AssignableAVM2Item.killTemp(localData, this, Arrays.asList(xmlListReg)));
return ret;
}
@Override
public List<GraphSourceItem> generate(SourceGeneratorLocalData localData, IfItem item) throws CompilationException {
return generateIf(localData, item.expression, item.onTrue, item.onFalse, false);
@@ -2684,18 +2717,18 @@ public class AVM2SourceGenerator implements SourceGenerator {
ret.add(ins(AVM2Instructions.PushNull));
AVM2Instruction ifEq = ins(AVM2Instructions.IfEq, 0);
ret.add(ifEq);
List<GraphSourceItem> onNotNull = GraphTargetItem.toSourceMerge(localData, this, item.leftSide);
List<GraphSourceItem> onNotNull = GraphTargetItem.toSourceMerge(localData, this, item.leftSide);
AVM2Instruction jump = ins(AVM2Instructions.Jump, 0);
onNotNull.add(jump);
ifEq.operands[0] = insToBytes(toInsList(onNotNull)).length;
List<GraphSourceItem> onNull = GraphTargetItem.toSourceMerge(localData, this, item.rightSide);
jump.operands[0] = insToBytes(toInsList(onNull)).length;
ret.addAll(onNotNull);
ret.addAll(onNull);
return ret;
}
@@ -2742,6 +2775,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates for each in loop.
*
* @param localData Local data
* @param item Loop item
* @return Source items
@@ -2753,6 +2787,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates for in loop.
*
* @param localData Local data
* @param item Loop item
* @return Source items
@@ -2799,6 +2834,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates with statement.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -2934,7 +2970,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
forwardJump.operands[0] = insToBytes(bodies).length;
ret.addAll(bodies);
ret.addAll(cases);
ret.add(lookupOp);
ret.add(lookupOp);
fixSwitch(toInsList(ret), insToBytes(toInsList(ret)).length, item.loop.id);
return ret;
}
@@ -2999,6 +3035,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates function.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -3028,6 +3065,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates try-catch-finally.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -3393,6 +3431,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates return value.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -3432,6 +3471,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates return void.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -3465,6 +3505,7 @@ public class AVM2SourceGenerator implements SourceGenerator {
/**
* Generates throw.
*
* @param localData Local data
* @param item Item
* @return Source items
@@ -3537,11 +3578,13 @@ public class AVM2SourceGenerator implements SourceGenerator {
List<GraphSourceItem> ret = new ArrayList<>();
return ret;
}
/**
* For some strange reasons, &amp;&amp; and || operators must have coerced both sides
* when there is specific type expected.
* @param item Item to check. If it's &amp;&amp; or ||, it will be handled, otherwise ignored
* For some strange reasons, &amp;&amp; and || operators must have coerced
* both sides when there is specific type expected.
*
* @param item Item to check. If it's &amp;&amp; or ||, it will be handled,
* otherwise ignored
* @param type Coerced type
* @return Original value or coerced item
*/
@@ -3549,14 +3592,14 @@ public class AVM2SourceGenerator implements SourceGenerator {
if (type == null) {
return item;
}
if ((item instanceof OrItem)||(item instanceof AndItem)) {
if ((item instanceof OrItem) || (item instanceof AndItem)) {
BinaryOpItem bo = (BinaryOpItem) item;
if ((bo.leftSide instanceof OrItem)||(bo.leftSide instanceof AndItem)) {
if ((bo.leftSide instanceof OrItem) || (bo.leftSide instanceof AndItem)) {
bo.leftSide = handleAndOrCoerce(bo.leftSide, type);
} else {
bo.leftSide = new CoerceAVM2Item(null, null, bo.leftSide, type);
}
if ((bo.rightSide instanceof OrItem)||(bo.rightSide instanceof AndItem)) {
if ((bo.rightSide instanceof OrItem) || (bo.rightSide instanceof AndItem)) {
bo.rightSide = handleAndOrCoerce(bo.rightSide, type);
} else {
bo.rightSide = new CoerceAVM2Item(null, null, bo.rightSide, type);
@@ -657,7 +657,7 @@ public class ActionScript3Parser {
openedNamespaces.add(privateNs);
openedNamespaces.add(protectedNs);
openedNamespaces.add(staticProtectedNs);
Stack<Loop> cinitLoops = new Stack<>();
Map<Loop, String> cinitLoopLabels = new HashMap<>();
HashMap<String, Integer> cinitRegisterVars = new HashMap<>();
@@ -686,15 +686,15 @@ public class ActionScript3Parser {
}*/
List<Map.Entry<String, Map<String, String>>> metadata = parseMetadata();
//s = lex();
ParsedSymbol s = lex();
ParsedSymbol s = lex();
while (s.isType(SymbolType.NATIVE, SymbolType.STATIC, SymbolType.PUBLIC, SymbolType.PRIVATE, SymbolType.PROTECTED, SymbolType.OVERRIDE, SymbolType.FINAL, SymbolType.DYNAMIC, SymbolGroup.IDENTIFIER, SymbolType.INTERNAL, SymbolType.PREPROCESSOR)) {
if (s.type == SymbolType.FINAL) {
if (isFinal) {
throw new AVM2ParseException("Only one final keyword allowed", lexer.yyline());
}
preSymbols.add(s);
isFinal = true;
isFinal = true;
} else if (s.type == SymbolType.OVERRIDE) {
if (isOverride) {
throw new AVM2ParseException("Only one override keyword allowed", lexer.yyline());
@@ -723,7 +723,7 @@ public class ActionScript3Parser {
preSymbols.add(s);
isNative = true;
} else if (s.group == SymbolGroup.IDENTIFIER) {
customNs = s.value.toString();
customNs = s.value.toString();
if (isInterface) {
throw new AVM2ParseException("Namespace attributes are not permitted on interface methods", lexer.yyline());
}
@@ -767,14 +767,14 @@ public class ActionScript3Parser {
s = lex();
expected(s, lexer.yyline(), SymbolType.PARENT_OPEN);
preSymbols.add(s);
s = lex();
s = lex();
expected(s, lexer.yyline(), SymbolType.STRING);
preSymbols.add(s);
preSymbols.add(s);
namespace = new NamespaceItem((String) s.value, Namespace.KIND_NAMESPACE);
s = lex();
expected(s, lexer.yyline(), SymbolType.PARENT_CLOSE);
preSymbols.add(s);
preSymbols.add(s);
} else {
lexer.pushback(s);
}
@@ -971,7 +971,7 @@ public class ActionScript3Parser {
for (int i = preSymbols.size() - 1; i >= 0; i--) {
lexer.pushback(preSymbols.get(i));
}
GraphTargetItem cmd = command(allOpenedNamespaces, null, publicNs, cinitNeedsActivation, importedClasses, openedNamespaces, cinitLoops, cinitLoopLabels, cinitRegisterVars, true, false, 0, false, cinitVariables, abc);
if (cmd != null) {
traits.add(cmd);
@@ -988,28 +988,28 @@ public class ActionScript3Parser {
List<List<NamespaceItem>> allOpenedNamespaces,
int scriptIndex,
String scriptName,
List<GraphTargetItem> traits,
Reference<Integer> numberUsageRef,
Reference<Integer> numberRoundingRef,
List<GraphTargetItem> traits,
Reference<Integer> numberUsageRef,
Reference<Integer> numberRoundingRef,
Reference<Integer> numberPrecisionRef,
ABC abc,
Reference<Boolean> sinitNeedsActivation,
List<AssignableAVM2Item> sinitVariables
) throws AVM2ParseException, IOException, CompilationException, InterruptedException {
List<AssignableAVM2Item> sinitVariables
) throws AVM2ParseException, IOException, CompilationException, InterruptedException {
Stack<Loop> sinitLoops = new Stack<>();
Map<Loop, String> sinitLoopLabels = new HashMap<>();
HashMap<String, Integer> sinitRegisterVars = new HashMap<>();
while (scriptTraitsBlock(
importedClasses,
openedNamespaces,
allOpenedNamespaces,
allOpenedNamespaces,
scriptIndex,
scriptName,
traits,
scriptName,
traits,
numberUsageRef,
numberRoundingRef,
numberRoundingRef,
numberPrecisionRef,
abc,
sinitNeedsActivation,
@@ -1017,7 +1017,7 @@ public class ActionScript3Parser {
sinitLoopLabels,
sinitRegisterVars,
sinitVariables
)) {
)) {
//empty
}
}
@@ -1029,7 +1029,7 @@ public class ActionScript3Parser {
int scriptIndex,
String scriptName,
List<GraphTargetItem> traits,
Reference<Integer> numberUsageRef,
Reference<Integer> numberUsageRef,
Reference<Integer> numberRoundingRef,
Reference<Integer> numberPrecisionRef,
ABC abc,
@@ -1037,8 +1037,8 @@ public class ActionScript3Parser {
Stack<Loop> sinitLoops,
Map<Loop, String> sinitLoopLabels,
HashMap<String, Integer> sinitRegisterVars,
List<AssignableAVM2Item> sinitVariables
) throws AVM2ParseException, IOException, CompilationException, InterruptedException {
List<AssignableAVM2Item> sinitVariables
) throws AVM2ParseException, IOException, CompilationException, InterruptedException {
ParsedSymbol s;
boolean inPackage = false;
s = lex();
@@ -1105,7 +1105,7 @@ public class ActionScript3Parser {
throw new AVM2ParseException("Only one final keyword allowed", lexer.yyline());
}
isFinal = true;
preSymbols.add(s);
preSymbols.add(s);
}
if (s.type == SymbolType.PUBLIC) {
if (!inPackage) {
@@ -1153,16 +1153,16 @@ public class ActionScript3Parser {
expected(s, lexer.yyline(), SymbolGroup.IDENTIFIER);
subNameStr = s.value.toString();
s = lex();
boolean nullable = true;
if (s.type == SymbolType.NOT) {
s = lex();
nullable = false;
} else if (s.type == SymbolType.TERNAR) {
s = lex();
}
if (!isInterface) {
if (s.type == SymbolType.EXTENDS) {
@@ -1297,11 +1297,11 @@ public class ActionScript3Parser {
break;
default:
lexer.pushback(s);
for (int i = preSymbols.size() - 1; i >= 0; i--) {
lexer.pushback(preSymbols.get(i));
}
if (parseImportsUsages(importedClasses, openedNamespaces, numberUsageRef, numberPrecisionRef, numberRoundingRef, abc)) {
break;
}
@@ -1309,7 +1309,7 @@ public class ActionScript3Parser {
if (cmd != null) {
traits.add(cmd);
isEmpty = false;
} else {
} else {
break looptrait;
}
}
@@ -2465,7 +2465,7 @@ public class ActionScript3Parser {
break;
case PLUS:
GraphTargetItem nump = expressionPrimary(allOpenedNamespaces, thisType, pkg, needsActivation, importedClasses, openedNamespaces, false, registerVars, inFunction, inMethod, true, variables, abc);
GraphTargetItem nump = expressionPrimary(allOpenedNamespaces, thisType, pkg, needsActivation, importedClasses, openedNamespaces, false, registerVars, inFunction, inMethod, true, variables, abc);
if (abc.hasFloatSupport()) {
ret = new UnPlusAVM2Item(null, null, nump);
} else {
@@ -2480,7 +2480,7 @@ public class ActionScript3Parser {
ret = new IntegerValueAVM2Item(null, null, -(Integer) s.value);
} else if (s.isType(SymbolType.DECIMAL)) {
ret = new DecimalValueAVM2Item(null, null, ((Decimal128) s.value).multiply(Decimal128.NEG1));
} else if (s.isType(SymbolType.FLOAT)) {
} else if (s.isType(SymbolType.FLOAT)) {
ret = new FloatValueAVM2Item(null, null, -(Float) s.value);
} else {
lexer.pushback(s);
@@ -2586,7 +2586,7 @@ public class ActionScript3Parser {
case DOUBLE:
ret = new DoubleValueAVM2Item(null, null, (Double) s.value);
allowMemberOrCall = true; // 5.2.toString();
break;
break;
case DECIMAL:
if (!abc.hasDecimalSupport()) {
throw new AVM2ParseException("The ABC has no decimal support", lexer.yyline());
@@ -2604,11 +2604,11 @@ public class ActionScript3Parser {
case FLOAT4:
if (!abc.hasFloat4Support()) {
//parse again as method call
lexer.yypushbackstr(lexer.yytext().substring("float4".length()));
lexer.yypushbackstr(lexer.yytext().substring("float4".length()));
lexer.pushback(new ParsedSymbol(SymbolGroup.IDENTIFIER, SymbolType.IDENTIFIER, "float4"));
ret = name(allOpenedNamespaces, thisType, pkg, needsActivation, false, openedNamespaces, registerVars, inFunction, inMethod, variables, importedClasses, abc);
ret = name(allOpenedNamespaces, thisType, pkg, needsActivation, false, openedNamespaces, registerVars, inFunction, inMethod, variables, importedClasses, abc);
} else {
ret = new Float4ValueAVM2Item(null, null, (Float4) s.value);
ret = new Float4ValueAVM2Item(null, null, (Float4) s.value);
}
allowMemberOrCall = true;
break;
@@ -2723,11 +2723,11 @@ public class ActionScript3Parser {
private boolean parseImportsUsages(List<DottedChain> importedClasses, List<NamespaceItem> openedNamespaces, Reference<Integer> numberUsageRef, Reference<Integer> numberPrecisionRef, Reference<Integer> numberRoundingRef, ABC abc) throws IOException, AVM2ParseException, InterruptedException {
boolean isEmpty = true;
ParsedSymbol s;
ParsedSymbol s;
s = lex();
while (s.isType(SymbolType.IMPORT, SymbolType.USE)) {
if (s.isType(SymbolType.IMPORT)) {
isEmpty = false;
s = lex();
@@ -2757,7 +2757,7 @@ public class ActionScript3Parser {
} else {
importedClasses.add(fullName);
}
expected(s, lexer.yyline(), SymbolType.SEMICOLON);
expected(s, lexer.yyline(), SymbolType.SEMICOLON);
} else if (s.isType(SymbolType.USE)) {
isEmpty = false;
do {
@@ -2785,7 +2785,7 @@ public class ActionScript3Parser {
if (!abc.hasDecimalSupport()) {
throw new AVM2ParseException("Invalid use kind", lexer.yyline());
}
expected(s, lexer.yyline(), SymbolType.IDENTIFIER);
String pragmaItemName = (String) s.value;
switch (pragmaItemName) {
@@ -2848,9 +2848,9 @@ public class ActionScript3Parser {
default:
throw new AVM2ParseException("Invalid use kind", lexer.yyline());
}
}
}
s = lex();
}while(s.isType(SymbolType.COMMA));
} while (s.isType(SymbolType.COMMA));
expected(s, lexer.yyline(), SymbolType.SEMICOLON);
}
/*boolean isUse = s.type == SymbolType.USE;
@@ -2858,7 +2858,7 @@ public class ActionScript3Parser {
expectedType(SymbolType.NAMESPACE);
}*/
s = lex();
}
lexer.pushback(s);
@@ -2869,13 +2869,13 @@ public class ActionScript3Parser {
List<DottedChain> importedClasses,
List<NamespaceItem> openedNamespaces,
List<List<NamespaceItem>> allOpenedNamespaces,
int scriptIndex,
String fileName,
int scriptIndex,
String fileName,
Reference<Integer> numberContextRef,
ABC abc,
Reference<Boolean> sinitNeedsActivation,
List<AssignableAVM2Item> sinitVariables
) throws IOException, AVM2ParseException, CompilationException, InterruptedException {
) throws IOException, AVM2ParseException, CompilationException, InterruptedException {
//int scriptPrivateNs;
if (fileName.contains("/")) {
@@ -2889,7 +2889,7 @@ public class ActionScript3Parser {
Reference<Integer> numberRoundingRef = new Reference<>(NumberContext.ROUND_HALF_EVEN);
Reference<Integer> numberPrecisionRef = new Reference<>(34);
scriptTraits(importedClasses, openedNamespaces, allOpenedNamespaces, scriptIndex, fileName, items, numberUsageRef, numberRoundingRef, numberPrecisionRef, abc, sinitNeedsActivation, sinitVariables);
NumberContext nc = new NumberContext(numberUsageRef.getVal(), numberPrecisionRef.getVal(), numberRoundingRef.getVal());
if (!nc.isDefault()) {
numberContextRef.setVal(nc.toParam());
@@ -2899,6 +2899,7 @@ public class ActionScript3Parser {
/**
* Converts string to script traits.
*
* @param importedClasses Imported classes
* @param openedNamespaces Opened namespaces
* @param allOpenedNamespaces All opened namespaces
@@ -2918,15 +2919,15 @@ public class ActionScript3Parser {
public List<GraphTargetItem> scriptTraitsFromString(
List<DottedChain> importedClasses,
List<NamespaceItem> openedNamespaces,
List<List<NamespaceItem>> allOpenedNamespaces,
String str,
String fileName,
int scriptIndex,
Reference<Integer> numberContextRef,
List<List<NamespaceItem>> allOpenedNamespaces,
String str,
String fileName,
int scriptIndex,
Reference<Integer> numberContextRef,
ABC abc,
Reference<Boolean> sinitNeedsActivation,
List<AssignableAVM2Item> sinitVariables
) throws AVM2ParseException, IOException, CompilationException, InterruptedException {
) throws AVM2ParseException, IOException, CompilationException, InterruptedException {
lexer = new ActionScriptLexer(str);
List<GraphTargetItem> ret = parseScript(importedClasses, openedNamespaces, allOpenedNamespaces, scriptIndex, fileName, numberContextRef, abc, sinitNeedsActivation, sinitVariables);
@@ -2938,6 +2939,7 @@ public class ActionScript3Parser {
/**
* Adds script from tree.
*
* @param sinitVariables Script initializer variables
* @param sinitNeedsActivation Script initializer needs activation
* @param importedClasses Imported classes
@@ -2972,6 +2974,7 @@ public class ActionScript3Parser {
/**
* Adds script.
*
* @param s Source code
* @param fileName File name
* @param classPos Class position
@@ -2996,6 +2999,7 @@ public class ActionScript3Parser {
/**
* Constructor.
*
* @param abcIndex ABC index
* @throws IOException On I/O error
* @throws InterruptedException On interrupt
@@ -3008,6 +3012,7 @@ public class ActionScript3Parser {
/**
* Compiles AS3 source code.
*
* @param src Source code
* @param abc ABC
* @param abcIndex ABC index
@@ -3027,7 +3032,7 @@ public class ActionScript3Parser {
ActionScript3Parser parser = new ActionScript3Parser(abcIndex);
boolean success = false;
ABC originalAbc = ((ABCContainerTag) ((Tag) abc.parentTag).cloneTag()).getABC();
Set<Integer> modifiedScripts = new HashSet<>();
Set<Integer> modifiedScripts = new HashSet<>();
for (int i = 0; i < abc.script_info.size(); i++) {
if (abc.script_info.get(i).isModified()) {
modifiedScripts.add(i);
@@ -3047,7 +3052,7 @@ public class ActionScript3Parser {
abc.script_info = originalAbc.script_info;
abc.bodies = originalAbc.bodies;
abc.resetMethodIndexing();
for (int i = 0; i < abc.script_info.size(); i++) {
if (modifiedScripts.contains(i)) {
abc.script_info.get(i).setModified(true);
@@ -3059,6 +3064,7 @@ public class ActionScript3Parser {
/**
* Compiles AS3 source code.
*
* @param swf SWF
* @param srcFile Source file
* @param destFile Target file
@@ -19,7 +19,6 @@ package com.jpexs.decompiler.flash.abc.avm2.parser.script;
import com.jpexs.decompiler.flash.SourceGeneratorLocalData;
import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instruction;
import com.jpexs.decompiler.flash.abc.avm2.instructions.AVM2Instructions;
import static com.jpexs.decompiler.flash.abc.avm2.model.AVM2Item.ins;
import com.jpexs.decompiler.flash.abc.types.Multiname;
import com.jpexs.decompiler.flash.helpers.GraphTextWriter;
import com.jpexs.decompiler.graph.CompilationException;
@@ -545,7 +545,12 @@ public class PropertyAVM2Item extends AssignableAVM2Item {
return result;
}
}
@Override
public List<GraphSourceItem> toSource(SourceGeneratorLocalData localData, SourceGenerator generator) throws CompilationException {
return toSource(localData, generator, true);
}
private int getBytesLen(List<GraphSourceItem> code) {
int len = 0;
for (GraphSourceItem instruction : code) {
@@ -555,10 +560,7 @@ public class PropertyAVM2Item extends AssignableAVM2Item {
return len;
}
@Override
public List<GraphSourceItem> toSource(SourceGeneratorLocalData localData, SourceGenerator generator) throws CompilationException {
return toSource(localData, generator, true);
}
@Override
public List<GraphSourceItem> toSourceIgnoreReturnValue(SourceGeneratorLocalData localData, SourceGenerator generator) throws CompilationException {
@@ -356,7 +356,7 @@ public abstract class Trait implements Cloneable, Serializable {
/**
* Writes imports.
*
* @param trait Trait
* @param traits Traits
* @param methodIndex Method index
* @param abcIndex ABC indexing
* @param scriptIndex Script index
@@ -80,7 +80,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
/**
* Frame trait names
*/
private final List<String> frameTraitNames = new ArrayList<>();
private final List<String> frameTraitNames = new ArrayList<>();
/**
* Deletes this trait.
@@ -147,13 +147,13 @@ public class TraitClass extends Trait implements TraitWithSlot {
//instance initializer
DependencyParser.parseDependenciesFromMethodInfo(abcIndex, null, scriptIndex, class_info, false, customNamespace, abc, instanceInfo.iinit_index, dependencies, packageName, fullyQualifiedNames, new ArrayList<>(), uses, numberContextRef);
}
@Override
public GraphTextWriter toStringHeader(int swfVersion, Trait parent, DottedChain packageName, ConvertData convertData, String path, ABC abc, boolean isStatic, ScriptExportMode exportMode, int scriptIndex, int classIndex, GraphTextWriter writer, List<DottedChain> fullyQualifiedNames, boolean parallel, boolean insideInterface) {
abc.instance_info.get(class_info).getClassHeaderStr(convertData.assetsDir, writer, abc, fullyQualifiedNames, false, false /*??*/);
return writer;
}
@Override
public void convertHeader(int swfVersion, Trait parent, ConvertData convertData, String path, ABC abc, boolean isStatic, ScriptExportMode exportMode, int scriptIndex, int classIndex, NulWriter writer, List<DottedChain> fullyQualifiedNames, boolean parallel) {
}
@@ -198,13 +198,13 @@ public class TraitClass extends Trait implements TraitWithSlot {
Multiname instanceInfoMultiname = instanceInfo.getName(abc.constants);
//DottedChain packageName = instanceInfoMultiname.getNamespace(abc.constants).getName(abc.constants); //assume not null name
Reference<Boolean> first = new Reference<>(true);
Reference<Boolean> first = new Reference<>(true);
String instanceInfoName = instanceInfoMultiname.getName(abc.constants, fullyQualifiedNames, false, true);
getMetaData(this, convertData, abc, writer);
boolean allowEmbed = true;
if (convertData.exportEmbedFlaMode) {
@@ -235,7 +235,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
}
}
}
//class header
instanceInfo.getClassHeaderStr(convertData.assetsDir, writer, abc, fullyQualifiedNames, false, allowEmbed);
writer.endTrait();
@@ -243,7 +243,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
writer.startClass(class_info);
first.setVal(true);
//static variables & constants
ClassInfo classInfo = abc.class_info.get(class_info);
classInfo.static_traits.toString(swfVersion, packageName, first, abcIndex, new Class[]{TraitSlotConst.class}, this, convertData, path + "/" + instanceInfoName, abc, true, exportMode, false, scriptIndex, class_info, writer, fullyQualifiedNames, parallel, new ArrayList<>(), isInterface);
@@ -257,7 +257,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
if (!classInitializerIsEmpty) {
//writer.startBlock();
if (!first.getVal()) {
writer.newLine();
writer.newLine();
}
first.setVal(false);
List<MethodBody> callStack = new ArrayList<>();
@@ -287,7 +287,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
ignoredInstanceVariableNames.add("__lastFrameAcc");
ignoredInstanceVariableNames.add("__lastFrameTab");
}
//instance variables
instanceInfo.instance_traits.toString(swfVersion, packageName, first, abcIndex, new Class[]{TraitSlotConst.class}, this, convertData, path + "/" + instanceInfoName, abc, false, exportMode, false, scriptIndex, class_info, writer, fullyQualifiedNames, parallel, ignoredInstanceVariableNames, isInterface);
@@ -297,7 +297,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
Multiname m = abc.constants.getMultiname(instanceInfo.name_index);
if (!first.getVal()) {
writer.newLine();
writer.newLine();
}
first.setVal(false);
writer.startTrait(GraphTextWriter.TRAIT_INSTANCE_INITIALIZER);
@@ -328,18 +328,18 @@ public class TraitClass extends Trait implements TraitWithSlot {
List<String> ignoredInstanceTraitNames = new ArrayList<>();
if (convertData.ignoreFrameScripts) {
ignoredInstanceTraitNames.addAll(frameTraitNames);
ignoredInstanceTraitNames.addAll(frameTraitNames);
}
if (convertData.ignoreAccessibility) {
if (convertData.ignoreAccessibility) {
for (Trait t : instanceInfo.instance_traits.traits) {
String traitName = t.getName(abc).getName(abc.constants, new ArrayList<>(), true, false); ;
String traitName = t.getName(abc).getName(abc.constants, new ArrayList<>(), true, false);;
if (traitName.startsWith("__setAcc_")
|| traitName.startsWith("__setTab_")) {
ignoredInstanceTraitNames.add(traitName);
}
}
}
}
//instance methods
instanceInfo.instance_traits.toString(swfVersion, packageName, first, abcIndex, new Class[]{TraitClass.class, TraitFunction.class, TraitMethodGetterSetter.class}, this, convertData, path + "/" + instanceInfoName, abc, false, exportMode, false, scriptIndex, class_info, writer, fullyQualifiedNames, parallel, ignoredInstanceTraitNames, isInterface);
@@ -351,7 +351,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
writer.newLine();
return writer;
}
@Override
public void convert(int swfVersion, AbcIndexing abcIndex, Trait parent, ConvertData convertData, String path, ABC abc, boolean isStatic, ScriptExportMode exportMode, int scriptIndex, int classIndex, NulWriter writer, List<DottedChain> fullyQualifiedNames, boolean parallel, ScopeStack scopeStack) throws InterruptedException {
@@ -432,7 +432,7 @@ public class TraitClass extends Trait implements TraitWithSlot {
if (ti instanceof CallPropertyAVM2Item) {
CallPropertyAVM2Item callProp = (CallPropertyAVM2Item) ti;
if (callProp.propertyName instanceof FullMultinameAVM2Item) {
FullMultinameAVM2Item propName = (FullMultinameAVM2Item) callProp.propertyName;
FullMultinameAVM2Item propName = (FullMultinameAVM2Item) callProp.propertyName;
if ("addFrameScript".equals(propName.resolvedMultinameName)) {
for (int i = 0; i < callProp.arguments.size(); i += 2) {
if (callProp.arguments.get(i) instanceof IntegerValueAVM2Item) {
@@ -453,14 +453,10 @@ public class TraitClass extends Trait implements TraitWithSlot {
}
constructorBody.convertedItems.remove(j);
j--;
} else if (
propName.resolvedMultinameName != null
&& (
propName.resolvedMultinameName.startsWith("__setAcc_")
|| propName.resolvedMultinameName.startsWith("__setTab_")
)
&& callProp.arguments.isEmpty()
) {
} else if (propName.resolvedMultinameName != null
&& (propName.resolvedMultinameName.startsWith("__setAcc_")
|| propName.resolvedMultinameName.startsWith("__setTab_"))
&& callProp.arguments.isEmpty()) {
//accessibilityTraitNames.add(propName.resolvedMultinameName);
constructorBody.convertedItems.remove(j);
j--;
@@ -470,14 +466,14 @@ public class TraitClass extends Trait implements TraitWithSlot {
}
}
}
if (convertData.ignoreAccessibility) {
if (constructorBody.convertedItems != null) {
for (int j = 0; j < constructorBody.convertedItems.size(); j++) {
GraphTargetItem ti = constructorBody.convertedItems.get(j);
if (ti instanceof CallPropertyAVM2Item) {
CallPropertyAVM2Item callProp = (CallPropertyAVM2Item) ti;
if (callProp.propertyName instanceof FullMultinameAVM2Item) {
FullMultinameAVM2Item propName = (FullMultinameAVM2Item) callProp.propertyName;
if ("addEventListener".equals(propName.resolvedMultinameName)) {
@@ -505,21 +501,17 @@ public class TraitClass extends Trait implements TraitWithSlot {
}
fm = (FullMultinameAVM2Item) gp.propertyName;
if (!("__setAcc_handler".equals(fm.resolvedMultinameName)
|| "__setTab_handler".equals(fm.resolvedMultinameName))) {
|| "__setTab_handler".equals(fm.resolvedMultinameName))) {
continue;
}
constructorBody.convertedItems.remove(j);
j--;
}
if (
propName.resolvedMultinameName != null
&& (
propName.resolvedMultinameName.startsWith("__setAcc_")
|| propName.resolvedMultinameName.startsWith("__setTab_")
)
&& callProp.arguments.isEmpty()
) {
if (propName.resolvedMultinameName != null
&& (propName.resolvedMultinameName.startsWith("__setAcc_")
|| propName.resolvedMultinameName.startsWith("__setTab_"))
&& callProp.arguments.isEmpty()) {
//accessibilityTraitNames.add(propName.resolvedMultinameName);
constructorBody.convertedItems.remove(j);
j--;
@@ -313,9 +313,9 @@ public class Traits implements Cloneable, Serializable {
* @return Writer
* @throws InterruptedException On interrupt
*/
public GraphTextWriter toString(int swfVersion, DottedChain packageName, Reference<Boolean> first, AbcIndexing abcIndex, Class[] traitTypes, Trait parent, ConvertData convertData, String path, ABC abc, boolean isStatic, ScriptExportMode exportMode, boolean makePackages, int scriptIndex, int classIndex, GraphTextWriter writer, List<DottedChain> fullyQualifiedNames, boolean parallel, List<String> ignoredTraitNames, boolean insideInterface) throws InterruptedException {
public GraphTextWriter toString(int swfVersion, DottedChain packageName, Reference<Boolean> first, AbcIndexing abcIndex, Class[] traitTypes, Trait parent, ConvertData convertData, String path, ABC abc, boolean isStatic, ScriptExportMode exportMode, boolean makePackages, int scriptIndex, int classIndex, GraphTextWriter writer, List<DottedChain> fullyQualifiedNames, boolean parallel, List<String> ignoredTraitNames, boolean insideInterface) throws InterruptedException {
List<Trait> ordered = traits;
for (Trait trait : ordered) {
int t = traits.indexOf(trait);
if (traitTypes != null) {
@@ -336,23 +336,23 @@ public class Traits implements Cloneable, Serializable {
if (ignoredTraitNames.contains(trait.getName(abc).getName(abc.constants, new ArrayList<>(), false, false))) {
continue;
}
if ((trait instanceof TraitSlotConst) && convertData.assignedValues.containsKey((TraitSlotConst) trait) && isStatic) {
continue;
}
if (!first.getVal()) {
writer.newLine();
writer.newLine();
}
first.setVal(false);
int h = abc.getGlobalTraitId(TraitType.METHOD , isStatic, classIndex, t);
int h = abc.getGlobalTraitId(TraitType.METHOD, isStatic, classIndex, t);
writer.startTrait(h);
if (makePackages) {
trait.toStringPackaged(swfVersion, abcIndex, parent, convertData, path, abc, isStatic, exportMode, scriptIndex, classIndex, writer, fullyQualifiedNames, parallel, insideInterface);
} else {
trait.toString(swfVersion, abcIndex, packageName, parent, convertData, path, abc, isStatic, exportMode, scriptIndex, classIndex, writer, fullyQualifiedNames, parallel, insideInterface);
}
writer.endTrait();
writer.endTrait();
}
return writer;
}
@@ -38,6 +38,7 @@ public abstract class MethodMultinameUsage extends TraitMultinameUsage {
/**
* Constructor.
*
* @param abc ABC
* @param multinameIndex Multiname index
* @param scriptIndex Script index
@@ -55,6 +56,7 @@ public abstract class MethodMultinameUsage extends TraitMultinameUsage {
/**
* Is initializer.
*
* @return Is initializer
*/
public boolean isInitializer() {
@@ -102,7 +104,7 @@ public abstract class MethodMultinameUsage extends TraitMultinameUsage {
if (traitsType == TRAITS_TYPE_CLASS) {
((TraitMethodGetterSetter) abc.class_info.get(classIndex).static_traits.traits.get(parentTraitIndex)).toStringHeader(-1, null, DottedChain.EMPTY /*??*/, convertData, "", abc, traitsType == TRAITS_TYPE_CLASS, ScriptExportMode.AS, -1/*FIXME*/, classIndex, writer, new ArrayList<>(), false, insideInterface);
} else {
((TraitMethodGetterSetter) abc.instance_info.get(classIndex).instance_traits.traits.get(parentTraitIndex)).toStringHeader(-1, null, DottedChain.EMPTY /*??*/,convertData, "", abc, traitsType == TRAITS_TYPE_CLASS, ScriptExportMode.AS, -1/*FIXME*/, classIndex, writer, new ArrayList<>(), false, insideInterface);
((TraitMethodGetterSetter) abc.instance_info.get(classIndex).instance_traits.traits.get(parentTraitIndex)).toStringHeader(-1, null, DottedChain.EMPTY /*??*/, convertData, "", abc, traitsType == TRAITS_TYPE_CLASS, ScriptExportMode.AS, -1/*FIXME*/, classIndex, writer, new ArrayList<>(), false, insideInterface);
}
writer.appendNoHilight(" ");
}
@@ -142,6 +144,7 @@ public abstract class MethodMultinameUsage extends TraitMultinameUsage {
/**
* Is static.
*
* @return Is static
*/
public boolean isStatic() {
@@ -65,8 +65,10 @@ public abstract class ABCWalker {
*/
public ABCWalker() {
}
/**
* Walks ABC
*
* @param abc ABC
* @param walkOrphanItems Walk orphan items
*/
@@ -99,6 +101,7 @@ public abstract class ABCWalker {
/**
* Optional handle class
*
* @param handledClasses Handled classes
* @param handledMethodBodies Handled method bodies
* @param handledMethodInfos Handled method infos
@@ -126,6 +129,7 @@ public abstract class ABCWalker {
/**
* Optional handle method info.
*
* @param handledMethodBodies Handled method bodies
* @param handledMethodInfos Handled method infos
* @param abc ABC
@@ -161,6 +165,7 @@ public abstract class ABCWalker {
/**
* Optional handle method body.
*
* @param handledMethodBodies Handled method bodies
* @param handledMethodInfos Handled method infos
* @param abc ABC
@@ -192,6 +197,7 @@ public abstract class ABCWalker {
/**
* Walk traits.
*
* @param abc ABC
* @param traits Traits
* @param scriptIndex Script index
@@ -250,6 +256,7 @@ public abstract class ABCWalker {
/**
* Handle method info.
*
* @param abc ABC
* @param index Index
* @param scriptIndex Script index
@@ -266,6 +273,7 @@ public abstract class ABCWalker {
/**
* Handle method body.
*
* @param abc ABC
* @param index Index
* @param scriptIndex Script index
@@ -280,6 +288,7 @@ public abstract class ABCWalker {
/**
* Handle class.
*
* @param abc ABC
* @param index Index
* @param scriptIndex Script index
@@ -292,6 +301,7 @@ public abstract class ABCWalker {
/**
* Handle script.
*
* @param abc ABC
* @param index Index
*/
@@ -301,6 +311,7 @@ public abstract class ABCWalker {
/**
* Handle trait slot const.
*
* @param abc ABC
* @param trait Trait
* @param scriptIndex Script index
@@ -318,6 +329,7 @@ public abstract class ABCWalker {
/**
* Handle trait method getter setter.
*
* @param abc ABC
* @param trait Trait
* @param scriptIndex Script index
@@ -332,6 +344,7 @@ public abstract class ABCWalker {
/**
* Handle trait function.
*
* @param abc ABC
* @param trait Trait
* @param scriptIndex Script index
@@ -346,6 +359,7 @@ public abstract class ABCWalker {
/**
* Handle trait class.
*
* @param abc ABC
* @param trait Trait
* @param scriptIndex Script index
@@ -357,6 +371,7 @@ public abstract class ABCWalker {
/**
* Handle metadata info.
*
* @param abc ABC
* @param index Index
* @param trait Trait
@@ -728,50 +728,49 @@ public abstract class Action implements GraphSourceItem {
}
} else {
//if (!(a instanceof ActionNop)) {
String add = "";
String add = "";
//Flash player 4 does not allow more than 1 item in ActionPush, so I commented this out
/*if ((a instanceof ActionPush) && lastPush) {
writer.appendNoHilight(", ");
((ActionPush) a).paramsToStringReplaced(list, importantOffsets, exportMode, writer);
} else
*/
{
if (lastPush) {
writer.newLine();
//lastPush = false;
}
{ */
if (lastPush) {
writer.newLine();
//lastPush = false;
}
writer.append("", offset, a.getFileOffset());
writer.append("", offset, a.getFileOffset());
int fixBranch = -1;
if (a instanceof ActionIf) {
ActionIf aif = (ActionIf) a;
if (aif.jumpUsed && !aif.ignoreUsed) {
fixBranch = 0;
}
if (!aif.jumpUsed && aif.ignoreUsed) {
fixBranch = 1;
}
int fixBranch = -1;
if (a instanceof ActionIf) {
ActionIf aif = (ActionIf) a;
if (aif.jumpUsed && !aif.ignoreUsed) {
fixBranch = 0;
}
if (fixBranch > -1) {
writer.appendNoHilight("FFDec_DeobfuscatePop");
if (fixBranch == 0) { //jump
writer.newLine();
writer.appendNoHilight("Jump loc");
writer.appendNoHilight(Helper.formatAddress(((ActionIf) a).getTargetAddress()));
} else {
//nojump, ignore
}
} else {
a.getASMSourceReplaced(list, importantOffsets, exportMode, writer);
}
writer.appendNoHilight(a.isIgnored() ? "; ignored" : "");
writer.appendNoHilight(add);
if (!(a instanceof ActionPush)) {
writer.newLine();
if (!aif.jumpUsed && aif.ignoreUsed) {
fixBranch = 1;
}
}
if (fixBranch > -1) {
writer.appendNoHilight("FFDec_DeobfuscatePop");
if (fixBranch == 0) { //jump
writer.newLine();
writer.appendNoHilight("Jump loc");
writer.appendNoHilight(Helper.formatAddress(((ActionIf) a).getTargetAddress()));
} else {
//nojump, ignore
}
} else {
a.getASMSourceReplaced(list, importantOffsets, exportMode, writer);
}
writer.appendNoHilight(a.isIgnored() ? "; ignored" : "");
writer.appendNoHilight(add);
if (!(a instanceof ActionPush)) {
writer.newLine();
}
//}
lastPush = a instanceof ActionPush;
//}
}
@@ -985,8 +984,7 @@ public abstract class Action implements GraphSourceItem {
public List<GraphTargetItem> call() throws Exception {
int staticOperation = 0;
boolean insideDoInitAction = (asm instanceof DoInitActionTag);
List<GraphTargetItem>
tree = actionsToTree(uninitializedClassTraits, insideDoInitAction, false, new HashMap<>(), new HashMap<>(), new HashMap<>(), actions, version, staticOperation, path, charset);
List<GraphTargetItem> tree = actionsToTree(uninitializedClassTraits, insideDoInitAction, false, new HashMap<>(), new HashMap<>(), new HashMap<>(), actions, version, staticOperation, path, charset);
SWFDecompilerPlugin.fireActionTreeCreated(tree, swf);
for (ActionTreeOperation treeOperation : treeOperations) {
treeOperation.run(tree);
@@ -1055,6 +1053,7 @@ public abstract class Action implements GraphSourceItem {
/**
* Converts list of actions to List of treeItems.
*
* @param uninitializedClassTraits Uninitialized class traits
* @param insideDoInitAction Inside DoInitAction?
* @param insideFunction Inside function?
@@ -1237,7 +1236,7 @@ public abstract class Action implements GraphSourceItem {
loopip:
while (ip <= end) {
long addr = ip2adr(actions, ip);
long addr = ip2adr(actions, ip);
if (ip > end) {
break;
}
@@ -1248,7 +1247,7 @@ public abstract class Action implements GraphSourceItem {
if (Configuration.simplifyExpressions.get()) {
stack.simplify();
}
Action action = actions.get(ip);
Action action = actions.get(ip);
if (action.isIgnored()) {
ip++;
continue;
@@ -705,7 +705,7 @@ public class FastActionList implements Collection<ActionItem> {
}
modified = false;
ActionItem item = firstItem2;
do {
do {
ActionItem next = item.next;
//ActionItem alternativeNext = null;
Action action = item.action;
@@ -880,7 +880,7 @@ public class FastActionList implements Collection<ActionItem> {
/**
* Converts the list to an array.
*
* @param the array into which the elements of this collection are to be
* @param a the array into which the elements of this collection are to be
* stored, if it is big enough; otherwise, a new array of the same runtime
* type is allocated for this purpose.
* @param <T> Type
@@ -54,7 +54,6 @@ public class FSCommand2ActionItem extends ActionItem {
*
* @param instruction Instruction
* @param lineStartIns Line start instruction
* @param command Command
* @param arguments Arguments
*/
public FSCommand2ActionItem(GraphSourceItem instruction, GraphSourceItem lineStartIns, List<GraphTargetItem> arguments) {
@@ -17,7 +17,6 @@
package com.jpexs.decompiler.flash.action.model;
import com.jpexs.decompiler.flash.SourceGeneratorLocalData;
import com.jpexs.decompiler.flash.action.model.operations.AddActionItem;
import com.jpexs.decompiler.flash.action.model.operations.StringAddActionItem;
import com.jpexs.decompiler.flash.action.parser.script.ActionSourceGenerator;
import com.jpexs.decompiler.flash.action.swf3.ActionGetURL;
@@ -49,6 +48,7 @@ public class FSCommandActionItem extends ActionItem {
* Parameter
*/
private final GraphTargetItem parameter;
/**
* Constructor.
*
@@ -89,10 +89,12 @@ public class FSCommandActionItem extends ActionItem {
private List<GraphSourceItem> toSource(SourceGeneratorLocalData localData, SourceGenerator generator, boolean needsReturn) throws CompilationException {
ActionSourceGenerator asGenerator = (ActionSourceGenerator) generator;
String charset = asGenerator.getCharset();
if ((command instanceof DirectValueActionItem)
if ((command instanceof DirectValueActionItem)
&& ((DirectValueActionItem) command).isString()
&& (parameter == null ||
((parameter instanceof DirectValueActionItem) && ((DirectValueActionItem) parameter).isString()))) {
&& (
parameter == null
|| ((parameter instanceof DirectValueActionItem) && ((DirectValueActionItem) parameter).isString())
)) {
return toSourceMerge(localData, generator, new ActionGetURL("FSCommand:" + ((DirectValueActionItem) command).getAsString(), parameter == null ? "" : ((DirectValueActionItem) parameter).getAsString(), charset));
}
return toSourceMerge(localData, generator, new StringAddActionItem(null, null, asGenerator.pushConstTargetItem("FSCommand:"), command), parameter == null ? asGenerator.pushConstTargetItem("") : parameter, new ActionGetURL2(1/*GET*/, false, false, charset), needsReturn ? new ActionPush(new Object[]{Undefined.INSTANCE, Undefined.INSTANCE}, charset) : null);
@@ -126,7 +126,6 @@ import com.jpexs.decompiler.flash.action.model.operations.StringNeActionItem;
import com.jpexs.decompiler.flash.action.model.operations.SubtractActionItem;
import com.jpexs.decompiler.flash.action.model.operations.URShiftActionItem;
import com.jpexs.decompiler.flash.action.parser.ActionParseException;
import static com.jpexs.decompiler.flash.action.parser.script.SymbolType.FSCOMMAND;
import com.jpexs.decompiler.flash.action.swf4.ActionIf;
import com.jpexs.decompiler.flash.action.swf4.ActionPush;
import com.jpexs.decompiler.flash.action.swf4.ConstantIndex;
@@ -253,6 +252,7 @@ public class ActionScript2Parser {
/**
* Constructor
*
* @param swf Swf
* @param targetSource Target source
*/
@@ -269,6 +269,7 @@ public class ActionScript2Parser {
/**
* Parse SWF classes
*
* @param swf SWF
*/
private void parseSwfClasses(SWF swf) {
@@ -598,7 +599,7 @@ public class ActionScript2Parser {
s = lex();
GraphTargetItem parameter = null;
if (s.isType(SymbolType.COMMA)) {
parameter = expression(inFunction, inMethod, inTellTarget, true, variables, functions, false, hasEval);
parameter = expression(inFunction, inMethod, inTellTarget, true, variables, functions, false, hasEval);
} else {
lexer.pushback(s);
}
@@ -1408,7 +1409,7 @@ public class ActionScript2Parser {
}
return new EmptyCommand();
case DIRECTIVE:
switch((String)s.value) {
switch ((String) s.value) {
case "strict":
ret = new StrictModeActionItem(null, null, 1);
break;
@@ -2147,12 +2148,12 @@ public class ActionScript2Parser {
}
private DirectValueActionItem pushConst(String s) throws IOException, ActionParseException {
//ActionConstantPool was introduced in SWF 5
if (swfVersion < 5) {
return new DirectValueActionItem(null, null, 0, s, constantPool);
}
int index = constantPool.indexOf(s);
if (index == -1) {
if (ActionConstantPool.calculateSize(constantPool) + ActionConstantPool.calculateSize(s) <= 0xffff) {
@@ -2175,6 +2176,7 @@ public class ActionScript2Parser {
/**
* Convert a string to a high-level model.
*
* @param str The string to convert
* @param constantPool The constant pool to use
* @return The high-level model
@@ -2481,6 +2483,7 @@ public class ActionScript2Parser {
/**
* Converts a string to a list of actions.
*
* @param s The string to convert
* @param charset Charset
* @return List of actions
@@ -94,6 +94,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Constructor.
*
* @param swfVersion SWF version
* @param constantPool Constant pool
* @param charset Charset
@@ -106,6 +107,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Generates unique ID.
*
* @return Unique ID
*/
public String uniqId() {
@@ -115,6 +117,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets charset.
*
* @return Charset
*/
public String getCharset() {
@@ -131,22 +134,23 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Converts list of GraphSourceItem to list of Action.
*
* @param items List of GraphSourceItem
* @return List of Action
*/
public List<Action> toActionList(List<GraphSourceItem> items) {
items = groupPushes(items);
List<Action> ret = new ArrayList<>();
for (GraphSourceItem s : items) {
for (GraphSourceItem s : items) {
if (s instanceof Action) {
ret.add((Action) s);
ret.add((Action) s);
}
}
}
return ret;
}
private List<GraphSourceItem> groupPushes(List<GraphSourceItem> items) {
//TODO: This should take in account important offsets (jumps)
//And not group Pushes over different parts of code
/*Like:
@@ -157,9 +161,7 @@ public class ActionSourceGenerator implements SourceGenerator {
Push "C"
Should not be grouped to Push "A","B","C"
*/
*/
return items;
//Commented out for now...
/*if (swfVersion <= 4) {
@@ -223,10 +225,9 @@ public class ActionSourceGenerator implements SourceGenerator {
ifaif.setJumpOffset(onTrueLen);
ActionJump ajmp = null;
if (onFalse != null) {
if (onTrueCmds.isEmpty() ||
!((onTrueCmds.get(onTrueCmds.size() - 1) instanceof ContinueItem)
|| (onTrueCmds.get(onTrueCmds.size() - 1) instanceof BreakItem))
) {
if (onTrueCmds.isEmpty()
|| !((onTrueCmds.get(onTrueCmds.size() - 1) instanceof ContinueItem)
|| (onTrueCmds.get(onTrueCmds.size() - 1) instanceof BreakItem))) {
ajmp = new ActionJump(0, charset);
ret.add(ajmp);
onTrueLen += ajmp.getTotalActionLength();
@@ -266,6 +267,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets register variables.
*
* @param localData Local data
* @return Register variables
*/
@@ -275,6 +277,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Sets register variables.
*
* @param localData Local data
* @param value Register variables
*/
@@ -284,6 +287,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Sets in function.
*
* @param localData Local data
* @param value Value
*/
@@ -293,6 +297,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets in function.
*
* @param localData Local data
* @return Value
*/
@@ -302,6 +307,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Checks if in method.
*
* @param localData Local data
* @return True if in method
*/
@@ -311,6 +317,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Sets in method.
*
* @param localData Local data
* @param value Value
*/
@@ -320,6 +327,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets for in level.
*
* @param localData Local data
* @return For in level
*/
@@ -329,6 +337,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Sets for in level.
*
* @param localData Local data
* @param value Value
*/
@@ -338,6 +347,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets temp register.
*
* @param localData Local data
* @return Temp register
*/
@@ -354,6 +364,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Releases temp register.
*
* @param localData Local data
* @param tmp Temp register
*/
@@ -467,6 +478,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets SWF version.
*
* @return SWF version
*/
public int getSwfVersion() {
@@ -475,6 +487,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets constant pool.
*
* @return Constant pool
*/
public List<String> getConstantPool() {
@@ -483,6 +496,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets Push constant item.
*
* @param s Constant
* @return Push constant item
*/
@@ -497,6 +511,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Gets Push constant action.
*
* @param s Constant
* @return Push constant action
*/
@@ -518,6 +533,7 @@ public class ActionSourceGenerator implements SourceGenerator {
/**
* Generates traits.
*
* @param localData Local data
* @param isInterface Is interface
* @param name Name
@@ -1028,7 +1044,7 @@ public class ActionSourceGenerator implements SourceGenerator {
for (GraphTargetItem item : commands) {
ret.addAll(item.toSourceIgnoreReturnValue(localData, this));
}
ret = groupPushes(ret);
ret = groupPushes(ret);
return ret;
}
@@ -93,6 +93,7 @@ public class ActionGetURL2 extends Action {
/**
* Constructor
*
* @param sendVarsMethod Send variables method
* @param loadVariablesFlag Load variables flag
* @param loadTargetFlag Load target flag
@@ -107,6 +108,7 @@ public class ActionGetURL2 extends Action {
/**
* Constructor
*
* @param actionLength Action length
* @param sis SWF input stream
* @param charset Charset
@@ -145,6 +147,7 @@ public class ActionGetURL2 extends Action {
/**
* Constructor
*
* @param lexer Lexer
* @param charset Charset
* @throws IOException On I/O error
@@ -219,10 +222,7 @@ public class ActionGetURL2 extends Action {
}
}
}
if (loadVariablesFlag) {
if (num != null) {
output.add(new LoadVariablesNumActionItem(this, lineStartAction, urlString, num, sendVarsMethod));
@@ -244,7 +244,7 @@ public class ActionGetURL2 extends Action {
boolean doPrintAsBitmap = false;
boolean doFSCommand = false;
boolean doUnload = false;
if (urlString.isCompileTime() && (urlString.getResult() instanceof String)) {
String urlStr = (String) urlString.getResult();
if ("".equals(urlStr)) {
@@ -260,30 +260,30 @@ public class ActionGetURL2 extends Action {
doFSCommand = true;
}
} else if (urlString instanceof StringAddActionItem) {
StringAddActionItem sa = (StringAddActionItem) urlString;
if (sa.leftSide.isCompileTime()) {
Object res = sa.leftSide.getResult();
if (res instanceof String) {
String urlStr = (String) res;
switch (urlStr) {
case printPrefix:
printType = sa.rightSide;
doPrint = true;
urlString = null;
break;
case printAsBitmapPrefix:
printType = sa.rightSide;
doPrintAsBitmap = true;
urlString = null;
break;
case fscommandPrefix:
urlString = sa.rightSide;
doFSCommand = true;
break;
}
StringAddActionItem sa = (StringAddActionItem) urlString;
if (sa.leftSide.isCompileTime()) {
Object res = sa.leftSide.getResult();
if (res instanceof String) {
String urlStr = (String) res;
switch (urlStr) {
case printPrefix:
printType = sa.rightSide;
doPrint = true;
urlString = null;
break;
case printAsBitmapPrefix:
printType = sa.rightSide;
doPrintAsBitmap = true;
urlString = null;
break;
case fscommandPrefix:
urlString = sa.rightSide;
doFSCommand = true;
break;
}
}
}
}
if (num != null) {
if (doUnload) {
@@ -279,6 +279,7 @@ public class Amf0InputStream extends InputStream {
/**
* Reads UTF-8 value
*
* @param name Name
* @return UTF-8 value
* @throws IOException On I/O error
@@ -294,6 +295,7 @@ public class Amf0InputStream extends InputStream {
/**
* Reads UTF-8-long value
*
* @param name Name
* @return UTF-8-long value
* @throws IOException On I/O error
@@ -314,13 +316,15 @@ public class Amf0InputStream extends InputStream {
populateComplexObjects(value, complexObjects);
return resolveReferences(value, complexObjects);
}
/**
* Reads AMF0 value
*
* @param name Name
* @return AMF0 value
* @throws IOException On I/O error
* @throws NoSerializerExistsException When reading is switched to AMF3 and no serializer found for an object
* @throws NoSerializerExistsException When reading is switched to AMF3 and
* no serializer found for an object
*/
public Object readValue(String name) throws IOException, NoSerializerExistsException {
newDumpLevel(name, "value-type");
@@ -328,7 +332,7 @@ public class Amf0InputStream extends InputStream {
int marker = readInternal();
//System.err.println("marker " + Integer.toHexString(marker));
switch (marker) {
case Marker.NUMBER:
case Marker.NUMBER:
result = readDouble("DOUBLE");
break;
case Marker.BOOLEAN:
@@ -352,7 +356,7 @@ public class Amf0InputStream extends InputStream {
break;
}
object.properties.put(propName, val);
}
}
result = object;
break;
case Marker.MOVIECLIP:
@@ -370,7 +374,7 @@ public class Amf0InputStream extends InputStream {
int associativeCount = (int) readU32("associative-count");
EcmaArrayType ea = new EcmaArrayType();
for (int a = 0; a < associativeCount; a++) {
String eaKey = readUtf8("key");
String eaKey = readUtf8("key");
Object eaVal = readValue("value");
ea.denseValues.put(eaKey, eaVal);
}
@@ -413,7 +417,7 @@ public class Amf0InputStream extends InputStream {
typedObject.className = className;
while (true) {
propName = readUtf8("propertyName");
propName = readUtf8("propertyName");
val = readValue("propertyValue");
if (propName.equals("")) {
break;
@@ -424,28 +428,28 @@ public class Amf0InputStream extends InputStream {
break;
case Marker.AVMPLUS_OBJECT:
Amf3InputStream amf3 = new Amf3InputStream(is);
result = amf3.readValue("avm-plus-object");
result = amf3.readValue("avm-plus-object");
break;
default:
throw new IllegalArgumentException("Unsupported type");
}
/*if (result != null) {
System.err.println("Read: " + Amf0Exporter.amfToString(result, 0, "\r\n", new ArrayList<>(), new HashMap<>(), new HashMap<>()));
}*/
endDumpLevel();
return result;
}
public void resolveMapReferences(Map<String, Object> map) {
public void resolveMapReferences(Map<String, Object> map) {
List<Object> complexObjects = new ArrayList<>();
populateComplexObjects((List<Object>)new ArrayList<>(map.values()), complexObjects);
populateComplexObjects((List<Object>) new ArrayList<>(map.values()), complexObjects);
for (String key : map.keySet()) {
map.put(key, resolveReferences(map.get(key), complexObjects));
}
map.put(key, resolveReferences(map.get(key), complexObjects));
}
}
public Object resolveReferences(Object value, List<Object> complexObjects) {
if (value instanceof ReferenceType) {
ReferenceType rt = (ReferenceType) value;
@@ -454,19 +458,19 @@ public class Amf0InputStream extends InputStream {
if (value instanceof ObjectType) {
ObjectType ot = (ObjectType) value;
for (String key : ot.properties.keySet()) {
ot.properties.put(key, resolveReferences(ot.properties.get(key), complexObjects));
ot.properties.put(key, resolveReferences(ot.properties.get(key), complexObjects));
}
}
if (value instanceof TypedObjectType) {
TypedObjectType tot = (TypedObjectType) value;
for (String key : tot.properties.keySet()) {
tot.properties.put(key, resolveReferences(tot.properties.get(key), complexObjects));
tot.properties.put(key, resolveReferences(tot.properties.get(key), complexObjects));
}
}
if (value instanceof EcmaArrayType) {
EcmaArrayType eat = (EcmaArrayType) value;
for (String key : eat.denseValues.keySet()) {
eat.denseValues.put(key, resolveReferences(eat.denseValues.get(key), complexObjects));
eat.denseValues.put(key, resolveReferences(eat.denseValues.get(key), complexObjects));
}
for (String key : eat.associativeValues.keySet()) {
eat.associativeValues.put(key, resolveReferences(eat.associativeValues.get(key), complexObjects));
@@ -480,13 +484,13 @@ public class Amf0InputStream extends InputStream {
}
return value;
}
public void populateComplexObjects(List<Object> values, List<Object> result) {
for (Object value : values) {
populateComplexObjects(value, result);
}
}
public void populateComplexObjects(Object value, List<Object> result) {
if (result.contains(value)) {
return;
@@ -502,5 +506,5 @@ public class Amf0InputStream extends InputStream {
@Override
public long skip(long n) throws IOException {
return is.skip(n);
}
}
}
@@ -35,17 +35,19 @@ import java.util.List;
public class Amf0OutputStream extends OutputStream {
private final OutputStream os;
/**
* Constructor.
*
* @param os Output stream
*/
public Amf0OutputStream(OutputStream os) {
this.os = os;
this.os = os;
}
/**
* Writes U8 (unsigned 8-bit integer).
*
* @param v Value
* @throws IOException On I/O error
*/
@@ -55,6 +57,7 @@ public class Amf0OutputStream extends OutputStream {
/**
* Writes U16 (unsigned 16-bit integer).
*
* @param v Value
* @throws IOException On I/O error
*/
@@ -64,9 +67,10 @@ public class Amf0OutputStream extends OutputStream {
write(b1);
write(b2);
}
/**
* Writes S16 (signed 16-bit integer).
*
* @param v Value
* @throws IOException On I/O error
*/
@@ -76,9 +80,10 @@ public class Amf0OutputStream extends OutputStream {
write(b1);
write(b2);
}
/**
* Writes U32 (unsigned 32-bit integer).
*
* @param v Value
* @throws IOException On I/O error
*/
@@ -96,15 +101,17 @@ public class Amf0OutputStream extends OutputStream {
/**
* Writes double.
*
* @param v Value
* @throws IOException On I/O error
*/
public void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
/**
* Writes long.
*
* @param value Value
* @throws IOException On I/O error
*/
@@ -123,13 +130,14 @@ public class Amf0OutputStream extends OutputStream {
/**
* Writes bytes.
*
* @param data Data
* @throws IOException On I/O error
*/
public void writeBytes(byte[] data) throws IOException {
os.write(data);
}
@Override
public void write(int v) throws IOException {
os.write(v);
@@ -144,41 +152,41 @@ public class Amf0OutputStream extends OutputStream {
public void write(byte[] b, int off, int len) throws IOException {
os.write(b, off, len);
}
public void writeUtf8(String value) throws IOException {
byte[] data = value.getBytes("UTF-8");
writeU16(data.length);
writeBytes(data);
writeBytes(data);
}
public void writeUtf8Long(String value) throws IOException {
byte[] data = value.getBytes("UTF-8");
writeU32(data.length);
writeBytes(data);
writeBytes(data);
}
public void writeObjectProperty(String name, Object value, List<Object> complexObjectsList) throws IOException {
writeUtf8(name);
writeValue(value, complexObjectsList);
}
public void writeUtf8Empty() throws IOException {
writeU16(0);
}
public void writeValue(Object value, List<Object> complexObjectsList) throws IOException {
if (value instanceof ComplexObject) {
int index = complexObjectsList.indexOf(value);
if (index != -1 && index <= 65535) {
write(Marker.REFERENCE);
writeU16(index);
writeU16(index);
return;
} else {
complexObjectsList.add(value);
}
}
if (value instanceof Double) {
write(Marker.NUMBER);
writeDouble((Double) value);
@@ -198,7 +206,7 @@ public class Amf0OutputStream extends OutputStream {
write(Marker.OBJECT);
ObjectType ot = (ObjectType) value;
for (String key : ot.properties.keySet()) {
writeObjectProperty(key, ot.properties.get(key), complexObjectsList);
writeObjectProperty(key, ot.properties.get(key), complexObjectsList);
}
writeUtf8Empty();
write(Marker.OBJECT_END);
@@ -211,7 +219,7 @@ public class Amf0OutputStream extends OutputStream {
EcmaArrayType ea = (EcmaArrayType) value;
writeU32(ea.denseValues.size());
for (String key : ea.denseValues.keySet()) {
writeObjectProperty(key, ea.denseValues.get(key), complexObjectsList);
writeObjectProperty(key, ea.denseValues.get(key), complexObjectsList);
}
for (String key : ea.associativeValues.keySet()) {
writeObjectProperty(key, ea.associativeValues.get(key), complexObjectsList);
@@ -239,14 +247,14 @@ public class Amf0OutputStream extends OutputStream {
TypedObjectType tot = (TypedObjectType) value;
writeUtf8(tot.className);
for (String key : tot.properties.keySet()) {
writeObjectProperty(key, tot.properties.get(key), complexObjectsList);
writeObjectProperty(key, tot.properties.get(key), complexObjectsList);
}
writeUtf8Empty();
write(Marker.OBJECT_END);
} else {
throw new IllegalArgumentException("Unsupported value type for serialization");
}
//TODO: Switching to AMF3 when necessary
}
}
@@ -16,7 +16,7 @@
*/
package com.jpexs.decompiler.flash.amf.amf0.types;
import com.jpexs.decompiler.flash.amf.amf3.types.*;
import com.jpexs.decompiler.flash.amf.amf3.types.Amf3ValueType;
/**
* Basic AMF0 types.
@@ -16,8 +16,7 @@
*/
package com.jpexs.decompiler.flash.amf.amf0.types;
import com.jpexs.decompiler.flash.amf.amf3.types.*;
import com.jpexs.decompiler.flash.exporters.amf.amf3.Amf3Exporter;
import com.jpexs.decompiler.flash.amf.amf3.types.Amf3ValueType;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@@ -16,7 +16,7 @@
*/
package com.jpexs.decompiler.flash.amf.amf0.types;
import com.jpexs.decompiler.flash.amf.amf3.types.*;
import com.jpexs.decompiler.flash.amf.amf3.types.Amf3ValueType;
import java.util.ArrayList;
import java.util.List;
@@ -19,8 +19,8 @@ package com.jpexs.decompiler.flash.amf.amf3;
import com.jpexs.decompiler.flash.amf.amf3.types.Amf3ValueType;
import com.jpexs.decompiler.flash.amf.amf3.types.BasicType;
import com.jpexs.decompiler.flash.exporters.amf.amf3.Amf3Exporter;
import com.jpexs.decompiler.flash.importers.amf.amf3.Amf3Importer;
import com.jpexs.decompiler.flash.importers.amf.AmfParseException;
import com.jpexs.decompiler.flash.importers.amf.amf3.Amf3Importer;
import com.jpexs.decompiler.flash.types.annotations.Multiline;
import com.jpexs.decompiler.flash.types.annotations.SWFField;
import java.io.IOException;
@@ -18,11 +18,14 @@ package com.jpexs.decompiler.flash.exporters.amf.amf0;
import com.jpexs.decompiler.flash.amf.amf0.types.ArrayType;
import com.jpexs.decompiler.flash.amf.amf0.types.BasicType;
import com.jpexs.decompiler.flash.amf.amf0.types.ComplexObject;
import com.jpexs.decompiler.flash.amf.amf0.types.DateType;
import com.jpexs.decompiler.flash.amf.amf0.types.EcmaArrayType;
import com.jpexs.decompiler.flash.amf.amf0.types.ObjectType;
import com.jpexs.decompiler.flash.amf.amf0.types.ReferenceType;
import com.jpexs.decompiler.flash.amf.amf0.types.TypedObjectType;
import com.jpexs.decompiler.flash.amf.amf0.types.XmlDocumentType;
import com.jpexs.decompiler.flash.ecma.EcmaScript;
import com.jpexs.helpers.Helper;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -30,9 +33,6 @@ import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.jpexs.decompiler.flash.amf.amf0.types.ComplexObject;
import com.jpexs.decompiler.flash.amf.amf0.types.ReferenceType;
import com.jpexs.decompiler.flash.ecma.EcmaScript;
/**
* AMF0 exporter.
@@ -43,23 +43,23 @@ public class Amf0Exporter {
public static String amfMapToString(
Map<String, Object> map,
int level,
int level,
String newLine
) {
) {
List<Object> processedObjects = new ArrayList<>();
Map<Object, Integer> referenceCount = new LinkedHashMap<>();
Map<Object, String> objectAlias = new LinkedHashMap<>();
List<Object> objectList = new ArrayList<>();
for (String key: map.keySet()) {
for (String key : map.keySet()) {
Object val = map.get(key);
populateObjects(val, referenceCount, objectList, objectAlias);
}
StringBuilder sb = new StringBuilder();
sb.append("{").append(newLine);
boolean first = true;
for (String key: map.keySet()) {
for (String key : map.keySet()) {
if (!first) {
sb.append(",").append(newLine);
}
@@ -71,7 +71,7 @@ public class Amf0Exporter {
sb.append(indent(level)).append("}");
return sb.toString();
}
private static String referenceToString(String objectAlias, int level, String newLine) {
StringBuilder sb = new StringBuilder();
sb.append("{").append(newLine);
@@ -80,15 +80,15 @@ public class Amf0Exporter {
sb.append(indent(level)).append("}");
return sb.toString();
}
public static String amfToString(
Object value,
int level,
int level,
String newLine,
List<Object> processedObjects,
Map<Object, Integer> referenceCount,
Map<Object, String> objectAlias
) {
) {
String addId = "";
if (referenceCount.containsKey(value)) {
Integer refCount = referenceCount.get(value);
@@ -100,12 +100,12 @@ public class Amf0Exporter {
}
processedObjects.add(value);
}
if (value instanceof ReferenceType) {
ReferenceType rt = (ReferenceType) value;
return referenceToString("obj" + rt.referenceIndex, level, newLine);
}
if (value == BasicType.UNDEFINED) {
StringBuilder sb = new StringBuilder();
sb.append("{").append(newLine);
@@ -113,7 +113,7 @@ public class Amf0Exporter {
sb.append(indent(level)).append("}");
return sb.toString();
}
if (value instanceof Double) {
return EcmaScript.toString(value);
}
@@ -153,7 +153,7 @@ public class Amf0Exporter {
StringBuilder sb = new StringBuilder();
sb.append("{").append(newLine);
sb.append(indent(level + 1)).append("\"type\": \"Array\",").append(newLine);
sb.append(addId);
sb.append(addId);
sb.append(indent(level + 1)).append("\"values\": [").append(newLine);
boolean first = true;
for (Object val : at.values) {
@@ -174,7 +174,7 @@ public class Amf0Exporter {
StringBuilder sb = new StringBuilder();
sb.append("{").append(newLine);
sb.append(indent(level + 1)).append("\"type\": \"TypedObject\",").append(newLine);
sb.append(addId);
sb.append(addId);
sb.append(indent(level + 1)).append("\"className\": \"").append(Helper.escapeActionScriptString(tot.className)).append("\",").append(newLine);
membersToString("members", sb, tot.properties, level + 1, newLine, processedObjects, referenceCount, objectAlias);
sb.append(newLine);
@@ -194,7 +194,7 @@ public class Amf0Exporter {
sb.append(indent(level + 1)).append("\"type\": \"Date\",").append(newLine);
sb.append(addId);
sb.append(indent(level + 1)).append("\"value\": \"").append(sdf.format(dt.toDate())).append("\",").append(newLine);
sb.append(indent(level + 1)).append("\"timezone\": ").append(dt.getTimezone()).append(newLine);
sb.append(indent(level + 1)).append("\"timezone\": ").append(dt.getTimezone()).append(newLine);
sb.append(indent(level)).append("}");
return sb.toString();
}
@@ -209,7 +209,7 @@ public class Amf0Exporter {
sb.append(indent(level)).append("}");
return sb.toString();
}
return "unknown";
}
@@ -217,7 +217,7 @@ public class Amf0Exporter {
String membersLabel,
StringBuilder sb,
Map<String, Object> members,
int level,
int level,
String newLine,
List<Object> processedObjects,
Map<Object, Integer> referenceCount,
@@ -244,7 +244,7 @@ public class Amf0Exporter {
}
return na;
}
/**
* Populates all object instances and their references and generates aliases
*
@@ -268,12 +268,12 @@ public class Amf0Exporter {
if (prevRef == 0) {
if (object instanceof ComplexObject) {
objectAlias.put(object, "obj" + objectList.size());
objectList.add(object);
objectList.add(object);
List<Object> subvalues = ((ComplexObject) object).getSubValues();
for (Object o : subvalues) {
populateObjects(o, referenceCount, objectList, objectAlias);
}
}
}
}
}
}
@@ -41,7 +41,6 @@ import java.util.Map;
*/
public class Amf3Exporter {
/**
* Constructor.
*/
@@ -116,30 +115,6 @@ public class Amf3Exporter {
return amfToString(indentStr, newLine, new ArrayList<>(), 0, amfValue, refCount, objectAlias);
}
public static String amfMapToString(Map<String, Object> map, String indentStr, String newLine, int level) {
Map<Object, Integer> refCount = new HashMap<>();
List<Object> objectList = new ArrayList<>();
Map<Object, String> objectAlias = new HashMap<>();
for (Object val : map.values()) {
populateObjects(val, refCount, objectList, objectAlias);
}
List<Object> processedObjects = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append("{").append(newLine);
boolean first = true;
for (String key: map.keySet()) {
if (!first) {
sb.append(", ").append(newLine);
}
first = false;
sb.append(indent(level + 1)).append("\"").append(Helper.escapeActionScriptString(key)).append("\": ");
sb.append(amfToString(indentStr, newLine, processedObjects, level + 1, map.get(key), refCount, objectAlias));
}
sb.append(newLine);
sb.append(indent(level)).append("}");
return sb.toString();
}
/**
* Processes one level of object and converts it to string
*
@@ -157,7 +132,7 @@ public class Amf3Exporter {
if (((List<? extends Class>) Arrays.asList(Long.class, Double.class, Boolean.class)).contains(object.getClass())) {
return EcmaScript.toString(object);
}
StringBuilder ret = new StringBuilder();
if (object == BasicType.UNDEFINED) {
@@ -166,13 +141,11 @@ public class Amf3Exporter {
ret.append(indent(level)).append("}");
return ret.toString();
}
if (object instanceof BasicType) {
return object.toString();
}
Integer refCount = referenceCount.get(object);
if (refCount > 1 && processedObjects.contains(object)) {
ret.append("{").append(newLine);
@@ -365,4 +338,28 @@ public class Amf3Exporter {
return ret.toString();
}
public static String amfMapToString(Map<String, Object> map, String indentStr, String newLine, int level) {
Map<Object, Integer> refCount = new HashMap<>();
List<Object> objectList = new ArrayList<>();
Map<Object, String> objectAlias = new HashMap<>();
for (Object val : map.values()) {
populateObjects(val, refCount, objectList, objectAlias);
}
List<Object> processedObjects = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append("{").append(newLine);
boolean first = true;
for (String key : map.keySet()) {
if (!first) {
sb.append(", ").append(newLine);
}
first = false;
sb.append(indent(level + 1)).append("\"").append(Helper.escapeActionScriptString(key)).append("\": ");
sb.append(amfToString(indentStr, newLine, processedObjects, level + 1, map.get(key), refCount, objectAlias));
}
sb.append(newLine);
sb.append(indent(level)).append("}");
return sb.toString();
}
}
@@ -291,30 +291,30 @@ public class SwfFlashDevelopExporter {
if (air) {
String applicationXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> \n"
+ "<application xmlns=\"http://ns.adobe.com/air/application/" + airVersion + "\">\n"
+ " \n"
+ " <id>" + simpleNameNoSpaces + "</id> \n"
+ " <versionNumber>1.0</versionNumber> \n"
+ " <filename>" + simpleNameNoSpaces + "</filename> \n"
+ " \n"
+ " <name>" + simpleName + "</name> \n"
+ " <description></description> \n"
+ " <copyright></copyright> \n"
+ " \n"
+ " <initialWindow> \n"
+ " <title>" + simpleName + "</title> \n"
+ " <content>" + simpleNameNoSpaces + ".swf</content> \n"
+ " <systemChrome>standard</systemChrome> \n"
+ " <transparent>false</transparent> \n"
+ " <visible>true</visible> \n"
+ " <minimizable>true</minimizable> \n"
+ " <maximizable>true</maximizable> \n"
+ " <resizable>true</resizable> \n"
+ " </initialWindow> \n"
+ " \n"
+ " <!-- \n"
+ " More options:\n"
+ " http://livedocs.adobe.com/flex/3/html/File_formats_1.html#1043413\n"
+ " -->\n"
+ "\t\n"
+ "\t<id>" + simpleNameNoSpaces + "</id> \n"
+ "\t<versionNumber>1.0</versionNumber> \n"
+ "\t<filename>" + simpleNameNoSpaces + "</filename> \n"
+ "\t\n"
+ "\t<name>" + simpleName + "</name> \n"
+ "\t<description></description> \n"
+ "\t<copyright></copyright> \n"
+ "\t\n"
+ "\t<initialWindow> \n"
+ "\t\t<title>" + simpleName + "</title> \n"
+ "\t\t<content>" + simpleNameNoSpaces + ".swf</content> \n"
+ "\t\t<systemChrome>standard</systemChrome> \n"
+ "\t\t<transparent>false</transparent> \n"
+ "\t\t<visible>true</visible> \n"
+ "\t\t<minimizable>true</minimizable> \n"
+ "\t\t<maximizable>true</maximizable> \n"
+ "\t\t<resizable>true</resizable> \n"
+ "\t</initialWindow> \n"
+ "\t\n"
+ "\t<!-- \n"
+ "\tMore options:\n"
+ "\thttp://livedocs.adobe.com/flex/3/html/File_formats_1.html#1043413\n"
+ "\t-->\n"
+ "</application>";
try (FileOutputStream fos = new FileOutputStream(outFile.toPath().getParent().resolve("application.xml").toFile())) {
fos.write(Utf8Helper.getBytes(applicationXml));
@@ -62,24 +62,23 @@ public class SwfIntelliJIdeaExporter {
if (!swf.isAS3()) {
return false;
}
//Cannot export if it has something on main timeline
for (Tag t : swf.getTags()) {
if (
(t instanceof PlaceObjectTypeTag)
if ((t instanceof PlaceObjectTypeTag)
|| (t instanceof SoundStreamBlockTag)
|| (t instanceof VideoFrameTag)
|| (t instanceof StartSoundTag)
|| (t instanceof StartSound2Tag)
) {
|| (t instanceof StartSound2Tag)) {
return false;
}
}
return true;
}
/**
* Exports SWF to IntelliJ IDEA project.
*
* @param swf SWF to export
* @param outDir Output directory
* @param handler Handler for abort, retry, ignore
@@ -91,6 +90,7 @@ public class SwfIntelliJIdeaExporter {
/**
* Exports SWF to IntelliJ IDEA project.
*
* @param swf SWF to export
* @param outDir Output directory
* @param handler Handler for abort, retry, ignore
@@ -101,7 +101,7 @@ public class SwfIntelliJIdeaExporter {
if (!swf.isAS3()) {
throw new IllegalArgumentException("SWF must be AS3");
}
if (!canExportSwf(swf)) {
throw new IllegalArgumentException("SWF must not contain main timeline");
}
@@ -136,14 +136,13 @@ public class SwfIntelliJIdeaExporter {
}
String flashPlayerVersion = FlashPlayerVersion.getFlashPlayerBySwfVersion(swf.version);
String imlData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<module type=\"Flex\" version=\"4\">\n"
+ " <component name=\"FlexBuildConfigurationManager\" active=\"" + simpleName + "\">\n"
+ " <configurations>\n"
+ " <configuration name=\"" + simpleName + "\" pure-as=\"true\" main-class=\"" + documentClass + "\" output-file=\"" + simpleName + ".swf\" output-folder=\"$MODULE_DIR$/out/production/" + simpleName + "\">\n"
+ " <dependencies target-player=\"" + flashPlayerVersion +"\">\n"
+ " <dependencies target-player=\"" + flashPlayerVersion + "\">\n"
+ " <sdk name=\"flex\" />\n"
+ " </dependencies>\n"
+ " <compiler-options>\n"
@@ -120,296 +120,296 @@ public class SwfVsCodeExporter {
String[] airVersions = airVersion.split("\\.");
project = "{\n"
+ " \"config\": \"air\",\n"
+ " \"compilerOptions\": {\n"
+ " \"source-path\": [\n"
+ " \"src\"\n"
+ " ],\n"
+ " \"library-path\": [\n"
+ " \"libs\"\n"
+ " ],\n"
+ " \"output\": \"bin/"+simpleNameNoSpaces+".swf\",\n"
+ " \"default-background-color\": \"" + (bgColorTag == null ? "#FFFFFF" : bgColorTag.backgroundColor.toHexRGB()) + "\",\n"
+ " \"default-frame-rate\": " + doubleToString(swf.frameRate) + ",\n"
+ " \"default-size\": {\n"
+ " \"width\": " + doubleToString(swf.displayRect.getWidth() / SWF.unitDivisor) + ",\n"
+ " \"height\": " + doubleToString(swf.displayRect.getWidth() / SWF.unitDivisor) + "\n"
+ " },\n"
+ " \"swf-version\": " + swf.version + "\n"
+ "\t\"config\": \"air\",\n"
+ "\t\"compilerOptions\": {\n"
+ "\t\t\"source-path\": [\n"
+ "\t\t\t\"src\"\n"
+ "\t\t],\n"
+ "\t\t\"library-path\": [\n"
+ "\t\t\t\"libs\"\n"
+ "\t\t],\n"
+ "\t\t\"output\": \"bin/" + simpleNameNoSpaces + ".swf\",\n"
+ "\t\t\"default-background-color\": \"" + (bgColorTag == null ? "#FFFFFF" : bgColorTag.backgroundColor.toHexRGB()) + "\",\n"
+ "\t\t\"default-frame-rate\": " + doubleToString(swf.frameRate) + ",\n"
+ "\t\t\"default-size\": {\n"
+ "\t\t\t\"width\": " + doubleToString(swf.displayRect.getWidth() / SWF.unitDivisor) + ",\n"
+ "\t\t\t\"height\": " + doubleToString(swf.displayRect.getWidth() / SWF.unitDivisor) + "\n"
+ "\t\t},\n"
+ "\t\t\"swf-version\": " + swf.version + "\n"
//
+ " },\n"
+ " \"application\": \"src/"+simpleNameNoSpaces+"-app.xml\",\n"
+ " \"mainClass\": \"" + documentClass +"\"\n"
+ "\t},\n"
+ "\t\"application\": \"src/" + simpleNameNoSpaces + "-app.xml\",\n"
+ "\t\"mainClass\": \"" + documentClass + "\"\n"
+ "}";
try (FileOutputStream fos = new FileOutputStream(outDir.toPath().resolve("asconfig.json").toFile())) {
fos.write(Utf8Helper.getBytes(project));
}
File vscodeDir = outDir.toPath().resolve(".vscode").toFile();
vscodeDir.mkdirs();
String launch = "{\n" +
" \"version\": \"0.2.0\",\n" +
" \"configurations\": [\n" +
" {\n" +
" \"type\": \"swf\",\n" +
" \"request\": \"launch\",\n" +
" \"name\": \"Launch SWF\"\n" +
" }\n" +
" ]\n" +
"}";
String launch = "{\n"
+ "\t\"version\": \"0.2.0\",\n"
+ "\t\"configurations\": [\n"
+ "\t\t{\n"
+ "\t\t\t\"type\": \"swf\",\n"
+ "\t\t\t\"request\": \"launch\",\n"
+ "\t\t\t\"name\": \"Launch SWF\"\n"
+ "\t\t}\n"
+ "\t]\n"
+ "}";
try (FileOutputStream fos = new FileOutputStream(vscodeDir.toPath().resolve("launch.json").toFile())) {
fos.write(Utf8Helper.getBytes(launch));
}
String settings = "{\n" +
" \"as3mxml.sdk.framework\": \"c:\\\\flex\"\n" +
"}";
String settings = "{\n"
+ "\t\"as3mxml.sdk.framework\": \"c:\\\\flex\"\n"
+ "}";
try (FileOutputStream fos = new FileOutputStream(vscodeDir.toPath().resolve("settings.json").toFile())) {
fos.write(Utf8Helper.getBytes(settings));
}
String app = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
"<application xmlns=\"http://ns.adobe.com/air/application/3.1\">\n" +
"\n" +
"<!-- Adobe AIR Application Descriptor File Template.\n" +
"\n" +
" Specifies parameters for identifying, installing, and launching AIR applications.\n" +
"\n" +
" xmlns - The Adobe AIR namespace: http://ns.adobe.com/air/application/3.1\n" +
" The last segment of the namespace specifies the version \n" +
" of the AIR runtime required for this application to run.\n" +
" \n" +
" minimumPatchLevel - The minimum patch level of the AIR runtime required to run \n" +
" the application. Optional.\n" +
"-->\n" +
"\n" +
" <!-- A universally unique application identifier. Must be unique across all AIR applications.\n" +
" Using a reverse DNS-style name as the id is recommended. (Eg. com.example.ExampleApplication.) Required. -->\n" +
" <id>test-flex</id>\n" +
"\n" +
" <!-- Used as the filename for the application. Required. -->\n" +
" <filename>"+simpleNameNoSpaces+"</filename>\n" +
"\n" +
" <!-- The name that is displayed in the AIR application installer. \n" +
" May have multiple values for each language. See samples or xsd schema file. Optional. -->\n" +
" <name></name>\n" +
" \n" +
" <!-- A string value of the format <0-999>.<0-999>.<0-999> that represents application version which can be used to check for application upgrade. \n" +
" Values can also be 1-part or 2-part. It is not necessary to have a 3-part value.\n" +
" An updated version of application must have a versionNumber value greater than the previous version. Required for namespace >= 2.5 . -->\n" +
" <versionNumber>1.0.0</versionNumber>\n" +
" \n" +
" <!-- A string value (such as \"v1\", \"2.5\", or \"Alpha 1\") that represents the version of the application, as it should be shown to users. Optional. -->\n" +
" <!-- <versionLabel></versionLabel> -->\n" +
"\n" +
" <!-- Description, displayed in the AIR application installer.\n" +
" May have multiple values for each language. See samples or xsd schema file. Optional. -->\n" +
" <!-- <description></description> -->\n" +
"\n" +
" <!-- Copyright information. Optional -->\n" +
" <!-- <copyright></copyright> -->\n" +
"\n" +
" <!-- Publisher ID. Used if you're updating an application created prior to 1.5.3 -->\n" +
" <!-- <publisherID></publisherID> -->\n" +
"\n" +
" <!-- Settings for the application's initial window. Required. -->\n" +
" <initialWindow>\n" +
" <!-- The main SWF or HTML file of the application. Required. -->\n" +
" <!-- Note: In Flash Builder, the SWF reference is set automatically. -->\n" +
" <content>" + simpleNameNoSpaces + ".swf</content>\n" +
" \n" +
" <!-- The title of the main window. Optional. -->\n" +
" <!-- <title></title> -->\n" +
"\n" +
" <!-- The type of system chrome to use (either \"standard\" or \"none\"). Optional. Default standard. -->\n" +
" <!-- <systemChrome></systemChrome> -->\n" +
"\n" +
" <!-- Whether the window is transparent. Only applicable when systemChrome is none. Optional. Default false. -->\n" +
" <!-- <transparent></transparent> -->\n" +
"\n" +
" <!-- Whether the window is initially visible. Optional. Default false. -->\n" +
" <visible>true</visible>\n" +
"\n" +
" <!-- Whether the user can minimize the window. Optional. Default true. -->\n" +
" <!-- <minimizable></minimizable> -->\n" +
"\n" +
" <!-- Whether the user can maximize the window. Optional. Default true. -->\n" +
" <!-- <maximizable></maximizable> -->\n" +
"\n" +
" <!-- Whether the user can resize the window. Optional. Default true. -->\n" +
" <!-- <resizable></resizable> -->\n" +
"\n" +
" <!-- The window's initial width in pixels. Optional. -->\n" +
" <!-- <width></width> -->\n" +
"\n" +
" <!-- The window's initial height in pixels. Optional. -->\n" +
" <!-- <height></height> -->\n" +
"\n" +
" <!-- The window's initial x position. Optional. -->\n" +
" <!-- <x></x> -->\n" +
"\n" +
" <!-- The window's initial y position. Optional. -->\n" +
" <!-- <y></y> -->\n" +
"\n" +
" <!-- The window's minimum size, specified as a width/height pair in pixels, such as \"400 200\". Optional. -->\n" +
" <!-- <minSize></minSize> -->\n" +
"\n" +
" <!-- The window's initial maximum size, specified as a width/height pair in pixels, such as \"1600 1200\". Optional. -->\n" +
" <!-- <maxSize></maxSize> -->\n" +
"\n" +
" <!-- The initial aspect ratio of the app when launched (either \"portrait\" or \"landscape\"). Optional. Mobile only. Default is the natural orientation of the device -->\n" +
"\n" +
" <!-- <aspectRatio></aspectRatio> -->\n" +
"\n" +
" <!-- Whether the app will begin auto-orienting on launch. Optional. Mobile only. Default false -->\n" +
"\n" +
" <!-- <autoOrients></autoOrients> -->\n" +
"\n" +
" <!-- Whether the app launches in full screen. Optional. Mobile only. Default false -->\n" +
"\n" +
" <!-- <fullScreen></fullScreen> -->\n" +
"\n" +
" <!-- The render mode for the app (either auto, cpu, gpu, or direct). Optional. Default auto -->\n" +
"\n" +
" <!-- <renderMode></renderMode> -->\n" +
"\n" +
" <!-- Whether or not to pan when a soft keyboard is raised or lowered (either \"pan\" or \"none\"). Optional. Defaults \"pan.\" -->\n" +
" <!-- <softKeyboardBehavior></softKeyboardBehavior> -->\n" +
" </initialWindow>\n" +
"\n" +
" <!-- We recommend omitting the supportedProfiles element, -->\n" +
" <!-- which in turn permits your application to be deployed to all -->\n" +
" <!-- devices supported by AIR. If you wish to restrict deployment -->\n" +
" <!-- (i.e., to only mobile devices) then add this element and list -->\n" +
" <!-- only the profiles which your application does support. -->\n" +
" <!-- <supportedProfiles>desktop extendedDesktop mobileDevice extendedMobileDevice</supportedProfiles> -->\n" +
"\n" +
" <!-- The subpath of the standard default installation location to use. Optional. -->\n" +
" <!-- <installFolder></installFolder> -->\n" +
"\n" +
" <!-- The subpath of the Programs menu to use. (Ignored on operating systems without a Programs menu.) Optional. -->\n" +
" <!-- <programMenuFolder></programMenuFolder> -->\n" +
"\n" +
" <!-- The icon the system uses for the application. For at least one resolution,\n" +
" specify the path to a PNG file included in the AIR package. Optional. -->\n" +
" <!-- <icon>\n" +
" <image16x16></image16x16>\n" +
" <image32x32></image32x32>\n" +
" <image36x36></image36x36>\n" +
" <image48x48></image48x48>\n" +
" <image57x57></image57x57>\n" +
" <image72x72></image72x72>\n" +
" <image114x114></image114x114>\n" +
" <image128x128></image128x128>\n" +
" </icon> -->\n" +
"\n" +
" <!-- Whether the application handles the update when a user double-clicks an update version\n" +
" of the AIR file (true), or the default AIR application installer handles the update (false).\n" +
" Optional. Default false. -->\n" +
" <!-- <customUpdateUI></customUpdateUI> -->\n" +
" \n" +
" <!-- Whether the application can be launched when the user clicks a link in a web browser.\n" +
" Optional. Default false. -->\n" +
" <!-- <allowBrowserInvocation></allowBrowserInvocation> -->\n" +
"\n" +
" <!-- Listing of file types for which the application can register. Optional. -->\n" +
" <!-- <fileTypes> -->\n" +
"\n" +
" <!-- Defines one file type. Optional. -->\n" +
" <!-- <fileType> -->\n" +
"\n" +
" <!-- The name that the system displays for the registered file type. Required. -->\n" +
" <!-- <name></name> -->\n" +
"\n" +
" <!-- The extension to register. Required. -->\n" +
" <!-- <extension></extension> -->\n" +
" \n" +
" <!-- The description of the file type. Optional. -->\n" +
" <!-- <description></description> -->\n" +
" \n" +
" <!-- The MIME content type. -->\n" +
" <!-- <contentType></contentType> -->\n" +
" \n" +
" <!-- The icon to display for the file type. Optional. -->\n" +
" <!-- <icon>\n" +
" <image16x16></image16x16>\n" +
" <image32x32></image32x32>\n" +
" <image48x48></image48x48>\n" +
" <image128x128></image128x128>\n" +
" </icon> -->\n" +
" \n" +
" <!-- </fileType> -->\n" +
" <!-- </fileTypes> -->\n" +
"\n" +
" <!-- iOS specific capabilities -->\n" +
" <!-- <iPhone> -->\n" +
" <!-- A list of plist key/value pairs to be added to the application Info.plist -->\n" +
" <!-- <InfoAdditions>\n" +
" <![CDATA[\n" +
" <key>UIDeviceFamily</key>\n" +
" <array>\n" +
" <string>1</string>\n" +
" <string>2</string>\n" +
" </array>\n" +
" <key>UIStatusBarStyle</key>\n" +
" <string>UIStatusBarStyleBlackOpaque</string>\n" +
" <key>UIRequiresPersistentWiFi</key>\n" +
" <string>YES</string>\n" +
" ]]>\n" +
" </InfoAdditions> -->\n" +
" <!-- A list of plist key/value pairs to be added to the application Entitlements.plist -->\n" +
" <!-- <Entitlements>\n" +
" <![CDATA[\n" +
" <key>keychain-access-groups</key>\n" +
" <array>\n" +
" <string></string>\n" +
" <string></string>\n" +
" </array>\n" +
" ]]>\n" +
" </Entitlements> -->\n" +
" <!-- Display Resolution for the app (either \"standard\" or \"high\"). Optional. Default \"standard\" -->\n" +
" <!-- <requestedDisplayResolution></requestedDisplayResolution> -->\n" +
" <!-- </iPhone> -->\n" +
"\n" +
" <!-- Specify Android specific tags that get passed to AndroidManifest.xml file. -->\n" +
" <!--<android> -->\n" +
" <!-- <manifestAdditions>\n" +
" <![CDATA[\n" +
" <manifest android:installLocation=\"auto\">\n" +
" <uses-permission android:name=\"android.permission.INTERNET\"/>\n" +
" <uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n" +
" <uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>\n" +
" <uses-feature android:required=\"true\" android:name=\"android.hardware.touchscreen.multitouch\"/>\n" +
" <application android:enabled=\"true\">\n" +
" <activity android:excludeFromRecents=\"false\">\n" +
" <intent-filter>\n" +
" <action android:name=\"android.intent.action.MAIN\"/>\n" +
" <category android:name=\"android.intent.category.LAUNCHER\"/>\n" +
" </intent-filter>\n" +
" </activity>\n" +
" </application>\n" +
" </manifest>\n" +
" ]]>\n" +
" </manifestAdditions> -->\n" +
" <!-- Color depth for the app (either \"32bit\" or \"16bit\"). Optional. Default 16bit before namespace 3.0, 32bit after -->\n" +
" <!-- <colorDepth></colorDepth> -->\n" +
" <!-- </android> -->\n" +
" <!-- End of the schema for adding the android specific tags in AndroidManifest.xml file -->\n" +
"\n" +
"</application>";
String app = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"
+ "<application xmlns=\"http://ns.adobe.com/air/application/3.1\">\n"
+ "\n"
+ "<!-- Adobe AIR Application Descriptor File Template.\n"
+ "\n"
+ "\tSpecifies parameters for identifying, installing, and launching AIR applications.\n"
+ "\n"
+ "\txmlns - The Adobe AIR namespace: http://ns.adobe.com/air/application/3.1\n"
+ "\t\t\tThe last segment of the namespace specifies the version \n"
+ "\t\t\tof the AIR runtime required for this application to run.\n"
+ "\t\t\t\n"
+ "\tminimumPatchLevel - The minimum patch level of the AIR runtime required to run \n"
+ "\t\t\tthe application. Optional.\n"
+ "-->\n"
+ "\n"
+ "\t<!-- A universally unique application identifier. Must be unique across all AIR applications.\n"
+ "\tUsing a reverse DNS-style name as the id is recommended. (Eg. com.example.ExampleApplication.) Required. -->\n"
+ "\t<id>test-flex</id>\n"
+ "\n"
+ "\t<!-- Used as the filename for the application. Required. -->\n"
+ "\t<filename>" + simpleNameNoSpaces + "</filename>\n"
+ "\n"
+ "\t<!-- The name that is displayed in the AIR application installer. \n"
+ "\tMay have multiple values for each language. See samples or xsd schema file. Optional. -->\n"
+ "\t<name></name>\n"
+ "\t\n"
+ "\t<!-- A string value of the format <0-999>.<0-999>.<0-999> that represents application version which can be used to check for application upgrade. \n"
+ "\tValues can also be 1-part or 2-part. It is not necessary to have a 3-part value.\n"
+ "\tAn updated version of application must have a versionNumber value greater than the previous version. Required for namespace >= 2.5 . -->\n"
+ "\t<versionNumber>1.0.0</versionNumber>\n"
+ "\t\t \n"
+ "\t<!-- A string value (such as \"v1\", \"2.5\", or \"Alpha 1\") that represents the version of the application, as it should be shown to users. Optional. -->\n"
+ "\t<!-- <versionLabel></versionLabel> -->\n"
+ "\n"
+ "\t<!-- Description, displayed in the AIR application installer.\n"
+ "\tMay have multiple values for each language. See samples or xsd schema file. Optional. -->\n"
+ "\t<!-- <description></description> -->\n"
+ "\n"
+ "\t<!-- Copyright information. Optional -->\n"
+ "\t<!-- <copyright></copyright> -->\n"
+ "\n"
+ "\t<!-- Publisher ID. Used if you're updating an application created prior to 1.5.3 -->\n"
+ "\t<!-- <publisherID></publisherID> -->\n"
+ "\n"
+ "\t<!-- Settings for the application's initial window. Required. -->\n"
+ "\t<initialWindow>\n"
+ "\t\t<!-- The main SWF or HTML file of the application. Required. -->\n"
+ "\t\t<!-- Note: In Flash Builder, the SWF reference is set automatically. -->\n"
+ "\t\t<content>" + simpleNameNoSpaces + ".swf</content>\n"
+ "\t\t\n"
+ "\t\t<!-- The title of the main window. Optional. -->\n"
+ "\t\t<!-- <title></title> -->\n"
+ "\n"
+ "\t\t<!-- The type of system chrome to use (either \"standard\" or \"none\"). Optional. Default standard. -->\n"
+ "\t\t<!-- <systemChrome></systemChrome> -->\n"
+ "\n"
+ "\t\t<!-- Whether the window is transparent. Only applicable when systemChrome is none. Optional. Default false. -->\n"
+ "\t\t<!-- <transparent></transparent> -->\n"
+ "\n"
+ "\t\t<!-- Whether the window is initially visible. Optional. Default false. -->\n"
+ "\t\t<visible>true</visible>\n"
+ "\n"
+ "\t\t<!-- Whether the user can minimize the window. Optional. Default true. -->\n"
+ "\t\t<!-- <minimizable></minimizable> -->\n"
+ "\n"
+ "\t\t<!-- Whether the user can maximize the window. Optional. Default true. -->\n"
+ "\t\t<!-- <maximizable></maximizable> -->\n"
+ "\n"
+ "\t\t<!-- Whether the user can resize the window. Optional. Default true. -->\n"
+ "\t\t<!-- <resizable></resizable> -->\n"
+ "\n"
+ "\t\t<!-- The window's initial width in pixels. Optional. -->\n"
+ "\t\t<!-- <width></width> -->\n"
+ "\n"
+ "\t\t<!-- The window's initial height in pixels. Optional. -->\n"
+ "\t\t<!-- <height></height> -->\n"
+ "\n"
+ "\t\t<!-- The window's initial x position. Optional. -->\n"
+ "\t\t<!-- <x></x> -->\n"
+ "\n"
+ "\t\t<!-- The window's initial y position. Optional. -->\n"
+ "\t\t<!-- <y></y> -->\n"
+ "\n"
+ "\t\t<!-- The window's minimum size, specified as a width/height pair in pixels, such as \"400 200\". Optional. -->\n"
+ "\t\t<!-- <minSize></minSize> -->\n"
+ "\n"
+ "\t\t<!-- The window's initial maximum size, specified as a width/height pair in pixels, such as \"1600 1200\". Optional. -->\n"
+ "\t\t<!-- <maxSize></maxSize> -->\n"
+ "\n"
+ " <!-- The initial aspect ratio of the app when launched (either \"portrait\" or \"landscape\"). Optional. Mobile only. Default is the natural orientation of the device -->\n"
+ "\n"
+ " <!-- <aspectRatio></aspectRatio> -->\n"
+ "\n"
+ " <!-- Whether the app will begin auto-orienting on launch. Optional. Mobile only. Default false -->\n"
+ "\n"
+ " <!-- <autoOrients></autoOrients> -->\n"
+ "\n"
+ " <!-- Whether the app launches in full screen. Optional. Mobile only. Default false -->\n"
+ "\n"
+ " <!-- <fullScreen></fullScreen> -->\n"
+ "\n"
+ " <!-- The render mode for the app (either auto, cpu, gpu, or direct). Optional. Default auto -->\n"
+ "\n"
+ " <!-- <renderMode></renderMode> -->\n"
+ "\n"
+ "\t\t<!-- Whether or not to pan when a soft keyboard is raised or lowered (either \"pan\" or \"none\"). Optional. Defaults \"pan.\" -->\n"
+ "\t\t<!-- <softKeyboardBehavior></softKeyboardBehavior> -->\n"
+ "\t</initialWindow>\n"
+ "\n"
+ "\t<!-- We recommend omitting the supportedProfiles element, -->\n"
+ "\t<!-- which in turn permits your application to be deployed to all -->\n"
+ "\t<!-- devices supported by AIR. If you wish to restrict deployment -->\n"
+ "\t<!-- (i.e., to only mobile devices) then add this element and list -->\n"
+ "\t<!-- only the profiles which your application does support. -->\n"
+ "\t<!-- <supportedProfiles>desktop extendedDesktop mobileDevice extendedMobileDevice</supportedProfiles> -->\n"
+ "\n"
+ "\t<!-- The subpath of the standard default installation location to use. Optional. -->\n"
+ "\t<!-- <installFolder></installFolder> -->\n"
+ "\n"
+ "\t<!-- The subpath of the Programs menu to use. (Ignored on operating systems without a Programs menu.) Optional. -->\n"
+ "\t<!-- <programMenuFolder></programMenuFolder> -->\n"
+ "\n"
+ "\t<!-- The icon the system uses for the application. For at least one resolution,\n"
+ "\tspecify the path to a PNG file included in the AIR package. Optional. -->\n"
+ "\t<!-- <icon>\n"
+ "\t\t<image16x16></image16x16>\n"
+ "\t\t<image32x32></image32x32>\n"
+ "\t\t<image36x36></image36x36>\n"
+ "\t\t<image48x48></image48x48>\n"
+ "\t\t<image57x57></image57x57>\n"
+ "\t\t<image72x72></image72x72>\n"
+ "\t\t<image114x114></image114x114>\n"
+ "\t\t<image128x128></image128x128>\n"
+ "\t</icon> -->\n"
+ "\n"
+ "\t<!-- Whether the application handles the update when a user double-clicks an update version\n"
+ "\tof the AIR file (true), or the default AIR application installer handles the update (false).\n"
+ "\tOptional. Default false. -->\n"
+ "\t<!-- <customUpdateUI></customUpdateUI> -->\n"
+ "\t\n"
+ "\t<!-- Whether the application can be launched when the user clicks a link in a web browser.\n"
+ "\tOptional. Default false. -->\n"
+ "\t<!-- <allowBrowserInvocation></allowBrowserInvocation> -->\n"
+ "\n"
+ "\t<!-- Listing of file types for which the application can register. Optional. -->\n"
+ "\t<!-- <fileTypes> -->\n"
+ "\n"
+ "\t\t<!-- Defines one file type. Optional. -->\n"
+ "\t\t<!-- <fileType> -->\n"
+ "\n"
+ "\t\t\t<!-- The name that the system displays for the registered file type. Required. -->\n"
+ "\t\t\t<!-- <name></name> -->\n"
+ "\n"
+ "\t\t\t<!-- The extension to register. Required. -->\n"
+ "\t\t\t<!-- <extension></extension> -->\n"
+ "\t\t\t\n"
+ "\t\t\t<!-- The description of the file type. Optional. -->\n"
+ "\t\t\t<!-- <description></description> -->\n"
+ "\t\t\t\n"
+ "\t\t\t<!-- The MIME content type. -->\n"
+ "\t\t\t<!-- <contentType></contentType> -->\n"
+ "\t\t\t\n"
+ "\t\t\t<!-- The icon to display for the file type. Optional. -->\n"
+ "\t\t\t<!-- <icon>\n"
+ "\t\t\t\t<image16x16></image16x16>\n"
+ "\t\t\t\t<image32x32></image32x32>\n"
+ "\t\t\t\t<image48x48></image48x48>\n"
+ "\t\t\t\t<image128x128></image128x128>\n"
+ "\t\t\t</icon> -->\n"
+ "\t\t\t\n"
+ "\t\t<!-- </fileType> -->\n"
+ "\t<!-- </fileTypes> -->\n"
+ "\n"
+ " <!-- iOS specific capabilities -->\n"
+ "\t<!-- <iPhone> -->\n"
+ "\t\t<!-- A list of plist key/value pairs to be added to the application Info.plist -->\n"
+ "\t\t<!-- <InfoAdditions>\n"
+ " <![CDATA[\n"
+ " <key>UIDeviceFamily</key>\n"
+ " <array>\n"
+ " <string>1</string>\n"
+ " <string>2</string>\n"
+ " </array>\n"
+ " <key>UIStatusBarStyle</key>\n"
+ " <string>UIStatusBarStyleBlackOpaque</string>\n"
+ " <key>UIRequiresPersistentWiFi</key>\n"
+ " <string>YES</string>\n"
+ " ]]>\n"
+ " </InfoAdditions> -->\n"
+ " <!-- A list of plist key/value pairs to be added to the application Entitlements.plist -->\n"
+ "\t\t<!-- <Entitlements>\n"
+ " <![CDATA[\n"
+ " <key>keychain-access-groups</key>\n"
+ " <array>\n"
+ " <string></string>\n"
+ " <string></string>\n"
+ " </array>\n"
+ " ]]>\n"
+ " </Entitlements> -->\n"
+ "\t<!-- Display Resolution for the app (either \"standard\" or \"high\"). Optional. Default \"standard\" -->\n"
+ "\t<!-- <requestedDisplayResolution></requestedDisplayResolution> -->\n"
+ "\t<!-- </iPhone> -->\n"
+ "\n"
+ "\t<!-- Specify Android specific tags that get passed to AndroidManifest.xml file. -->\n"
+ " <!--<android> -->\n"
+ " <!--\t<manifestAdditions>\n"
+ "\t\t<![CDATA[\n"
+ "\t\t\t<manifest android:installLocation=\"auto\">\n"
+ "\t\t\t\t<uses-permission android:name=\"android.permission.INTERNET\"/>\n"
+ "\t\t\t\t<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>\n"
+ "\t\t\t\t<uses-permission android:name=\"android.permission.ACCESS_FINE_LOCATION\"/>\n"
+ "\t\t\t\t<uses-feature android:required=\"true\" android:name=\"android.hardware.touchscreen.multitouch\"/>\n"
+ "\t\t\t\t<application android:enabled=\"true\">\n"
+ "\t\t\t\t\t<activity android:excludeFromRecents=\"false\">\n"
+ "\t\t\t\t\t\t<intent-filter>\n"
+ "\t\t\t\t\t\t\t<action android:name=\"android.intent.action.MAIN\"/>\n"
+ "\t\t\t\t\t\t\t<category android:name=\"android.intent.category.LAUNCHER\"/>\n"
+ "\t\t\t\t\t\t</intent-filter>\n"
+ "\t\t\t\t\t</activity>\n"
+ "\t\t\t\t</application>\n"
+ " </manifest>\n"
+ "\t\t]]>\n"
+ " </manifestAdditions> -->\n"
+ "\t <!-- Color depth for the app (either \"32bit\" or \"16bit\"). Optional. Default 16bit before namespace 3.0, 32bit after -->\n"
+ " <!-- <colorDepth></colorDepth> -->\n"
+ " <!-- </android> -->\n"
+ "\t<!-- End of the schema for adding the android specific tags in AndroidManifest.xml file -->\n"
+ "\n"
+ "</application>";
File srcDir = outDir.toPath().resolve("src").toFile();
srcDir.mkdirs();
try (FileOutputStream fos = new FileOutputStream(srcDir.toPath().resolve(simpleNameNoSpaces + "-app.xml").toFile())) {
fos.write(Utf8Helper.getBytes(app));
}
File libsDir = outDir.toPath().resolve("libs").toFile();
libsDir.mkdirs();
boolean parallel = Configuration.parallelSpeedUp.get();
ScriptExportSettings scriptExportSettings = new ScriptExportSettings(ScriptExportMode.AS, false, false, true, false, false, "/_assets/", Configuration.linkAllClasses.get(), false);
swf.exportActionScript(handler, srcDir.getAbsolutePath(), scriptExportSettings, parallel, eventListener);
@@ -46,23 +46,24 @@ public class HarmanBinaryDataEncrypt {
/**
* Encrypts data.
*
* @param data Data to encrypt
* @param key Key
* @return Encrypted data
*/
public static byte[] encrypt(byte[] data, String key) {
byte[] customKey = null;
if (key != null) {
customKey = new byte[16];
int keyLen = key.length();
for(int i = 0; i < 16; ++i) {
customKey[i] = (byte)key.charAt(i % keyLen);
for (int i = 0; i < 16; ++i) {
customKey[i] = (byte) key.charAt(i % keyLen);
}
}
byte[] result;
try {
SecureRandom random = new SecureRandom();
@@ -165,6 +166,7 @@ public class HarmanBinaryDataEncrypt {
/**
* Decrypts data.
*
* @param data Encrypted data
* @param key
* @return Decrypted data
@@ -173,18 +175,18 @@ public class HarmanBinaryDataEncrypt {
if (data.length < 32) {
return null;
}
byte[] customKey = null;
if (key != null) {
customKey = new byte[16];
int keyLen = key.length();
for(int i = 0; i < 16; ++i) {
customKey[i] = (byte)key.charAt(i % keyLen);
for (int i = 0; i < 16; ++i) {
customKey[i] = (byte) key.charAt(i % keyLen);
}
}
long encryptedLen = data.length;
long encryptedLenXorHash = unpack(data, 0);
long decryptedLenXorRandom1 = unpack(data, 4);
@@ -224,6 +226,7 @@ public class HarmanBinaryDataEncrypt {
/**
* Test encryption/decryption.
*
* @param args Command line arguments
* @throws IOException On I/O error
*/
@@ -42,7 +42,6 @@ import javax.crypto.spec.SecretKeySpec;
*/
public class HarmanSwfEncrypt {
private static final String GLOBAL_KEY = "Adobe AIR SDK (c) 2021 HARMAN Internation Industries Incorporated";
/**
@@ -107,6 +106,7 @@ public class HarmanSwfEncrypt {
/**
* Encrypts data.
*
* @param data Data to encrypt
* @return Encrypted data
* @throws IOException On I/O error
@@ -123,6 +123,7 @@ public class HarmanSwfEncrypt {
/**
* Encrypts data.
*
* @param is Data to encrypt
* @return Encrypted data
* @throws IOException On I/O error
@@ -142,6 +143,7 @@ public class HarmanSwfEncrypt {
/**
* Encrypts data.
*
* @param is Data to encrypt
* @param header Header
* @return Encrypted data
@@ -216,6 +218,7 @@ public class HarmanSwfEncrypt {
/**
* Decrypts data.
*
* @param data Data to decrypt
* @return Decrypted data
* @throws IOException On I/O error
@@ -232,6 +235,7 @@ public class HarmanSwfEncrypt {
/**
* Decrypts data.
*
* @param is Data to decrypt
* @return Decrypted data
* @throws IOException On I/O error
@@ -255,6 +259,7 @@ public class HarmanSwfEncrypt {
/**
* Decrypts data.
*
* @param is Data to decrypt
* @param header Header
* @return Decrypted data
@@ -324,6 +329,7 @@ public class HarmanSwfEncrypt {
/**
* Encrypts/decrypts data.
*
* @param args Command line arguments
* @throws Exception On error
*/
@@ -23,9 +23,9 @@ import com.jpexs.decompiler.flash.amf.amf0.types.EcmaArrayType;
import com.jpexs.decompiler.flash.amf.amf0.types.ObjectType;
import com.jpexs.decompiler.flash.amf.amf0.types.TypedObjectType;
import com.jpexs.decompiler.flash.amf.amf0.types.XmlDocumentType;
import com.jpexs.decompiler.flash.importers.amf.ParsedSymbol;
import com.jpexs.decompiler.flash.importers.amf.AmfLexer;
import com.jpexs.decompiler.flash.importers.amf.AmfParseException;
import com.jpexs.decompiler.flash.importers.amf.ParsedSymbol;
import com.jpexs.decompiler.flash.importers.amf.SymbolType;
import java.io.IOException;
import java.io.StringReader;
@@ -16,9 +16,6 @@
*/
package com.jpexs.decompiler.flash.importers.amf.amf3;
import com.jpexs.decompiler.flash.importers.amf.AmfLexer;
import com.jpexs.decompiler.flash.importers.amf.AmfParseException;
import com.jpexs.decompiler.flash.importers.amf.SymbolType;
import com.jpexs.decompiler.flash.amf.amf3.ListMap;
import com.jpexs.decompiler.flash.amf.amf3.Traits;
import com.jpexs.decompiler.flash.amf.amf3.types.ArrayType;
@@ -33,7 +30,10 @@ import com.jpexs.decompiler.flash.amf.amf3.types.VectorObjectType;
import com.jpexs.decompiler.flash.amf.amf3.types.VectorUIntType;
import com.jpexs.decompiler.flash.amf.amf3.types.XmlDocType;
import com.jpexs.decompiler.flash.amf.amf3.types.XmlType;
import com.jpexs.decompiler.flash.importers.amf.AmfLexer;
import com.jpexs.decompiler.flash.importers.amf.AmfParseException;
import com.jpexs.decompiler.flash.importers.amf.ParsedSymbol;
import com.jpexs.decompiler.flash.importers.amf.SymbolType;
import com.jpexs.helpers.Helper;
import java.io.IOException;
import java.io.StringReader;
@@ -451,7 +451,7 @@ public class Amf3Importer {
JsObject entryJso = (JsObject) entry;
entryJso.resolve("key", objectTable, true);
entryJso.resolve("value", objectTable, true);
Object key = entryJso.get("key");
Object value = entryJso.get("value");
entries.put(key, value);
@@ -484,8 +484,8 @@ public class Amf3Importer {
}
}
return resultObject;
}
}
private Map<String, Object> map(Map<String, Object> objectTable) throws IOException, AmfParseException {
Map<String, Object> result = new LinkedHashMap<>();
expectedType(SymbolType.CURLY_OPEN);
@@ -499,12 +499,12 @@ public class Amf3Importer {
expectedType(SymbolType.COLON);
result.put(key, value(objectTable));
s = lex();
} while(s.type == SymbolType.COMMA);
} while (s.type == SymbolType.COMMA);
expected(s, lexer.yyline(), SymbolType.CURLY_CLOSE);
return result;
}
private Object value(Map<String, Object> objectTable) throws IOException, AmfParseException {
ParsedSymbol s = lex();
switch (s.type) {
@@ -613,7 +613,7 @@ public class Amf3Importer {
* @param val AMF3 string
* @return Object
* @throws IOException On I/O error
* @throws AmfParseException On parse error
* @throws AmfParseException On parse error
*/
public Object stringToAmf(String val) throws IOException, AmfParseException {
lexer = new AmfLexer(new StringReader(val));
@@ -624,30 +624,30 @@ public class Amf3Importer {
Object resultNoRef = replaceReferences(resultResolved, objectsTable);
return resultNoRef;
}
/**
* Convert AMF3 map string to object
*
* @param val AMF3 string
* @return Object
* @throws IOException On I/O error
* @throws AmfParseException On parse error
* @throws AmfParseException On parse error
*/
public Map<String, Object> stringToAmfMap(String val) throws IOException, AmfParseException {
lexer = new AmfLexer(new StringReader(val));
Map<String, Object> objectsTable = new LinkedHashMap<>();
List<ReferencedObjectType> references = new ArrayList<>();
Map<String, Object> result = map(objectsTable);
for (String key: result.keySet()) {
for (String key : result.keySet()) {
Object resultResolved = resolveObjects(result.get(key), objectsTable, true);
result.put(key, resultResolved);
}
for (String key: result.keySet()) {
for (String key : result.keySet()) {
Object resultNoRef = replaceReferences(result.get(key), objectsTable);
result.put(key, resultNoRef);
}
return result;
}
}
@@ -41,7 +41,7 @@ import java.util.logging.Logger;
public class LsoTag extends Tag {
public static final int ID = 2;
public String fileName;
public int amfVersion;
public Map<String, Object> amfValues = new LinkedHashMap<>();
@@ -49,7 +49,7 @@ public class LsoTag extends Tag {
public LsoTag(byte[] data, boolean forceWriteAsLong) {
super(ID, "DefineLso", data, forceWriteAsLong);
}
public LsoTag(String fileName, int amfVersion, Map<String, Object> amfValues) {
super(ID, "DefineLso", new byte[0], true);
this.fileName = fileName;
@@ -81,7 +81,7 @@ public class LsoTag extends Tag {
while (ais.available() > 0) {
String varName = ais.readUtf8("varName");
try {
Object varValue = ais.readValue("varValue");
Object varValue = ais.readValue("varValue");
amfValues.put(varName, varValue);
} catch (NoSerializerExistsException ex) {
throw new IllegalArgumentException("Serializer for class " + ex.getClassName() + " not found");
@@ -89,7 +89,7 @@ public class LsoTag extends Tag {
ais.read(); //ending byte
}
ais.resolveMapReferences(amfValues);
}
}
if (amfVersion == 3) {
Amf3InputStream ais = new Amf3InputStream(new MemoryInputStream(amfData));
@@ -114,18 +114,18 @@ public class LsoTag extends Tag {
@Override
public void writeData(OutputStream os) throws IOException {
Amf0OutputStream aos = new Amf0OutputStream(os);
aos.write(new byte[] {'T', 'C', 'S', 'O'});
aos.write(new byte[] {0x00,0x04,0x00,0x00,0x00,0x00});
aos.write(new byte[]{'T', 'C', 'S', 'O'});
aos.write(new byte[]{0x00, 0x04, 0x00, 0x00, 0x00, 0x00});
byte[] fileNameData = fileName.getBytes("UTF-8");
aos.writeU16(fileNameData.length);
aos.write(fileNameData);
aos.writeU32(amfVersion);
if (amfVersion == 0) {
List<Object> complexObjects = new ArrayList<>();
for(String key: amfValues.keySet()) {
for (String key : amfValues.keySet()) {
aos.writeUtf8(key);
aos.writeValue(amfValues.get(key), complexObjects);
aos.writeValue(amfValues.get(key), complexObjects);
aos.write(0);
}
}
@@ -134,7 +134,7 @@ public class LsoTag extends Tag {
List<String> stringTable = new ArrayList<>();
List<Traits> traitTable = new ArrayList<>();
List<Object> objectTable = new ArrayList<>();
for(String key: amfValues.keySet()) {
for (String key : amfValues.keySet()) {
try {
a3os.writeUtf8Vr(key, stringTable);
a3os.writeValue(amfValues.get(key), new HashMap<>(), stringTable, traitTable, objectTable);
@@ -144,6 +144,6 @@ public class LsoTag extends Tag {
aos.write(0);
}
}
}
}
@@ -20,9 +20,9 @@ import com.jpexs.decompiler.flash.EndOfStreamException;
import com.jpexs.decompiler.flash.amf.amf0.Amf0OutputStream;
import com.jpexs.decompiler.flash.exporters.amf.amf0.Amf0Exporter;
import com.jpexs.decompiler.flash.exporters.amf.amf3.Amf3Exporter;
import com.jpexs.decompiler.flash.importers.amf.AmfParseException;
import com.jpexs.decompiler.flash.importers.amf.amf0.Amf0Importer;
import com.jpexs.decompiler.flash.importers.amf.amf3.Amf3Importer;
import com.jpexs.decompiler.flash.importers.amf.AmfParseException;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.EOFException;
@@ -46,24 +46,24 @@ public class SolFile {
private DataInputStream is;
private long pos = 0;
private List<Tag> tags = new ArrayList<>();
public SolFile(InputStream is) throws IOException {
this.is = new DataInputStream(is);
readTags();
}
public SolFile(String fileName, int amfVersion, Map<String, Object> amfValues) {
tags.add(new LsoTag(fileName, amfVersion, amfValues));
}
public void writeTo(OutputStream os) throws IOException {
for (Tag t: tags) {
for (Tag t : tags) {
writeTag(os, t);
}
}
private void readTags() throws IOException {
while (is.available() > 0) {
Tag t = readTag();
@@ -112,10 +112,10 @@ public class SolFile {
is.skip(count);
pos += count;
}
private void writeTag(OutputStream os, Tag t) throws IOException{
private void writeTag(OutputStream os, Tag t) throws IOException {
Amf0OutputStream aos = new Amf0OutputStream(os);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
t.writeData(baos);
int contentLength = baos.size();
@@ -137,7 +137,7 @@ public class SolFile {
contentLength = (int) readUI32();
writeAsLong = true;
}
int tagType = tagTypeAndLength >> 6;
int tagType = tagTypeAndLength >> 6;
byte[] data = readBytes(contentLength);
switch (tagType) {
@@ -153,8 +153,8 @@ public class SolFile {
public List<Tag> getTags() {
return tags;
}
private LsoTag getLsoTag() throws IOException {
private LsoTag getLsoTag() throws IOException {
for (Tag t : getTags()) {
if (t instanceof LsoTag) {
return (LsoTag) t;
@@ -162,7 +162,7 @@ public class SolFile {
}
return null;
}
public int getAmfVersion() throws IOException {
LsoTag lsoTag = getLsoTag();
if (lsoTag == null) {
@@ -170,7 +170,7 @@ public class SolFile {
}
return lsoTag.amfVersion;
}
public String getFileName() throws IOException {
LsoTag lsoTag = getLsoTag();
if (lsoTag == null) {
@@ -178,14 +178,14 @@ public class SolFile {
}
return lsoTag.fileName;
}
public Map<String, Object> getAmfValues() throws IOException {
LsoTag lsoTag = getLsoTag();
if (lsoTag == null) {
return new HashMap<>();
}
return lsoTag.amfValues;
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
SolFile sol0 = new SolFile(new FileInputStream("testdata/sharedobjects/data/amf0test.sol"));
@@ -1088,7 +1088,7 @@ public class Timeline {
double y = filter.getDeltaY();
deltaXMax = Math.max(x, deltaXMax);
deltaYMax = Math.max(y, deltaYMax);
}
}
rect.xMin -= deltaXMax * unzoom * SWF.unitDivisor;
rect.xMax += deltaXMax * unzoom * SWF.unitDivisor;
rect.yMin -= deltaYMax * unzoom * SWF.unitDivisor;
@@ -1096,9 +1096,9 @@ public class Timeline {
viewRect2.xMin -= deltaXMax * SWF.unitDivisor;
viewRect2.xMax += deltaXMax * SWF.unitDivisor;
viewRect2.yMin -= deltaYMax * SWF.unitDivisor;
viewRect2.yMax += deltaYMax * SWF.unitDivisor;
viewRect2.yMax += deltaYMax * SWF.unitDivisor;
}
drawMatrix.translate(rect.xMin, rect.yMin);
drawMatrix.translateX /= SWF.unitDivisor;
drawMatrix.translateY /= SWF.unitDivisor;
@@ -1111,7 +1111,6 @@ public class Timeline {
int deltaY = (int) Math.ceil(rect.yMin / SWF.unitDivisor);
newWidth = Math.min(image.getWidth() - deltaX, newWidth);
newHeight = Math.min(image.getHeight() - deltaY, newHeight);
if (newWidth <= 0 || newHeight <= 0) {
return;
@@ -1190,17 +1189,17 @@ public class Timeline {
} else {
// todo: show one time warning
}
if (cacheAsBitmap && layer.backGroundColor != null && (blendMode <= 1 || (filters != null && !filters.isEmpty()))) {
Graphics2D g2 = (Graphics2D) img.getGraphics();
g2.setComposite(AlphaComposite.DstOver);
Color bgColor = layer.backGroundColor.toColor();
g2.setColor(bgColor);
g2.setColor(bgColor);
g2.fillRect((int) Math.round(deltaXMax * unzoom),
(int) Math.round(deltaYMax * unzoom),
(int) Math.round(rect.getWidth() / SWF.unitDivisor - 2 * deltaXMax * unzoom),
(int) Math.round(rect.getHeight()/ SWF.unitDivisor - 2 * deltaYMax * unzoom)
);
(int) Math.round(deltaYMax * unzoom),
(int) Math.round(rect.getWidth() / SWF.unitDivisor - 2 * deltaXMax * unzoom),
(int) Math.round(rect.getHeight() / SWF.unitDivisor - 2 * deltaYMax * unzoom)
);
}
if (filters != null) {
@@ -1213,7 +1212,7 @@ public class Timeline {
img = colorTransForm.apply(img);
}
}
if (!sameImage && cacheAsBitmap && renderContext.displayObjectCache != null) {
renderContext.clearPlaceObjectCache(layer.placeObjectTag);
renderContext.displayObjectCache.put(new DisplayObjectCacheKey(layer.placeObjectTag, unzoom, viewRect), img);
@@ -1315,20 +1314,20 @@ public class Timeline {
g.setTransform(drawMatrix.toTransform());
if ((blendMode > 1 || (filters != null && !filters.isEmpty())) && mergedColorTransform != null) {
img = mergedColorTransform.apply(img);
img = mergedColorTransform.apply(img);
}
if (blendMode > 1 && (filters == null || filters.isEmpty()) && cacheAsBitmap && layer.backGroundColor != null) {
Graphics2D g2 = (Graphics2D) img.getGraphics();
g2.setComposite(AlphaComposite.DstOver);
Color bgColor = layer.backGroundColor.toColor();
g2.setColor(bgColor);
g2.fillRect((int) Math.round(deltaXMax * unzoom),
(int) Math.round(deltaYMax * unzoom),
(int) Math.round(rect.getWidth() / SWF.unitDivisor - 2 * deltaXMax * unzoom),
(int) Math.round(rect.getHeight()/ SWF.unitDivisor - 2 * deltaYMax * unzoom)
(int) Math.round(deltaYMax * unzoom),
(int) Math.round(rect.getWidth() / SWF.unitDivisor - 2 * deltaXMax * unzoom),
(int) Math.round(rect.getHeight() / SWF.unitDivisor - 2 * deltaYMax * unzoom)
);
}
}
if (!((blendMode == 11 || blendMode == 12) && parentBlendMode <= 1)) { //alpha and erase modes require parent blendmode not normal
g.drawImage(img.getBufferedImage(), 0, 0, null);
@@ -1386,7 +1385,7 @@ public class Timeline {
int maxDepth = getMaxDepth();
int clipCount = 0;
for (int i = 0; i <= maxDepth; i++) {
for (int i = 0; i <= maxDepth; i++) {
boolean clipChanged = clipCount != clips.size();
for (int c = 0; c < clips.size(); c++) {
if (clips.get(c).depth < i) {
@@ -1449,11 +1448,11 @@ public class Timeline {
if (drawMode != DRAW_MODE_ALL && drawMode != DRAW_MODE_SHAPES && (character instanceof ShapeTag)) {
continue;
}
if (ignoreDepths.contains(i)) {
continue;
}
if (character instanceof DrawableTag) {
RECT scalingRect = null;
@@ -203,6 +203,7 @@ public class FILLSTYLE implements NeedsCharacters, FieldChangeObserver, Serializ
/**
* Checks if fill style has bitmap
*
* @return True if fill style has bitmap
*/
public boolean hasBitmap() {
@@ -218,6 +219,7 @@ public class FILLSTYLE implements NeedsCharacters, FieldChangeObserver, Serializ
/**
* Checks if fill style has gradient
*
* @return True if fill style has gradient
*/
public boolean hasGradient() {
@@ -232,6 +234,7 @@ public class FILLSTYLE implements NeedsCharacters, FieldChangeObserver, Serializ
/**
* Checks whether fill style is compatible with other fill style
*
* @param otherFillStyle Other fill style
* @param swf SWF
* @return True if fill styles are compatible
@@ -264,6 +267,7 @@ public class FILLSTYLE implements NeedsCharacters, FieldChangeObserver, Serializ
/**
* Converts fill style to morph fill style
*
* @return Morph fill style
*/
public MORPHFILLSTYLE toMorphStyle() {
@@ -289,6 +293,7 @@ public class FILLSTYLE implements NeedsCharacters, FieldChangeObserver, Serializ
/**
* Converts fill style to morph fill style
*
* @param endFillStyle End fill style
* @param swf SWF
* @return Morph fill style
@@ -376,10 +381,9 @@ public class FILLSTYLE implements NeedsCharacters, FieldChangeObserver, Serializ
result.color = new RGBA(color);
}
}
if (fillStyleType == LINEAR_GRADIENT
if (fillStyleType == LINEAR_GRADIENT
|| fillStyleType == RADIAL_GRADIENT
|| fillStyleType == FOCAL_RADIAL_GRADIENT
) {
|| fillStyleType == FOCAL_RADIAL_GRADIENT) {
result.gradient = result.gradient.toShapeNum(targetShapeNum);
}
if (fillStyleType == FOCAL_RADIAL_GRADIENT && targetShapeNum < 4) {
@@ -387,7 +391,7 @@ public class FILLSTYLE implements NeedsCharacters, FieldChangeObserver, Serializ
}
return result;
}
public int getMinShapeNum() {
int shapeNum = 1;
if (fillStyleType == SOLID) {
@@ -51,7 +51,7 @@ public class LINESTYLEARRAY implements NeedsCharacters, Serializable {
public int getMinShapeNum(int sourceShapeNum) {
int result = 1;
if (sourceShapeNum >= 4) {
if (sourceShapeNum >= 4) {
for (LINESTYLE2 ls : lineStyles2) {
int sn = ls.getMinShapeNum();
if (sn > result) {
@@ -68,7 +68,7 @@ public class LINESTYLEARRAY implements NeedsCharacters, Serializable {
}
return result;
}
public LINESTYLEARRAY toShapeNum(int sourceShapeNum, int targetShapeNum) {
if (sourceShapeNum == targetShapeNum) {
return Helper.deepCopy(this);
@@ -80,7 +80,7 @@ public class LINESTYLEARRAY implements NeedsCharacters, Serializable {
result.lineStyles2[i] = lineStyles[i].toLineStyle2();
}
} else {
result.lineStyles = new LINESTYLE[sourceShapeNum >=4 ? lineStyles2.length : lineStyles.length];
result.lineStyles = new LINESTYLE[sourceShapeNum >= 4 ? lineStyles2.length : lineStyles.length];
if (sourceShapeNum >= 4) {
for (int i = 0; i < lineStyles2.length; i++) {
result.lineStyles[i] = lineStyles2[i].toLineStyle1(targetShapeNum);
@@ -100,7 +100,7 @@ public class LINESTYLEARRAY implements NeedsCharacters, Serializable {
}
return result;
}
@Override
public void getNeededCharacters(Set<Integer> needed, SWF swf) {
if (lineStyles != null) {
@@ -150,6 +150,7 @@ public class LINESTYLEARRAY implements NeedsCharacters, Serializable {
/**
* Converts to MORPHLINESTYLEARRAY
*
* @return MORPHLINESTYLEARRAY
*/
public MORPHLINESTYLEARRAY toMorphLineStyleArray() {
@@ -16,11 +16,6 @@
*/
package com.jpexs.decompiler.flash.types;
import static com.jpexs.decompiler.flash.types.GRADIENT.INTERPOLATION_LINEAR_RGB_MODE;
import static com.jpexs.decompiler.flash.types.GRADIENT.INTERPOLATION_RGB_MODE;
import static com.jpexs.decompiler.flash.types.GRADIENT.SPREAD_PAD_MODE;
import static com.jpexs.decompiler.flash.types.GRADIENT.SPREAD_REFLECT_MODE;
import static com.jpexs.decompiler.flash.types.GRADIENT.SPREAD_REPEAT_MODE;
import com.jpexs.decompiler.flash.types.annotations.EnumValue;
import com.jpexs.decompiler.flash.types.annotations.SWFType;
import java.io.Serializable;
@@ -36,17 +31,17 @@ public class MORPHGRADIENT implements Serializable {
* Spread mode. See GRADIENT.SPREAD_* constants
*/
@SWFType(value = BasicType.UB, count = 2)
@EnumValue(value = SPREAD_PAD_MODE, text = "Pad")
@EnumValue(value = SPREAD_REFLECT_MODE, text = "Reflect")
@EnumValue(value = SPREAD_REPEAT_MODE, text = "Repeat")
@EnumValue(value = GRADIENT.SPREAD_PAD_MODE, text = "Pad")
@EnumValue(value = GRADIENT.SPREAD_REFLECT_MODE, text = "Reflect")
@EnumValue(value = GRADIENT.SPREAD_REPEAT_MODE, text = "Repeat")
public int spreadMode;
/**
* Interpolation mode. See GRADIENT.INTERPOLATION_* constants
*/
@SWFType(value = BasicType.UB, count = 2)
@EnumValue(value = INTERPOLATION_RGB_MODE, text = "Normal RGB")
@EnumValue(value = INTERPOLATION_LINEAR_RGB_MODE, text = "Linear RGB")
@EnumValue(value = GRADIENT.INTERPOLATION_RGB_MODE, text = "Normal RGB")
@EnumValue(value = GRADIENT.INTERPOLATION_LINEAR_RGB_MODE, text = "Linear RGB")
public int interpolationMode;
/**
@@ -56,6 +51,7 @@ public class MORPHGRADIENT implements Serializable {
/**
* Morphs two colors at given ratio.
*
* @param c1 Color 1
* @param c2 Color 2
* @param ratio Ratio
@@ -83,6 +79,7 @@ public class MORPHGRADIENT implements Serializable {
/**
* Gets gradient at given ratio.
*
* @param ratio Ratio
* @return Gradient
*/
@@ -103,6 +100,7 @@ public class MORPHGRADIENT implements Serializable {
/**
* Gets start gradient.
*
* @return Start gradient
*/
public GRADIENT getStartGradient() {
@@ -118,6 +116,7 @@ public class MORPHGRADIENT implements Serializable {
/**
* Gets end gradient.
*
* @return End gradient
*/
public GRADIENT getEndGradient() {
@@ -41,12 +41,7 @@ public class BinDataOutputStream extends OutputStream {
os.write(i);
}
}
public void writeUI16(int value) throws IOException {
write(value & 0xFF);
write((value >> 8) & 0xFF);
}
@Override
public void write(byte[] b) throws IOException {
os.write(b);
@@ -57,6 +52,11 @@ public class BinDataOutputStream extends OutputStream {
os.write(b, off, len);
}
public void writeUI16(int value) throws IOException {
write(value & 0xFF);
write((value >> 8) & 0xFF);
}
public void writeUI32(long value) throws IOException {
write((int) (value & 0xFF));
write((int) ((value >> 8) & 0xFF));
@@ -30,12 +30,14 @@ import javax.imageio.ImageIO;
/**
* Generates bin/*.dat file for images.
*
* @author JPEXS
*/
public class ImageBinDataGenerator {
/**
* Generates data
*
* @param is Input stream
* @param os Output stream
* @param format Image format
@@ -65,7 +67,7 @@ public class ImageBinDataGenerator {
w.writeUI32(0);
w.writeUI32(20 * bimg.getWidth());
w.writeUI32(0);
w.writeUI32(0);
w.writeUI32(20 * bimg.getHeight());
w.write(0x01); //has transparency
@@ -81,19 +83,19 @@ public class ImageBinDataGenerator {
int b = (rgba >> 16) & 0xFF;
int g = (rgba >> 8) & 0xFF;
int r = rgba & 0xFF;
//some weird premultiplication
if (a != 255) {
r = (int)Math.floor(r * a / 256f);
g = (int)Math.floor(g * a / 256f);
b = (int)Math.floor(b * a / 256f);
r = (int) Math.floor(r * a / 256f);
g = (int) Math.floor(g * a / 256f);
b = (int) Math.floor(b * a / 256f);
}
//also weird, but this way it works...
if (a != 0 && a != 255) {
a = a + 1;
}
}
def.write(a);
def.write(b);
def.write(g);
@@ -29,6 +29,7 @@ import javax.imageio.ImageIO;
/**
* Reads bin/*.dat file of lossless images and produces BufferedImage
*
* @author JPEXS
*/
public class LosslessImageBinDataReader {
@@ -87,14 +88,14 @@ public class LosslessImageBinDataReader {
int b = data[pos++] & 0xFF;
int g = data[pos++] & 0xFF;
int r = data[pos++] & 0xFF;
if (a != 0 && a != 255) {
a = a - 1;
r = (int)Math.floor(r * 256f / a);
g = (int)Math.floor(g * 256f / a);
b = (int)Math.floor(b * 256f / a);
}
r = (int) Math.floor(r * 256f / a);
g = (int) Math.floor(g * 256f / a);
b = (int) Math.floor(b * 256f / a);
}
int rgba = r + (g << 8) + (b << 16) + (a << 24);
img.setRGB(x, y, rgba);
@@ -2914,12 +2914,14 @@ public class XFLConverter {
return ret;
}
private static class AccessibilityBag {
private List<AccessibilityItem> items = new ArrayList<>();
public void add(AccessibilityItem item) {
items.add(item);
}
public Map<String, String> getAttributes(String instanceName, int frame) {
Map<String, String> ret = new LinkedHashMap<>();
for (AccessibilityItem item : items) {
@@ -2942,10 +2944,11 @@ public class XFLConverter {
sb.append(item.toString());
}
return sb.toString();
}
}
}
private static class AccessibilityItem {
int startFrame;
int endFrame;
String instanceName;
@@ -2955,19 +2958,18 @@ public class XFLConverter {
public AccessibilityItem(String instanceName, String attributeKey, String attributeValue) {
this(instanceName, attributeKey, attributeValue, 1, Integer.MAX_VALUE);
}
public AccessibilityItem(String instanceName, String attributeKey, String attributeValue, int frame) {
this(instanceName, attributeKey, attributeValue, frame, frame);
}
public AccessibilityItem(String instanceName, String attributeKey, String attributeValue, int startFrame, int endFrame) {
this.startFrame = startFrame;
this.endFrame = endFrame;
this.instanceName = instanceName;
this.attributeKey = attributeKey;
this.attributeValue = attributeValue;
}
}
public boolean contains(String instanceName, int frame) {
if (!Objects.equals(instanceName, this.instanceName)) {
@@ -2978,7 +2980,7 @@ public class XFLConverter {
@Override
public String toString() {
return "[instance: " + instanceName+" key: \"" + attributeKey+"\" value: \"" + attributeValue +"\" frames: " + startFrame + " to " + (endFrame == Integer.MAX_VALUE ? "end" : endFrame) + "]";
return "[instance: " + instanceName + " key: \"" + attributeKey + "\" value: \"" + attributeValue + "\" frames: " + startFrame + " to " + (endFrame == Integer.MAX_VALUE ? "end" : endFrame) + "]";
}
@Override
@@ -3019,10 +3021,7 @@ public class XFLConverter {
return Objects.equals(this.attributeValue, other.attributeValue);
}
}
private static AccessibilityBag getAccessibilityFromPack(AbcIndexing abcIndex, ScriptPack pack) {
int swfVersion = -1;
@@ -3089,7 +3088,7 @@ public class XFLConverter {
TraitMethodGetterSetter tm = (TraitMethodGetterSetter) t;
if (abc.method_info.get(tm.method_info).param_types.length != 1) {
continue;
}
}
MethodBody traitBody = abc.findBody(tm.method_info);
List<MethodBody> traitCallStack = new ArrayList<>();
traitCallStack.add(traitBody);
@@ -3112,8 +3111,8 @@ public class XFLConverter {
|| propName.resolvedMultinameName.startsWith("__setTab_"))
&& callProp.arguments.size() == 1) {
frameRangeAccessibilityTraitNames.add(propName.resolvedMultinameName);
}
}
}
}
}
if (frameTraitNames.contains(traitName)) {
TraitMethodGetterSetter tm = (TraitMethodGetterSetter) t;
@@ -3144,7 +3143,7 @@ public class XFLConverter {
for (Trait t : instanceInfo.instance_traits.traits) {
if (t instanceof TraitMethodGetterSetter) {
String traitName = t.getName(abc).getName(abc.constants, new ArrayList<>(), true, false);
String traitName = t.getName(abc).getName(abc.constants, new ArrayList<>(), true, false);
if (frameAccessibilityTraitNames.contains(traitName)) {
TraitMethodGetterSetter tm = (TraitMethodGetterSetter) t;
MethodBody traitBody = abc.findBody(tm.method_info);
@@ -3246,7 +3245,7 @@ public class XFLConverter {
}
}
}
if (frameRangeAccessibilityTraitNames.contains(traitName)) {
TraitMethodGetterSetter tm = (TraitMethodGetterSetter) t;
MethodBody traitBody = abc.findBody(tm.method_info);
@@ -3351,21 +3350,21 @@ public class XFLConverter {
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
for (Trait t : instanceInfo.instance_traits.traits) {
if (allFramesAccessibilityTraitNames.contains(t.getName(abc).getName(abc.constants, new ArrayList<>(), true, false))) {
if (t instanceof TraitMethodGetterSetter) {
@@ -3440,7 +3439,7 @@ public class XFLConverter {
if (setProp.value instanceof FalseItem) {
val = invert ? "true" : "false";
}
ret.add(new AccessibilityItem(parentParentProp.resolvedMultinameName, acProp, val));
ret.add(new AccessibilityItem(parentParentProp.resolvedMultinameName, acProp, val));
}
}
}
@@ -3548,8 +3547,8 @@ public class XFLConverter {
callStack.add(frameBody);
frameBody.convert(swfVersion, callStack, abcIndex, new ConvertData(), "??", ScriptExportMode.AS, false, methodIndex, pack.scriptIndex, classIndex, abc, methodTrait, new ScopeStack(), 0, new NulWriter(), new ArrayList<>(), new Traits(), true, new HashSet<>(), new ArrayList<>());
if (frameBody.convertedItems != null) {
if (frameBody.convertedItems != null) {
for (int i = 0; i < frameBody.convertedItems.size(); i++) {
GraphTargetItem ti = frameBody.convertedItems.get(i);
if (ti instanceof CallPropertyAVM2Item) {
@@ -3567,7 +3566,7 @@ public class XFLConverter {
}
}
}
StringBuilderTextWriter writer = new StringBuilderTextWriter(Configuration.getCodeFormatting(), scriptBuilder);
frameBody.toString(swfVersion, callStack, abcIndex, "??", ScriptExportMode.AS, abc, methodTrait, writer, new ArrayList<>(), new HashSet<>());
@@ -96,7 +96,7 @@ public class Graph {
* Exceptions in the graph
*/
private final List<GraphException> exceptions;
/**
* Debug flag to print all parts
*/
@@ -2692,6 +2692,19 @@ public class Graph {
}
return true;
}
/**
* Gets if expression from stack. Can be overridden for custom handling
*
* @param localData Local data
* @param stack Stack
* @param output Output
* @return Expression
*/
protected GraphTargetItem getIfExpression(BaseLocalData localData, TranslateStack stack, List<GraphTargetItem> output) {
return stack.pop();
}
/**
* Walks graph parts and converts them to target items.
@@ -2717,18 +2730,6 @@ public class Graph {
protected final List<GraphTargetItem> printGraph(List<GotoItem> foundGotos, Map<GraphPart, List<GraphTargetItem>> partCodes, Map<GraphPart, Integer> partCodePos, Set<GraphPart> visited, BaseLocalData localData, TranslateStack stack, Set<GraphPart> allParts, GraphPart parent, GraphPart part, List<GraphPart> stopPart, List<StopPartKind> stopPartKind, List<Loop> loops, List<ThrowState> throwStates, int staticOperation, String path) throws InterruptedException {
return printGraph(foundGotos, partCodes, partCodePos, visited, localData, stack, allParts, parent, part, stopPart, stopPartKind, loops, throwStates, null, staticOperation, path, 0);
}
/**
* Gets if expression from stack.
* Can be overridden for custom handling
* @param localData Local data
* @param stack Stack
* @param output Output
* @return Expression
*/
protected GraphTargetItem getIfExpression(BaseLocalData localData, TranslateStack stack, List<GraphTargetItem> output) {
return stack.pop();
}
/**
* Walks graph parts and converts them to target items.
@@ -2964,7 +2965,7 @@ public class Graph {
List<StopPartKind> stopPartKind2 = new ArrayList<>(stopPartKind);
stopPartKind2.add(StopPartKind.OTHER);
Set<GraphPart> subVisited = new HashSet<>();
/*
* Save loop phases to be able to walk precontinue block again.
*/
@@ -3003,8 +3004,8 @@ public class Graph {
}
if (currentLoop.loopPreContinue == null) {
precontinueCommands.clear();
/**
/*
* Restore loop phases
*/
for (int i = 0; i < loopPhases.size(); i++) {
@@ -3352,7 +3353,7 @@ public class Graph {
} else {
ternarOnFalse = filteredOnFalse.get(0).value;
}
TernarOpItem top = new TernarOpItem(null, localData.lineStartInstruction, expr.invert(null), ternarOnTrue, ternarOnFalse);
TernarOpItem top = new TernarOpItem(null, localData.lineStartInstruction, expr.invert(null), ternarOnTrue, ternarOnFalse);
stack.push(handleTernar(top, localData));
} else {
boolean isIf = true;
@@ -3887,7 +3888,7 @@ public class Graph {
if (ti.hasSingleNewLineAround() && !lastNewLine) {
writer.newLine();
}
ti.toStringSemicoloned(writer, localData);
ti.toStringSemicoloned(writer, localData);
if (!ti.handlesNewLine()) {
writer.newLine();
}
@@ -4293,9 +4294,10 @@ public class Graph {
protected boolean partIsSwitch(GraphPart part) {
return false;
}
/**
* Replaces ternar with custom value
*
* @param ternar Ternar
* @param localData Local data
* @return Custom item
@@ -31,14 +31,13 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
/*private static final Map<Thread, CancellableWorker> threadWorkers = Collections.synchronizedMap(new WeakHashMap<>());
/*private static final Map<Thread, CancellableWorker> threadWorkers = Collections.synchronizedMap(new WeakHashMap<>());
private static final Map<Thread, CancellableWorker> parentThreadWorkers = Collections.synchronizedMap(new WeakHashMap<>());
private static final Map<Thread, Thread> threadToParentThread = Collections.synchronizedMap(new WeakHashMap<>());
*/
*/
/**
* Cancellable worker.
@@ -55,57 +54,55 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
private FutureTask<T> future;
private List<CancellableWorker> subWorkers = Collections.synchronizedList(new ArrayList<>());
private static final Map<Thread, CancellableWorker> thread2Worker = Collections.synchronizedMap(new WeakHashMap<>());
private static final Map<Thread, CancellableWorker> thread2Worker = Collections.synchronizedMap(new WeakHashMap<>());
private Thread parentThread;
private Thread thread;
private String name;
private CancellableWorker parentWorker;
private boolean canceled = false;
private List<Runnable> cancelListeners = new ArrayList<>();
public Thread getThread() {
return thread;
}
}
public static void assignThreadToWorker(Thread t, CancellableWorker w) {
if (w == null) {
return;
}
thread2Worker.put(t, w);
}
public static CancellableWorker getCurrent() {
Thread t = Thread.currentThread();
CancellableWorker w = thread2Worker.get(t);
return w;
}
public void addCancelListener(Runnable listener) {
cancelListeners.add(listener);
}
public void removeCancelListener(Runnable listener) {
cancelListeners.remove(listener);
}
public static boolean isInterrupted() {
Thread t = Thread.currentThread();
if (t.isInterrupted()) {
return true;
}
CancellableWorker w = thread2Worker.get(t);
if (w != null) {
CancellableWorker w = thread2Worker.get(t);
if (w != null) {
while (w != null) {
t = w.thread;
if (t != null && t.isInterrupted()) {
@@ -115,26 +112,27 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
return true;
}
w = w.parentWorker;
}
}
}
return false;
}
/**
* Constructor.
*
* @param name Identifier of action
*/
public CancellableWorker(String name) {
super();
this.name = name;
this.name = name;
Callable<T> callable = new Callable<T>() {
@Override
public T call() throws Exception {
thread = Thread.currentThread();
thread = Thread.currentThread();
thread2Worker.put(thread, CancellableWorker.this);
if (isInterrupted()) {
throw new InterruptedException();
}
}
return doInBackground();
}
};
@@ -149,6 +147,7 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
/**
* Do in background.
*
* @return Result
* @throws Exception On error
*/
@@ -188,25 +187,24 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
}
@Override
public final boolean cancel(boolean mayInterruptIfRunning) {
public final boolean cancel(boolean mayInterruptIfRunning) {
canceled = true;
boolean r = future.cancel(mayInterruptIfRunning);
List<CancellableWorker> sw = new ArrayList<>(subWorkers);
for (CancellableWorker w : sw) {
w.cancel(mayInterruptIfRunning);
}
if (r) {
List<Runnable> cls = new ArrayList<>(cancelListeners);
}
if (r) {
List<Runnable> cls = new ArrayList<>(cancelListeners);
for (Runnable listener : cls) {
listener.run();
}
workerCancelled();
}
}
return r;
}
@@ -234,17 +232,15 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
@Override
public final T get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
ExecutionException, TimeoutException {
return future.get(timeout, unit);
}
@Override
public String toString() {
return "[CancellableWorker \"" + name + "\" on thread " + thread +", subworkers: " + subWorkers.size() + ", " + (canceled ? " canceled" : "") + ", " + (parentWorker != null ? "HASPARENT" : "NOPARENT");
return "[CancellableWorker \"" + name + "\" on thread " + thread + ", subworkers: " + subWorkers.size() + ", " + (canceled ? " canceled" : "") + ", " + (parentWorker != null ? "HASPARENT" : "NOPARENT");
}
private void workerDone() {
if (thread != null && thread2Worker.get(thread) == this) {
//thread2Worker.remove(thread);
@@ -255,6 +251,7 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
/**
* Calls a callable with a timeout.
*
* @param name Name
* @param c Callable
* @param timeout Timeout
@@ -265,7 +262,7 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
* @throws ExecutionException On execution error
* @throws TimeoutException On timeout
*/
public static <T> T call(String name, final Callable<T> c, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
public static <T> T call(String name, final Callable<T> c, long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
CancellableWorker<T> worker = new CancellableWorker<T>(name) {
@Override
@@ -279,7 +276,7 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
} finally {
worker.cancel(true);
}
}
}
/**
* Cancels all background threads.
@@ -295,7 +292,7 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
}
}
}
public static void cancelThread(Thread t) {
List<CancellableWorker> ws = new ArrayList<>(workers);
for (CancellableWorker w : ws) {
@@ -304,7 +301,7 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
w.cancel(true);
}
}
}
}
}
/**
@@ -316,7 +313,7 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
w.free();
}
}
@SuppressWarnings("unchecked")
private void printTree(List<String> out) {
out.add("worker " + name + " on thread " + thread);
@@ -324,32 +321,32 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
for (CancellableWorker sw : sws) {
List<String> subout = new ArrayList<>();
sw.printTree(subout);
for (String s:subout) {
for (String s : subout) {
out.add("-" + s);
}
}
}
public void printTree() {
System.err.println("=======================");
List<String> out = new ArrayList<>();
printTree(out);
for (String s : out) {
System.err.println(s);
}
System.err.println("/=======================");
}
public static void printAllWorkers() {
List<CancellableWorker> aw = new ArrayList<>(workers);
System.err.println("====ALL WORKERS ====");
for (CancellableWorker w : aw) {
System.err.println("" + w);
}
System.err.println("/====================");
}
public void printTree() {
System.err.println("=======================");
List<String> out = new ArrayList<>();
printTree(out);
for (String s:out) {
System.err.println(s);
}
System.err.println("/=======================");
}
public void startWorkerMonitor() {
Thread monit = new Thread() {
@Override
@@ -364,8 +361,8 @@ public abstract class CancellableWorker<T> implements RunnableFuture<T> {
return;
}
}
}
}
};
monit.start();
monit.start();
}
}