code
stringlengths
3
1.18M
language
stringclasses
1 value
package kianxali.loader.pe; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import kianxali.loader.ByteSequence; public class Imports { private List<Import> imports; private Map<Long, Import> memToImport; private Map<Long, String> memToFunc; private boolean imports64; private class Import { @SuppressWarnings("unused") long orgThunk, timeStamp, forwarderChain, nameRVA, firstThunk; String dllName; List<String> functionNames; } { imports = new LinkedList<>(); memToImport = new HashMap<>(); memToFunc = new HashMap<>(); } public Imports() { } public Imports(ByteSequence image, AddressConverter rva, boolean isPE32Plus) { this.imports64 = isPE32Plus; do { Import imp = new Import(); // IMAGE_IMPORT_DESCRIPTOR entry imp.orgThunk = image.readUDword(); // points to IMAGE_THUNK_DATA (union: as type IMAGE_IMPORT_BY_NAME) chain imp.timeStamp = image.readUDword(); imp.forwarderChain = image.readUDword(); imp.nameRVA = image.readUDword(); imp.firstThunk = image.readUDword(); if(imp.nameRVA == 0) { break; } imp.functionNames = new ArrayList<>(); imports.add(imp); } while(true); for(Import imp : imports) { loadImport(image, imp, rva); } loadIAT(image, rva); } private void loadImport(ByteSequence image, Import imp, AddressConverter rva) { image.seek(rva.rvaToFile(imp.nameRVA)); imp.dllName = image.readString(); List<Long> nameHints = new LinkedList<>(); image.seek(rva.rvaToFile(imp.orgThunk)); do { long nameHintRva; // walk IMAGE_THUNK_DATA chain, interpreting it as IMAGE_IMPORT_BY_NAME if(imports64) { nameHintRva = image.readSQword(); // FIXME UQWord } else { nameHintRva = image.readUDword(); } if(nameHintRva == 0) { break; } nameHints.add(nameHintRva); } while(true); // now that we read the chain with the name pointers, read the actual names for(Long nameRva : nameHints) { String name; if((!imports64 && (nameRva & 0x80000000) != 0) || (imports64 && (nameRva & 0x8000000000000000L) != 0)) { // hint only, no name name = String.format("<%s!ordinal%04X>", imp.dllName, nameRva & 0xFFFF); } else { image.seek(rva.rvaToFile(nameRva)); image.readUWord(); // ignore import hint name = image.readString(); } imp.functionNames.add(name); } } private void loadIAT(ByteSequence image, AddressConverter rva) { for(Import imp : imports) { image.seek(rva.rvaToFile(imp.firstThunk)); int nameIndex = 0; do { long entryRVA = rva.fileToRVA(image.getPosition()); long nameHintRva; if(imports64) { nameHintRva = image.readSQword(); // FIXME UQWord } else { nameHintRva = image.readUDword(); } if(nameHintRva == 0) { break; } memToImport.put(rva.rvaToMemory(entryRVA), imp); memToFunc.put(rva.rvaToMemory(entryRVA), imp.functionNames.get(nameIndex++)); } while(true); } } public String getDLLName(long memAddress) { if(memToImport.containsKey(memAddress)) { return memToImport.get(memAddress).dllName; } else { return null; } } public String getFunctionName(long memAddress) { if(memToFunc.containsKey(memAddress)) { return memToFunc.get(memAddress); } else { return null; } } public Map<Long, String> getAllImports() { Map<Long, String> res = new HashMap<>(); for(Long mem : memToFunc.keySet()) { res.put(mem, memToFunc.get(mem)); } return res; } @Override public String toString() { StringBuilder res = new StringBuilder(); List<Long> memLocs = new ArrayList<>(memToFunc.keySet()); Collections.sort(memLocs); for(Long mem : memLocs) { res.append(String.format("%08X", mem) + ": " + memToImport.get(mem).dllName + " -> " + memToFunc.get(mem) + "\n"); } return res.toString(); } }
Java
package kianxali.loader.pe; import kianxali.loader.ByteSequence; public class OptionalHeader { public static final int HEADER_MAGIC_PE32 = 0x010B; public static final int HEADER_MAGIC_PE32PLUS = 0x020B; // means some fields are 64 bit, but doesn't imply 64 bit code public enum SubSystem { DLL, CONSOLE, GUI }; public static final int DATA_DIRECTORY_EXPORT = 0; public static final int DATA_DIRECTORY_IMPORT = 1; public static final int DATA_DIRECTORY_RESOURCES = 2; public static final int DATA_DIRECTORY_RELOC = 5; public static final int DATA_DIRECTORY_BOUND_IMPORT = 11; public static final int DATA_DIRECTORY_IAT = 12; private final long entryPointRVA, imageBase; private final long sectionAlignment, fileAlignment; private final long requiredMemory; private SubSystem subSystem; private final DataDirectory[] dataDirectories; private boolean pe32plus; private class DataDirectory { long offset, size; } public OptionalHeader(ByteSequence image) { int magic = image.readUWord(); if(magic == HEADER_MAGIC_PE32) { pe32plus = false; } else if(magic == HEADER_MAGIC_PE32PLUS) { pe32plus = true; } else { throw new RuntimeException("invalid optional header magic: " + magic); } // ignore linker version image.readUWord(); // ignore unreliable section sizes image.readUDword(); image.readUDword(); image.readUDword(); entryPointRVA = image.readUDword(); // ignore uninteresting offsets image.readUDword(); if(pe32plus) { imageBase = image.readSQword(); } else { image.readUDword(); imageBase = image.readUDword(); } sectionAlignment = image.readUDword(); fileAlignment = image.readUDword(); // ignore expected OS version image.readUWord(); image.readUWord(); // ignore binary version image.readUWord(); image.readUWord(); // ignore subsystem version image.readUWord(); image.readUWord(); // ignore win32 version image.readUDword(); requiredMemory = image.readUDword(); // ignore size of headers image.readUDword(); // ignore checksum image.readUDword(); // ignore subsystem int subSys = image.readUWord(); switch (subSys) { case 0: subSystem = SubSystem.DLL; break; case 2: subSystem = SubSystem.GUI; break; case 3: subSystem = SubSystem.CONSOLE; break; default: throw new RuntimeException("invalid subsystem in optional header: " + subSys); } // ignore unused DLL stuff image.readUWord(); // ignore stack sizes if(pe32plus) { image.readSQword(); image.readSQword(); image.readSQword(); image.readSQword(); } else { image.readUDword(); image.readUDword(); image.readUDword(); image.readUDword(); } // ignore loader flags image.readUDword(); int numberOfRVAs = (int) Math.min(16, image.readUDword()); dataDirectories = new DataDirectory[numberOfRVAs]; for(int i = 0; i < numberOfRVAs; i++) { dataDirectories[i] = new DataDirectory(); dataDirectories[i].offset = image.readUDword(); dataDirectories[i].size = image.readUDword(); } } public long getEntryPointRVA() { return entryPointRVA; } public long getImageBase() { return imageBase; } public long getFileAlignment() { return fileAlignment; } public long getSectionAlignment() { return sectionAlignment; } public SubSystem getSubSystem() { return subSystem; } public long getRequiredMemory() { return requiredMemory; } public long getDataDirectoryOffsetRVA(int index) { return dataDirectories[index].offset; } public long getDataDirectorySize(int index) { return dataDirectories[index].size; } }
Java
package kianxali.decoder; import kianxali.util.OutputFormatter; /** * An entity is a decoded instruction or data with a fixed * memory address. Every memory address can become either * data or instruction. * @author fwi * */ public interface DecodedEntity { /** * Returns the memory address of this entity * @return the memory address of this entity */ long getMemAddress(); /** * Returns the size of this entity in bytes * @return the size in bytes */ int getSize(); /** * Converts this entity into a string representation * @param format the formatter to use * @return a string describing the entity */ String asString(OutputFormatter format); }
Java
/** * The decoder's task is to process a single entry from a {@link kianxali.loader.ByteSequence} and * parse it into an {@link kianxali.decoder.Instruction} instance. The main class that can be used * by other packages is {@link kianxali.decoder.Decoder}. */ package kianxali.decoder;
Java
package kianxali.decoder; import kianxali.loader.ByteSequence; import kianxali.util.OutputFormatter; /** * This class represents data references that can be yielded by operands. * The data can be used for further analysis by higher level classes. * @author fwi * */ public class Data implements DecodedEntity { /** Data type that an instance can represent */ public enum DataType { BYTE, WORD, DWORD, QWORD, DQWORD, DYWORD, FLOAT, DOUBLE, STRING, FUN_PTR, UNKNOWN, JUMP_TABLE; } private final long memAddr; private DataType type; private Object content; private int tableScaling; // for data arrays /** * Construct a new data item * @param memAddr the address of the data * @param type the type of data */ public Data(long memAddr, DataType type) { this.memAddr = memAddr; this.type = type; } /** * Change the data type * @param type new type */ public void setType(DataType type) { this.type = type; } /** * If the data is a table, this sets the size of the * entries * @param tableScaling size of the entries in the table */ public void setTableScaling(int tableScaling) { this.tableScaling = tableScaling; } /** * If the data is a table, this returns the size of its entries * @return the size of a table entry */ public int getTableScaling() { return tableScaling; } /** * Actually analyze the contents of the memory address * @param seq a byte sequence already pointing to the correct address */ public void analyze(ByteSequence seq) { String str = checkForString(seq); if(str != null) { content = str; return; } switch(type) { case BYTE: content = seq.readUByte(); break; case WORD: content = seq.readUWord(); break; case DWORD: content = seq.readUDword(); break; case QWORD: content = seq.readSQword(); break; case DQWORD: content = seq.readSQword(); break; // FIXME case FLOAT: content = seq.readFloat(); break; case DOUBLE: content = seq.readDouble(); break; case FUN_PTR: content = seq.readUDword(); break; // FIXME -> 32 || 64 case STRING: content = seq.readString(); break; case UNKNOWN: content = seq.readUByte(); break; case DYWORD: content = seq.readSDword(); break; default: content = seq.readUByte(); break; } } private String checkForString(ByteSequence seq) { long oldPos = seq.getPosition(); StringBuilder res = new StringBuilder(); boolean complete = false; do { byte b = seq.readSByte(); if(b == 0) { complete = true; break; } else if(b == '\r' || b == '\n' || b >= 32) { res.append((char) b); } else { break; } } while(true); if(res.length() > 0 && complete) { type = DataType.STRING; return res.toString(); } else { seq.seek(oldPos); return null; } } @Override public long getMemAddress() { return memAddr; } @Override public int getSize() { switch(type) { case BYTE: return 1; case WORD: return 2; case DWORD: return 4; case QWORD: return 8; case DQWORD: return 16; case DYWORD: return 64; case FLOAT: return 4; case DOUBLE: return 8; case FUN_PTR: return 4; // FIXME case STRING: return 1; // FIXME case UNKNOWN: return 1; default: return 1; } } /** * Returns the type of the associated data * @return the type of the associated data */ public DataType getType() { return type; } /** * Returns an arbitrary object that was decoded when * analyzing the data, can be null. * @return an arbitrary object representing the decoded data */ public Object getRawContent() { return content; } @Override public String asString(OutputFormatter format) { if(content instanceof Number) { Number n = (Number) content; return "<" + type + ": " + format.formatImmediate(n.longValue()) + ">"; } else { return "<" + type + ": " + content + ">"; } } @Override public String toString() { if(content != null) { return content.toString(); } else { return "<empty data>"; } } }
Java
package kianxali.decoder; import java.util.List; import java.util.Map; /** * This interface represents a decoded instruction. To have the * disassembler architecture independent, instructions must supply * some information to the dissasembler through this interface. * @author fwi * */ public interface Instruction extends DecodedEntity { /** * If this instruction stops the current execution trace, * this method must return true. In other words: If the * next instruction following this instruction <i>can't</i> * be the next instruction in the byte sequence, it must return * true. Examples are RET and JMP, but not CALL or JNZ * @return true iff the instruction stops the current trace */ boolean stopsTrace(); /** * Return true if this instruction is a function call * @return true iff the instruction is a function call */ boolean isFunctionCall(); /** * Return true if this instruction is an unconditional jump. * If this is true, the destination should be returned * in {@link Instruction#getBranchAddresses()}. * @return true iff this instruction is an uncinditonal jump */ boolean isUnconditionalJump(); /** * Returns a string representation of the mnemonic (excluding operands) * @return a string containing the mnemonic */ String getMnemonic(); /** * Return a list of operands for this instruction * @return a list of operands, may not be null */ List<Operand> getOperands(); /** * Return a list of operands that are used as source * @return a list of source operands */ List<Operand> getSrcOperands(); /** * Return a list of operands that are used as destination * @return a list of destination operands */ List<Operand> getDestOperands(); /** * Return a list of possible branch addresses * @return a list containing branch addresses, may not be null */ List<Long> getBranchAddresses(); /** * Return a map of data references that are referenced * by this instruction, the boolean is a flag for write access * @return a list of data references, may not be null */ Map<Data, Boolean> getAssociatedData(); /** * Return a map of numbers that are likely to refer * to memory addresses of data, the boolean is a flag for write access * @return a list of likely data addresses */ Map<Long, Boolean> getProbableDataPointers(); /** * Return the full instruction including operands as an array of bytes * @return a byte array containing the full instruction */ short[] getRawBytes(); /** * Return a short string description of the instruction * @return a short string describing the instruction */ String getDescription(); }
Java
package kianxali.decoder; import java.util.ArrayList; import java.util.List; import kianxali.loader.ByteSequence; import kianxali.util.OutputFormatter; /** * A jump table is a special type of data that represents * a table of memory adresses pointing to code. * @author fwi * */ public class JumpTable extends Data { private final List<Long> entries; /** * Construct a new jump table object * @param memAddr the memory address of this table */ public JumpTable(long memAddr) { super(memAddr, DataType.JUMP_TABLE); this.entries = new ArrayList<>(); } /** * Adds a code address to the table * @param entry the code address to add */ public void addEntry(long entry) { entries.add(entry); } @Override public void analyze(ByteSequence seq) { // analyzed by disassembler return; } @Override public String asString(OutputFormatter format) { StringBuilder res = new StringBuilder("<Jump table with " + entries.size() + " entries:"); for(long entry : entries) { res.append(" " + format.formatAddress(entry)); } res.append(">"); return res.toString(); } }
Java
package kianxali.decoder; /** * A context stores information that is required for and modified when parsing * opcodes. It is mostly architecture dependent. * @author fwi * */ public interface Context { /** * Create an instruction decoder for the this context. * @return an instruction decoder matching the configuration of the context */ Decoder createInstructionDecoder(); /** * Set the current address of execution. * @param pointer the memory address of the current location */ void setInstructionPointer(long pointer); /** * Returns the memory address of the current location * @return the memory address of the current location */ long getInstructionPointer(); /** * Returns the default size of memory addresses in bytes * @return the default size of memory addresses in bytes */ int getDefaultAddressSize(); }
Java
package kianxali.decoder; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * This class describes the prefix tree that is used to parse * opcodes. * @author fwi * * @param <LeafType> the type of data in the leaves, architecture dependent */ public class DecodeTree<LeafType> { private class Node { public Map<Short, DecodeTree<LeafType>> subTrees; public Map<Short, List<LeafType>> leaves; public Node() { subTrees = new HashMap<>(); leaves = new HashMap<>(); } } private final Node node; /** * Creates a new and empty prefix tree */ public DecodeTree() { node = new Node(); } /** * Adds a sequence of bytes to the prefix tree * @param sequence the byte sequence to ad * @param leaf the leaf to add for this sequence */ public void addEntry(short[] sequence, LeafType leaf) { addEntry(sequence, 0, leaf); } /** * Returns whether this tree has any sub trees * @return true iff there are sub trees */ public boolean hasSubTrees() { return node.subTrees.size() != 0; } /** * Get the sub tree for a given byte * @param s the byte to dive into * @return the sub tree for this byte */ public DecodeTree<LeafType> getSubTree(short s) { return node.subTrees.get(s); } /** * Get a list of all sub trees * @return a list of all sub trees inside this node */ public Collection<DecodeTree<LeafType>> getSubTrees() { return node.subTrees.values(); } /** * Get a list of all leaves in this node for a given byte * @param s the byte to get the leaves for * @return the list of leaves matching this byte */ public List<LeafType> getLeaves(short s) { return node.leaves.get(s); } /** * Returns a set of bytes that this tree has leaves for * @return the set of bytes */ public Set<Short> getLeaveCodes() { return node.leaves.keySet(); } private void addEntry(short[] sequence, int index, LeafType leaf) { short s = sequence[index]; if(index < sequence.length - 1) { // non-leaf child DecodeTree<LeafType> subTree = node.subTrees.get(s); if(subTree == null) { subTree = new DecodeTree<LeafType>(); node.subTrees.put(s, subTree); } subTree.addEntry(sequence, index + 1, leaf); } else { // leaf List<LeafType> leaves = node.leaves.get(s); if(leaves == null) { leaves = new LinkedList<>(); node.leaves.put(s, leaves); } leaves.add(leaf); } } }
Java
package kianxali.decoder; /** * Specifies whether an operand is used as source or destination of an instruction * @author fwi * */ public enum UsageType { SOURCE, DEST; }
Java
/** * This package contains an XML parser that parses the x86 instruction set * from <a href='http://ref.x86asm.net/'>http://ref.x86asm.net/</a> and * stores all opcode syntaxes in a list that can be processed further. * The main class to do that is {@link kianxali.decoder.arch.x86.xml.XMLParserX86}. * */ package kianxali.decoder.arch.x86.xml;
Java
package kianxali.decoder.arch.x86.xml; /** * A group used to categorize an opcode semantically. * @author fwi * */ public enum OpcodeGroup { PREFIX, PREFIX_SEGREG, PREFIX_BRANCH, PREFIX_BRANCH_CONDITIONAL, PREFIX_FPU, PREFIX_FPU_CONTROL, PREFIX_STRING, // undocumented in the XML doc OBSOLETE, OBSOLETE_CONTROL, GENERAL, GENERAL_DATAMOVE, GENERAL_STACK, GENERAL_CONVERSION, GENERAL_ARITHMETIC, GENERAL_ARITHMETIC_BINARY, GENERAL_ARITHMETIC_DECIMAL, GENERAL_LOGICAL, GENERAL_SHIFTROT, GENERAL_BITMANIPULATION, GENERAL_BRANCH, GENERAL_BRANCH_CONDITIONAL, GENERAL_BREAK, GENERAL_STRING, // can use REP prefix GENERAL_IO, GENERAL_FLAGCONTROL, GENERAL_SEGREGMANIPULATION, GENERAL_CONTROL, SYSTEM, SYSTEM_BRANCH, SYSTEM_BRANCH_TRANSITIONAL, // obeys operand-size attribute FPU, FPU_DATAMOVE, FPU_ARITHMETIC, FPU_COMPARISON, FPU_TRANSCENDENTAL, FPU_LOADCONST, FPU_CONTROL, FPU_CONVERSION, FPUSIMDSTATE, MMX_DATAMOV, MMX_ARITHMETIC, MMX_COMPARISON, MMX_CONVERSION, MMX_LOGICAL, MMX_SHIFT, MMX_UNPACK, SSE1_SINGLE, // SIMD single precision floating point SSE1_SINGLE_DATAMOVE, SSE1_SINGLE_ARITHMETIC, SSE1_SINGLE_COMPARISON, SSE1_SINGLE_LOGICAL, SSE1_SINGLE_SHUFFLEUNPACK, SSE1_CONVERSION, SSE1_INT64, // SIMD on 64 bit integers SSE1_MXCSR, // MXCSR state management SSE1_CACHE, SSE1_PREFETCH, SSE1_INSTRUCTIONORDER, SSE2_DOUBLE, // packed and scalar double precision floats SSE2_DOUBLE_DATAMOVE, SSE2_DOUBLE_CONVERSION, SSE2_DOUBLE_ARITHMETIC, SSE2_DOUBLE_COMPARISON, SSE2_DOUBLE_LOGICAL, SSE2_DOUBLE_SHUFFLEUNPACK, SSE2_SINGLE, // packed single precision floats SSE2_INT128, // SIMD on 128 bit integers SSE2_INT128_DATAMOVE, SSE2_INT128_ARITHMETIC, SSE2_INT128_SHUFFLEUNPACK, SSE2_INT128_SHIFT, SSE2_INT128_COMPARISON, SSE2_INT128_CONVERSION, SSE2_INT128_LOGICAL, SSE2_CACHE, SSE2_INSTRUCTIONORDER, SSE3_FLOAT, // SIMD single precision float SSE3_FLOAT_DATAMOVE, SSE3_FLOAT_ARITHMETIC, SSE3_CACHE, SSE3_SYNC, SSSE3_INT, // SIMD integer SSE41_INT, // SIMD integer SSE41_INT_DATAMOVE, SSE41_INT_ARITHMETIC, SSE41_INT_COMPARISON, SSE41_INT_CONVERSION, SSE41_FLOAT, SSE41_FLOAT_DATAMOVE, SSE41_FLOAT_ARITHMETIC, SSE41_FLOAT_CONVERSION, SSE41_CACHE, SSE42_INT, // SIMD integer SSE42_INT_COMPARISON, SSE42_STRINGTEXT }
Java
package kianxali.decoder.arch.x86.xml; import java.io.FileReader; import java.io.IOException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Logger; import kianxali.decoder.UsageType; import kianxali.decoder.arch.x86.X86Mnemonic; import kianxali.decoder.arch.x86.X86CPU.ExecutionMode; import kianxali.decoder.arch.x86.X86CPU.InstructionSetExtension; import kianxali.decoder.arch.x86.X86CPU.Model; import kianxali.decoder.arch.x86.xml.OperandDesc.AddressType; import kianxali.decoder.arch.x86.xml.OperandDesc.DirectGroup; import kianxali.decoder.arch.x86.xml.OperandDesc.OperandType; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * Parses an XML document in the syntax from <a href='http://ref.x86asm.net/'>http://ref.x86asm.net/</a> * into a list of {@link OpcodeSyntax} entries. * A SAX parser is used to avoid having the whole DOM tree in memory. * * @author fwi * */ public class XMLParserX86 { private static final Logger LOG = Logger.getLogger("kianxali.decoder.arch.x86.xml"); private final List<OpcodeSyntax> syntaxes; // SAX parsing stuff to remember current state private Short currentOpcode; private OpcodeEntry currentEntry; private OpcodeSyntax currentSyntax; private OperandDesc currentOpDesc; private Short opcdExt; private Model inheritProcStart; private boolean inOneByte, inTwoByte, inSyntax, inMnem; private boolean inSrc, inDst, inA, inT, inOpcdExt, inGroup, inInstrExt; private boolean inProcStart, inProcEnd, in2ndOpcode, inPref, inBrief; /** * Constructs a new parser. Use {@link XMLParserX86#loadXML(String, String)} to load * the actual XML document. */ public XMLParserX86() { syntaxes = new LinkedList<>(); } /** * Loads the XML document describing the x86 instruction set. * When done, use {@link XMLParserX86#getSyntaxEntries()} to retrieve the result. * * @param xmlPath path to the XML document * @param dtdPath path to the DTD that defines the syntax of the XML document * @throws SAXException if there is a parse error * @throws IOException if one of the input files couldn't be read */ public void loadXML(String xmlPath, String dtdPath) throws SAXException, IOException { XMLReader xmlReader = XMLReaderFactory.createXMLReader(); FileReader reader = new FileReader(xmlPath); InputSource source = new InputSource(reader); source.setSystemId(dtdPath); xmlReader.setContentHandler(new ContentHandler() { public void setDocumentLocator(Locator locator) { } public void startPrefixMapping(String prefix, String uri) throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { } public void skippedEntity(String name) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } public void startDocument() throws SAXException { } public void endDocument() throws SAXException { } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { onElementStart(localName, atts); } public void characters(char[] ch, int start, int length) throws SAXException { onElementText(new String(ch, start, length)); } public void endElement(String uri, String localName, String qName) throws SAXException { onElementEnd(localName); } }); xmlReader.parse(source); reader.close(); } /** * Returns a list of all the opcode syntaxes defined in the XML document. * @return the syntax list as an unmodifiable list */ public List<OpcodeSyntax> getSyntaxEntries() { return Collections.unmodifiableList(syntaxes); } private void onElementStart(String name, Attributes atts) { switch(name) { case "x86reference": break; case "one-byte": inOneByte = true; inTwoByte = false; break; case "two-byte": inOneByte = false; inTwoByte = true; break; case "pri_opcd": currentOpcode = Short.parseShort(atts.getValue("value"), 16); break; case "entry": currentEntry = new OpcodeEntry(); currentEntry.opcode = currentOpcode; if(!inOneByte && inTwoByte) { currentEntry.twoByte = inTwoByte; } fillEntry(currentEntry, atts); break; case "opcd_ext": inOpcdExt = true; break; case "syntax": if(opcdExt != null) { currentSyntax = new OpcodeSyntax(currentEntry, opcdExt); } else { currentSyntax = new OpcodeSyntax(currentEntry); } String mod = atts.getValue("mod"); if("mem".equals(mod)) { currentSyntax.setModRMMustMem(true); } else if("nomem".equals(mod)) { currentSyntax.setModRMMustReg(true); } inSyntax = true; break; case "mnem": // TODO: attribute sug: yes iff mnem is only suggested and no official if(inSyntax) { inMnem = true; } break; case "src": if(inSyntax) { currentOpDesc = new OperandDesc(); currentOpDesc.usageType = UsageType.SOURCE; parseOperandAtts(currentOpDesc, atts); inSrc = true; } break; case "dst": if(inSyntax) { currentOpDesc = new OperandDesc(); currentOpDesc.usageType = UsageType.DEST; parseOperandAtts(currentOpDesc, atts); inDst = true; } break; case "a": if(inSrc || inDst) { // addressing mode inA = true; } break; case "t": if(inSrc || inDst) { // operand type inT = true; } break; case "sup": // superscript in <brief>, e.g. for x^2 case "sub": // subscript in <brief>, e.g. for log_x break; case "grp1": case "grp2": case "grp3": inGroup = true; break; case "instr_ext": inInstrExt = true; break; case "proc_start": // attributes "post" and "lat_step": unknown purpose inProcStart = true; break; case "proc_end": inProcEnd = true; break; case "sec_opcd": // attribute escape: yes can be ignored because we already know if opcode is 2bytes in2ndOpcode = true; break; case "pref": inPref = true; break; case "brief": inBrief = true; break; case "def_f": case "f_vals": case "test_f": case "modif_f": case "undef_f": case "def_f_fpu": case "f_vals_fpu": case "modif_f_fpu": case "undef_f_fpu": // TODO: flag support break; case "note": case "det": case "gen_note": case "gen_notes": case "ring_note": case "ring_notes": // TODO: documentation break; default: System.err.println("Unhandled tag: " + name); } } private void onElementText(String val) throws SAXException { if(inMnem) { X86Mnemonic mnem = X86Mnemonic.valueOf(val.replace('.', '_')); if(mnem == null) { System.err.println("Unknown mnemonic: " + val); } else { currentSyntax.setMnemonic(mnem); } } else if(inA) { currentOpDesc.adrType = parseAddressType(val); } else if(inT) { currentOpDesc.operType = parseOperandType(val); } else if(inSrc) { if(!currentOpDesc.indirect && val.trim().length() > 0) { currentOpDesc.hardcoded = val.trim(); } } else if(inDst) { if(!currentOpDesc.indirect && val.trim().length() > 0) { currentOpDesc.hardcoded = val.trim(); } } else if(inProcStart) { Model proc = parseProcessor(val); if(currentEntry != null) { currentEntry.setStartProcessor(proc); } else { inheritProcStart = proc; } } else if(inProcEnd) { currentEntry.setEndProcessor(parseProcessor(val)); } else if(inOpcdExt) { opcdExt = Short.parseShort(val); } else if(inGroup) { currentEntry.addOpcodeGroup(parseOpcodeGroup(currentEntry.instrExt, currentEntry.groups, val)); } else if(inInstrExt) { currentEntry.instrExt = parseInstrExt(val); } else if(in2ndOpcode) { currentEntry.secondOpcode = Short.parseShort(val, 16); } else if(inPref) { currentEntry.prefix = Short.parseShort(val, 16); } else if(inBrief) { currentEntry.briefDescription = val; } } private void onElementEnd(String name) throws SAXException { switch(name) { case "one-byte": inTwoByte = false; break; case "two-byte": inOneByte = false; break; case "pri_opcd": inheritProcStart = null; currentOpcode = null; break; case "syntax": currentEntry.addSyntax(currentSyntax); syntaxes.add(currentSyntax); currentSyntax = null; inSyntax = false; break; case "proc_start": inProcStart = false; break; case "proc_end": inProcEnd = false; break; case "opcd_ext": inOpcdExt = false; break; case "entry": if(currentEntry.startModel == null) { if(inheritProcStart != null) { currentEntry.setStartProcessor(inheritProcStart); } } currentEntry = null; opcdExt = null; break; case "sec_opcd": in2ndOpcode = false; break; case "pref": inPref = false; break; case "mnem": inMnem = false; break; case "src": inSrc = false; // fall-through case "dst": currentSyntax.addOperand(currentOpDesc); if(currentOpDesc.operType == null && !currentOpDesc.indirect) { currentOpDesc.operType = chooseOpType(); if(currentOpDesc.operType == null) { LOG.warning("No opType for " + currentSyntax); } } else if(currentOpDesc.adrType == AddressType.MOD_RM_MMX && currentOpDesc.operType == OperandType.DWORD) { // TODO bug in xml? currentOpDesc.operType = OperandType.QWORD; } currentOpDesc = null; inDst = false; break; case "a": inA = false; break; case "t": inT = false; break; case "grp1": case "grp2": case "grp3": inGroup = false; break; case "instr_ext": inInstrExt = false; break; case "brief": inBrief = false; break; default: break; } } private void fillEntry(OpcodeEntry currentModeOpts, Attributes atts) { String modeStr = atts.getValue("mode"); if(modeStr == null) { modeStr = "r"; } switch(modeStr) { case "r": currentModeOpts.mode = ExecutionMode.REAL; break; case "p": currentModeOpts.mode = ExecutionMode.PROTECTED; break; case "e": currentModeOpts.mode = ExecutionMode.LONG; break; case "s": currentModeOpts.mode = ExecutionMode.SMM; break; default: throw new UnsupportedOperationException("invalid mode: " + modeStr); } if("1".equals(atts.getValue("direction"))) { currentModeOpts.direction = true; } if("1".equals(atts.getValue("sign-ext"))) { currentModeOpts.sgnExt = true; } if("1".equals(atts.getValue("op_size"))) { currentModeOpts.opSize = true; } if("yes".equals(atts.getValue("r"))) { currentModeOpts.modRM = true; } if("yes".equals(atts.getValue("lock"))) { currentModeOpts.lock = true; } String memFormat = atts.getValue("mem_format"); if(memFormat != null) { currentModeOpts.memFormat = Integer.parseInt(memFormat); } String attr = atts.getValue("attr"); if(attr == null) { attr = ""; } if(attr.contains("invd")) { currentModeOpts.invalid = true; } if(attr.contains("undef")) { currentModeOpts.undefined = true; } if("yes".equals(atts.getValue("particular"))) { currentModeOpts.particular = true; } String tttnStr = atts.getValue("tttn"); if(tttnStr != null) { currentModeOpts.tttn = Byte.parseByte(tttnStr, 2); } } private AddressType parseAddressType(String val) { switch(val) { case "A": return AddressType.DIRECT; case "BA": return AddressType.DS_EAX_RAX; case "BB": return AddressType.DS_EBX_AL_RBX; case "BD": return AddressType.DS_EDI_RDI; case "C": return AddressType.MOD_RM_R_CTRL; case "D": return AddressType.MOD_RM_R_DEBUG; case "E": return AddressType.MOD_RM_M; case "F": return AddressType.FLAGS; case "ES": return AddressType.MOD_RM_M_FPU; case "EST": return AddressType.MOD_RM_M_FPU_REG; case "G": return AddressType.MOD_RM_R; case "H": return AddressType.MOD_RM_M_FORCE_GEN; case "I": return AddressType.IMMEDIATE; case "J": return AddressType.RELATIVE; case "M": return AddressType.MOD_RM_MUST_M; case "N": return AddressType.MOD_RM_M_MMX; case "O": return AddressType.OFFSET; case "P": return AddressType.MOD_RM_R_MMX; case "Q": return AddressType.MOD_RM_MMX; case "R": return AddressType.MOD_RM_R_FORCE_GEN; case "S": return AddressType.MOD_RM_R_SEG; case "S2": return AddressType.SEGMENT2; case "S30": return AddressType.SEGMENT30; case "S33": return AddressType.SEGMENT33; case "SC": return AddressType.STACK; case "T": return AddressType.MOD_RM_R_TEST; case "U": return AddressType.MOD_RM_M_XMM_REG; case "V": return AddressType.MOD_RM_R_XMM; case "W": return AddressType.MOD_RM_XMM; case "X": return AddressType.DS_ESI_RSI; case "Y": return AddressType.ES_EDI_RDI; case "Z": return AddressType.LEAST_REG; default: System.err.println("Unknown address type: " + val); return null; } } private OperandType parseOperandType(String val) { switch(val) { case "a": return OperandType.TWO_INDICES; case "b": return OperandType.BYTE; case "bcd": return OperandType.BCD; case "bs": return OperandType.BYTE_SGN; case "bss": return OperandType.BYTE_STACK; case "d": return OperandType.DWORD; case "da": return OperandType.DWORD_ADR; case "di": return OperandType.DWORD_INT_FPU; case "do": return OperandType.DWORD_OPS; case "dr": return OperandType.DOUBLE_FPU; case "dq": return OperandType.DQWORD; case "dqa": return OperandType.DWORD_QWORD_ADR; case "dq ": return OperandType.DQWORD; case "dqp": return OperandType.DWORD_QWORD; case "e": return OperandType.FPU_ENV; case "er": return OperandType.REAL_EXT_FPU; case "p": return OperandType.POINTER; case "pi": return OperandType.QWORD_MMX; case "pd": return OperandType.DOUBLE_128; case "ptp": return OperandType.POINTER_REX; case "ps": return OperandType.SINGLE_128; case "psq": return OperandType.SINGLE_64; case "q": return OperandType.QWORD; case "qa": return OperandType.QWORD_ADR; case "qi": return OperandType.QWORD_FPU; case "qs": return OperandType.QWORD_STACK; case "qp": return OperandType.QWORD_REX; case "s": return OperandType.PSEUDO_DESC; case "sr": return OperandType.REAL_SINGLE_FPU; case "st": return OperandType.FPU_STATE; case "sd": return OperandType.SCALAR_DOUBLE; case "ss": return OperandType.SCALAR_SINGLE; case "stx": return OperandType.FPU_SIMD_STATE; case "vds": return OperandType.WORD_DWORD_S64; case "vq": return OperandType.QWORD_WORD; case "vqp": return OperandType.WORD_DWORD_64; case "v": return OperandType.WORD_DWORD; case "va": return OperandType.WORD_DWORD_ADR; case "vs": return OperandType.WORD_DWORD_STACK; case "w": return OperandType.WORD; case "wa": return OperandType.WORD_ADR; case "ws": return OperandType.WORD_STACK; case "wo": return OperandType.WORD_OPS; case "wi": return OperandType.WORD_FPU; default: System.err.println("Unknown operand type: " + val); return null; } } private Model parseProcessor(String val) { switch(val) { case "00": return Model.I8086; case "01": return Model.I80186; case "02": return Model.I80286; case "03": return Model.I80386; case "04": return Model.I80486; case "05": return Model.PENTIUM; case "06": return Model.PENTIUM_MMX; case "07": return Model.PENTIUM_MMX; case "08": return Model.PENTIUM_II; case "09": return Model.PENTIUM_III; case "10": return Model.PENTIUM_IV; case "11": return Model.CORE_1; case "12": return Model.CORE_2; case "13": return Model.CORE_I7; case "99": return Model.ITANIUM; default: System.err.println("Unknown processor entry: " + val); return null; } } private InstructionSetExtension parseInstrExt(String val) { switch(val) { case "mmx": return InstructionSetExtension.MMX; case "sse1": return InstructionSetExtension.SSE_1; case "sse2": return InstructionSetExtension.SSE_2; case "sse3": return InstructionSetExtension.SSE_3; case "sse41": return InstructionSetExtension.SSE_4_1; case "sse42": return InstructionSetExtension.SSE_4_2; case "ssse3": return InstructionSetExtension.SSSE_3; case "vmx": return InstructionSetExtension.VMX; case "smx": return InstructionSetExtension.SMX; default: System.err.println("Unhandled instruction extension: " + val); return null; } } private OpcodeGroup parseOpcodeGroup(InstructionSetExtension ext, Set<OpcodeGroup> groups, String group) { switch (group) { case "prefix": return OpcodeGroup.PREFIX; case "segreg": if(groups.contains(OpcodeGroup.PREFIX)) { return OpcodeGroup.PREFIX_SEGREG; } else if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_SEGREGMANIPULATION; } else { System.err.println("invalid top group: " + group); return null; } case "arith": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_ARITHMETIC; } else if(groups.contains(OpcodeGroup.FPU)) { return OpcodeGroup.FPU_ARITHMETIC; } else if(groups.contains(OpcodeGroup.SSE1_SINGLE)) { return OpcodeGroup.SSE1_SINGLE_ARITHMETIC; } else if(groups.contains(OpcodeGroup.SSE2_DOUBLE)) { return OpcodeGroup.SSE2_DOUBLE_ARITHMETIC; } else if(groups.contains(OpcodeGroup.SSE2_INT128)) { return OpcodeGroup.SSE2_INT128_ARITHMETIC; } else if(groups.contains(OpcodeGroup.SSE3_FLOAT)) { return OpcodeGroup.SSE3_FLOAT_ARITHMETIC; } else if(groups.contains(OpcodeGroup.SSE41_INT)) { return OpcodeGroup.SSE41_INT_ARITHMETIC; } else if(groups.contains(OpcodeGroup.SSE41_FLOAT)) { return OpcodeGroup.SSE41_FLOAT_ARITHMETIC; } else if(ext == InstructionSetExtension.MMX) { return OpcodeGroup.MMX_ARITHMETIC; } else { System.err.println("invalid top group: " + group); return null; } case "simdint": if(ext == InstructionSetExtension.SSE_1) { return OpcodeGroup.SSE1_INT64; } else if(ext == InstructionSetExtension.SSE_2) { return OpcodeGroup.SSE2_INT128; } else if(ext == InstructionSetExtension.SSSE_3) { return OpcodeGroup.SSSE3_INT; } else if(ext == InstructionSetExtension.SSE_4_1) { return OpcodeGroup.SSE41_INT; } else if(ext == InstructionSetExtension.SSE_4_2) { return OpcodeGroup.SSE42_INT; } else { System.err.println("invalid top group: " + group); return null; } case "shift": if(groups.contains(OpcodeGroup.SSE2_INT128)) { return OpcodeGroup.SSE2_INT128_SHIFT; } else if(ext == InstructionSetExtension.MMX) { return OpcodeGroup.MMX_SHIFT; } else if(ext == InstructionSetExtension.SSE_2) { // TODO: verify that this is correct return OpcodeGroup.SSE2_INT128_SHIFT; } else { System.err.println("invalid top group: " + group); return null; } case "cachect": if(ext == InstructionSetExtension.SSE_1) { return OpcodeGroup.SSE1_CACHE; } else if(ext == InstructionSetExtension.SSE_2) { return OpcodeGroup.SSE2_CACHE; } else if(ext == InstructionSetExtension.SSE_3) { return OpcodeGroup.SSE3_CACHE; } else if(ext == InstructionSetExtension.SSE_4_1) { return OpcodeGroup.SSE41_CACHE; } else { System.err.println("invalid top group: " + group); return null; } case "logical": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_LOGICAL; } else if(groups.contains(OpcodeGroup.SSE1_SINGLE)) { return OpcodeGroup.SSE1_SINGLE_LOGICAL; } else if(groups.contains(OpcodeGroup.SSE2_DOUBLE)) { return OpcodeGroup.SSE2_DOUBLE_LOGICAL; } else if(groups.contains(OpcodeGroup.SSE2_INT128)) { return OpcodeGroup.SSE2_INT128_LOGICAL; } else if(ext == InstructionSetExtension.MMX) { return OpcodeGroup.MMX_LOGICAL; } else { System.err.println("invalid top group: " + group); return null; } case "conver": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_CONVERSION; } else if(groups.contains(OpcodeGroup.FPU)) { return OpcodeGroup.FPU_CONVERSION; } else if(ext == InstructionSetExtension.MMX) { return OpcodeGroup.MMX_CONVERSION; } else if(ext == InstructionSetExtension.SSE_1) { return OpcodeGroup.SSE1_CONVERSION; } else if(groups.contains(OpcodeGroup.SSE2_DOUBLE)) { return OpcodeGroup.SSE2_DOUBLE_CONVERSION; } else if(groups.contains(OpcodeGroup.SSE2_INT128)) { return OpcodeGroup.SSE2_INT128_CONVERSION; } else if(groups.contains(OpcodeGroup.SSE41_INT)) { return OpcodeGroup.SSE41_INT_CONVERSION; } else if(groups.contains(OpcodeGroup.SSE41_FLOAT)) { return OpcodeGroup.SSE41_FLOAT_CONVERSION; } else { System.err.println("invalid top group: " + group); return null; } case "pcksclr": if(ext == InstructionSetExtension.SSE_2) { return OpcodeGroup.SSE2_DOUBLE; } else { System.err.println("invalid top group: " + group); return null; } case "datamov": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_DATAMOVE; } else if(groups.contains(OpcodeGroup.FPU)) { return OpcodeGroup.FPU_DATAMOVE; } else if(groups.contains(OpcodeGroup.SSE1_SINGLE)) { return OpcodeGroup.SSE1_SINGLE_DATAMOVE; } else if(groups.contains(OpcodeGroup.SSE2_DOUBLE)) { return OpcodeGroup.SSE2_DOUBLE_DATAMOVE; } else if(groups.contains(OpcodeGroup.SSE2_INT128)) { return OpcodeGroup.SSE2_INT128_DATAMOVE; } else if(groups.contains(OpcodeGroup.SSE3_FLOAT)) { return OpcodeGroup.SSE3_FLOAT_DATAMOVE; } else if(groups.contains(OpcodeGroup.SSE41_INT)) { return OpcodeGroup.SSE41_INT_DATAMOVE; } else if(groups.contains(OpcodeGroup.SSE41_FLOAT)) { return OpcodeGroup.SSE41_FLOAT_DATAMOVE; } else if(ext == InstructionSetExtension.MMX) { return OpcodeGroup.MMX_DATAMOV; } else { System.err.println("invalid top group: " + group); return null; } case "binary": if(groups.contains(OpcodeGroup.GENERAL_ARITHMETIC)) { return OpcodeGroup.GENERAL_ARITHMETIC_BINARY; } else { System.err.println("invalid top group: " + group); return null; } case "gen": return OpcodeGroup.GENERAL; case "shunpck": if(groups.contains(OpcodeGroup.SSE1_SINGLE)) { return OpcodeGroup.SSE1_SINGLE_SHUFFLEUNPACK; } else if(groups.contains(OpcodeGroup.SSE2_DOUBLE)) { return OpcodeGroup.SSE2_DOUBLE_SHUFFLEUNPACK; } else if(groups.contains(OpcodeGroup.SSE2_INT128)) { return OpcodeGroup.SSE2_INT128_SHUFFLEUNPACK; } else { System.err.println("invalid top group: " + group); return null; } case "simdfp": if(ext == InstructionSetExtension.SSE_1) { return OpcodeGroup.SSE1_SINGLE; } else if(ext == InstructionSetExtension.SSE_3) { return OpcodeGroup.SSE3_FLOAT; } else if(ext == InstructionSetExtension.SSE_4_1) { return OpcodeGroup.SSE41_FLOAT; } else { System.err.println("invalid top group: " + group); return null; } case "compar": if(groups.contains(OpcodeGroup.FPU)) { return OpcodeGroup.FPU_COMPARISON; } else if(groups.contains(OpcodeGroup.SSE1_SINGLE)) { return OpcodeGroup.SSE1_SINGLE_COMPARISON; } else if(groups.contains(OpcodeGroup.SSE2_DOUBLE)) { return OpcodeGroup.SSE2_DOUBLE_COMPARISON; } else if(groups.contains(OpcodeGroup.SSE2_INT128)) { return OpcodeGroup.SSE2_INT128_COMPARISON; } else if(groups.contains(OpcodeGroup.SSE41_INT)) { return OpcodeGroup.SSE41_INT_COMPARISON; } else if(groups.contains(OpcodeGroup.SSE42_INT)) { return OpcodeGroup.SSE42_INT_COMPARISON; } else if(ext == InstructionSetExtension.MMX) { return OpcodeGroup.MMX_COMPARISON; } else { System.err.println("invalid top group: " + group); return null; } case "bit": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_BITMANIPULATION; } else { System.err.println("invalid top group: " + group); return null; } case "system": return OpcodeGroup.SYSTEM; case "branch": if(groups.contains(OpcodeGroup.PREFIX)) { return OpcodeGroup.PREFIX_BRANCH; } else if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_BRANCH; } else if(groups.contains(OpcodeGroup.SYSTEM)) { return OpcodeGroup.SYSTEM_BRANCH; } else { System.err.println("invalid top group: " + group); return null; } case "control": if(groups.contains(OpcodeGroup.PREFIX_FPU)) { return OpcodeGroup.PREFIX_FPU_CONTROL; } else if(groups.contains(OpcodeGroup.OBSOLETE)) { return OpcodeGroup.OBSOLETE_CONTROL; } else if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_CONTROL; } else if(groups.contains(OpcodeGroup.FPU)) { return OpcodeGroup.FPU_CONTROL; } else { System.err.println("invalid top group: " + group); return null; } case "stack": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_STACK; } else { System.err.println("invalid top group: " + group); return null; } case "order": if(ext == InstructionSetExtension.SSE_1) { return OpcodeGroup.SSE1_INSTRUCTIONORDER; } else if(ext == InstructionSetExtension.SSE_2) { return OpcodeGroup.SSE2_INSTRUCTIONORDER; } else { System.err.println("invalid top group: " + group); return null; } case "sm": return OpcodeGroup.FPUSIMDSTATE; case "mxcsrsm": if(ext == InstructionSetExtension.SSE_1) { return OpcodeGroup.SSE1_MXCSR; } else { System.err.println("invalid top group: " + group); return null; } case "shftrot": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_SHIFTROT; } else { System.err.println("invalid top group: " + group); return null; } case "cond": if(groups.contains(OpcodeGroup.GENERAL_BRANCH)) { return OpcodeGroup.GENERAL_BRANCH_CONDITIONAL; } else if(groups.contains(OpcodeGroup.PREFIX_BRANCH)) { return OpcodeGroup.PREFIX_BRANCH_CONDITIONAL; } else { System.err.println("invalid top group: " + group); return null; } case "unpack": if(ext == InstructionSetExtension.MMX) { return OpcodeGroup.MMX_UNPACK; } else { System.err.println("invalid top group: " + group); return null; } case "x87fpu": if(groups.contains(OpcodeGroup.PREFIX)) { return OpcodeGroup.PREFIX_FPU; } else { return OpcodeGroup.FPU; } case "strtxt": if(ext == InstructionSetExtension.SSE_4_2) { return OpcodeGroup.SSE42_STRINGTEXT; } else { System.err.println("invalid top group: " + group); return null; } case "pcksp": if(ext == InstructionSetExtension.SSE_2) { return OpcodeGroup.SSE2_SINGLE; } else { System.err.println("invalid top group: " + group); return null; } case "fetch": if(ext == InstructionSetExtension.SSE_1) { return OpcodeGroup.SSE1_PREFETCH; } else { System.err.println("invalid top group: " + group); return null; } case "trans": if(groups.contains(OpcodeGroup.SYSTEM_BRANCH)) { return OpcodeGroup.SYSTEM_BRANCH_TRANSITIONAL; } else if(groups.contains(OpcodeGroup.FPU)) { return OpcodeGroup.FPU_TRANSCENDENTAL; } else { System.err.println("invalid top group: " + group); return null; } case "flgctrl": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_FLAGCONTROL; } else { System.err.println("invalid top group: " + group); return null; } case "sync": if(ext == InstructionSetExtension.SSE_3) { return OpcodeGroup.SSE3_CACHE; } else { System.err.println("invalid top group: " + group); return null; } case "string": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_STRING; } else if(groups.contains(OpcodeGroup.PREFIX)) { return OpcodeGroup.PREFIX_STRING; } else { System.err.println("invalid top group: " + group); return null; } case "inout": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_IO; } else { System.err.println("invalid top group: " + group); return null; } case "break": if(groups.contains(OpcodeGroup.GENERAL)) { return OpcodeGroup.GENERAL_BREAK; } else { System.err.println("invalid top group: " + group); return null; } case "decimal": if(groups.contains(OpcodeGroup.GENERAL_ARITHMETIC)) { return OpcodeGroup.GENERAL_ARITHMETIC_DECIMAL; } else { System.err.println("invalid top group: " + group); return null; } case "obsol": return OpcodeGroup.OBSOLETE; case "ldconst": if(groups.contains(OpcodeGroup.FPU)) { return OpcodeGroup.FPU_LOADCONST; } else { System.err.println("invalid top group: " + group); return null; } default: System.err.println("Unknown opcode group: " + group); return null; } } private void parseOperandAtts(OperandDesc opDesc, Attributes atts) { boolean hasGroup = false; for(int i = 0; i < atts.getLength(); i++) { String key = atts.getLocalName(i); String val = atts.getValue(i); switch(key) { case "group": hasGroup = true; switch(val) { case "gen": opDesc.directGroup = DirectGroup.GENERIC; break; case "seg": opDesc.directGroup = DirectGroup.SEGMENT; break; case "x87fpu": opDesc.directGroup = DirectGroup.X87FPU; break; case "mmx": opDesc.directGroup = DirectGroup.MMX; break; case "xmm": opDesc.directGroup = DirectGroup.XMM; break; case "msr": opDesc.directGroup = DirectGroup.MSR; break; case "systabp": opDesc.directGroup = DirectGroup.SYSTABP; break; case "ctrl": opDesc.directGroup = DirectGroup.CONTROL; break; case "debug": opDesc.directGroup = DirectGroup.DEBUG; break; case "xcr": opDesc.directGroup = DirectGroup.XCR; break; default: System.err.println("unknown group: " + val); } break; case "type": opDesc.operType = parseOperandType(val); break; case "displayed": if(val.equals("no")) { opDesc.indirect = true; } break; case "nr": opDesc.numForGroup = Long.parseLong(val, 16); break; case "address": opDesc.adrType = parseAddressType(val); break; case "depend": if(val.equals("no")) { opDesc.depends = false; } else { // yes is default if not given opDesc.depends = true; } break; default: System.err.println("Unknown key: " + key); } } if(opDesc.adrType == null && hasGroup) { opDesc.adrType = AddressType.GROUP; } } private OperandType chooseOpType() { // TODO: not sure if this is correct at all... if(currentOpDesc.directGroup == DirectGroup.X87FPU) { return OperandType.REAL_EXT_FPU; } switch(currentOpDesc.adrType) { case IMMEDIATE: case MOD_RM_M: case MOD_RM_R: case MOD_RM_MUST_M: return OperandType.WORD_DWORD_64; case MOD_RM_M_FPU_REG: return OperandType.REAL_EXT_FPU; default: return null; } } }
Java
package kianxali.decoder.arch.x86.xml; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import kianxali.decoder.arch.x86.X86CPU.ExecutionMode; import kianxali.decoder.arch.x86.X86CPU.InstructionSetExtension; import kianxali.decoder.arch.x86.X86CPU.Model; /** * An x86 opcode can have a syntax depending on the current CPU mode. * This class stores the information that is shared across all different * syntaxes. * * @author fwi * */ public class OpcodeEntry { /** The prefix that must be present for this opcode (optional). * Note that it doesn't have to be directly before the opcode */ public Short prefix; /** whether the opcode is a two-byte one, e.g. needs 0F directly before it */ public boolean twoByte; /** the actual opcode byte */ public short opcode; /** A byte that must be immediately followed by the opcode */ public Short secondOpcode; /** the mode where this opcode is defined */ public ExecutionMode mode; /** whether the opcode always needs a ModR/M byte. false doesn't imply there won't be one */ public boolean modRM; /** If the opcode is not part of the basic x86 opcodes, * the instruction set extension is stored here */ public InstructionSetExtension instrExt; /** A brief description of what this opcode does */ public String briefDescription; /** groups that further describe this opcode */ public final Set<OpcodeGroup> groups; // not so important stuff coming from the XML document public boolean invalid, undefined; public boolean direction; public boolean sgnExt; public boolean opSize; public boolean lock; public boolean particular; public byte tttn; private final List<OpcodeSyntax> syntaxes; // models where the opcode was first and last supported Model startModel, lastModel; public Integer memFormat; OpcodeEntry() { this.groups = new HashSet<>(); this.syntaxes = new ArrayList<>(4); } void setStartProcessor(Model p) { this.startModel = p; } /** * Get the CPU model that introduced this opcode, * i.e. where it was first supported. * @return the first CPU model supporting this opcode. Never null. */ public Model getStartModel() { if(startModel != null) { return startModel; } else { return Model.I8086; } } void setEndProcessor(Model p) { this.lastModel = p; } /** * Get the latest CPU model that supports this opcode. * @return the latest CPU model supporting this opcode. * {@link Model#ANY} iff not obsolete. */ public Model getLastModel() { if(lastModel != null) { return lastModel; } else { return Model.ANY; } } /** * Checks whether this opcode is supported on a specific CPU model * in a specific execution mode. * @param p the CPU model to check for * @param pMode the execution mode to check for * @return true if the opcode is supported, false if not */ public boolean isSupportedOn(Model p, ExecutionMode pMode) { Model compare = p; if(p == Model.ANY) { compare = Model.CORE_I7; } Model last = getLastModel(); if(last.ordinal() < compare.ordinal()) { return false; } if(mode.ordinal() > pMode.ordinal()) { return false; } return true; } void addOpcodeGroup(OpcodeGroup group) { groups.add(group); } /** * Checks whether this opcode belongs to a certain group * @param group the group to check for * @return true if the opcode is part of the group, false otherwise */ public boolean belongsTo(OpcodeGroup group) { return groups.contains(group); } void addSyntax(OpcodeSyntax syntax) { syntaxes.add(syntax); } }
Java
package kianxali.decoder.arch.x86.xml; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import kianxali.decoder.arch.x86.X86Mnemonic; import kianxali.decoder.arch.x86.xml.OperandDesc.AddressType; /** * Represents the syntax of an opcode, i.e. the number and * format of its operands. * @author fwi * */ public class OpcodeSyntax { private final OpcodeEntry entry; // syntax belongs to this entry private final List<OperandDesc> operands; private Short extension; private boolean modRMMustMem, modRMMustReg; private X86Mnemonic mnemonic; { this.operands = new ArrayList<>(4); } OpcodeSyntax(OpcodeEntry entry) { this.entry = entry; } OpcodeSyntax(OpcodeEntry entry, short extension) { this.entry = entry; this.extension = extension; } void setModRMMustMem(boolean must) { this.modRMMustMem = must; } void setModRMMustReg(boolean must) { this.modRMMustReg = must; } public boolean isModRMMustMem() { return modRMMustMem; } public boolean isModRMMustReg() { return modRMMustReg; } public OpcodeEntry getOpcodeEntry() { return entry; } /** * Returns whether the opcode is an extension of another one, * in which case {@link OpcodeSyntax#getExtension()} will * return the actual extension number. * @return true iff the opcode extends another one */ public boolean isExtended() { return extension != null; } /** * Returns the extension number if this opcode extends * another one * @return the extension number of this opcode or null if not extending */ public Short getExtension() { return extension; } void addOperand(OperandDesc opDesc) { operands.add(opDesc); } void setMnemonic(X86Mnemonic mnemonic) { this.mnemonic = mnemonic; } /** * Returns the mnemonic of this opcode * @return this opcode's mnemonic. Can be null, e.g. when used on a prefix */ public X86Mnemonic getMnemonic() { return mnemonic; } /** * Returns whether this opcode has a register encoded in the opcode * byte. Use {@link OpcodeSyntax#getEncodedRegisterRelativeIndex()} to get * the position of the byte. * @return true iff the opcode byte encodes a register in the least 3 bit */ public boolean hasEncodedRegister() { for(OperandDesc o : operands) { if(o.adrType == AddressType.LEAST_REG) { return true; } } return false; } /** * Returns the operands of this opcode. * @return the operands as an unmodifable list, never null */ public List<OperandDesc> getOperands() { return Collections.unmodifiableList(operands); } // negative from end of opcode /** * If the opcode byte encodes a register, this method * returns the index from the end of the opcode that * encodes the register. * @return the index from the end of the opcode bytes that encodes a register */ public int getEncodedRegisterRelativeIndex() { int pos = 0; if(entry.secondOpcode != null) { pos = 1; } return pos; } /** * Returns the full opcode prefix (including the opcode bytes, * but excluding the operand bytes) for this opcode. * If the opcode has a mandatory prefix byte, it will not be * included here. * @return the bytes that make up this opcode, excluding mandatory prefix */ public short[] getPrefix() { short[] res = new short[4]; int i = 0; // if(entry.prefix != null) { // res[i++] = entry.prefix; // } if(entry.twoByte) { res[i++] = 0x0F; } res[i++] = entry.opcode; if(entry.secondOpcode != null) { res[i++] = entry.secondOpcode; } return Arrays.copyOf(res, i); } /** * Returns a hex string representation of the full opcode bytes, * including mandatory prefixes but excluding operands. * @return a hex string representing this opcode */ public String getPrefixAsHexString() { short[] prefix = getPrefix(); StringBuilder res = new StringBuilder(); if(entry.prefix != null) { res.append(String.format("%02X", entry.prefix)); } for(short b : prefix) { res.append(String.format("%02X", b)); } return res.toString(); } @Override public String toString() { StringBuilder res = new StringBuilder(); res.append(String.format("<syntax mode=%s opcode=%s mnemonic=%s", entry.mode, getPrefixAsHexString(), mnemonic)); for(int i = 0; i < operands.size(); i++) { res.append(String.format(" op%d=%s", i + 1, operands.get(i).toString())); } res.append(">"); return res.toString(); } }
Java
package kianxali.decoder.arch.x86.xml; import kianxali.decoder.UsageType; /** * This class describes an opcode's operands. * Each operand has an operand type specifying the width of the operand * and an address type specifying how this operand is addressed (encoded). * @author fwi * */ public class OperandDesc { /** * Describes how an operand can be encoded in an opcode. * @author fwi * */ public enum AddressType { DIRECT, // absolute address of adressType coded after opcode MOD_RM_M, // modRM.mem MOD_RM_M_FPU, // modRM.mem but use FPU registers when not mem MOD_RM_M_FPU_REG, // modRM.mem must be mode 3 with FPU reg MOD_RM_R, // modRM.reg MOD_RM_R_CTRL, // modRM.reg selects control register MOD_RM_R_DEBUG, // modRM.reg selects debug register MOD_RM_R_TEST, // modRM.reg selects test register MOD_RM_R_SEG, // modRM.reg as segment register MOD_RM_M_FORCE_GEN, // to be checked: modRM.mem regardless of mode (implementation not checked yet) MOD_RM_MUST_M, // to be checked: modRM.mem regardless of mode (implementation not checked yet) MOD_RM_R_FORCE_GEN, // to be checked: modRM.reg regardless of mode (implementation not checked yet) MOD_RM_XMM, // modRM as XMM MOD_RM_R_XMM, // modRM.reg as XMM MOD_RM_M_XMM_REG, // modRM.mem as XMM IMMEDIATE, // immediate coded after opcode RELATIVE, // relative address coded after opcode MOD_RM_MMX, // modRM.reg or modRM.mem as MMX (implementation not checked yet) MOD_RM_R_MMX, // modRM.reg as MMX register MOD_RM_M_MMX, // modRM.mem pointing to MMX qword / reg OFFSET, // offset coded after opcode LEAST_REG, // least 3 bits of opcode (!) select general register GROUP, // indirectly given by instruction -> look at DirectGroup STACK, // by group so it fits on stack SEGMENT2, // by group: two bits of index three select segment SEGMENT30, // by group: least three bits select segment SEGMENT33, // by group: three bits at index three select segment FLAGS, // by group: rFLAGS register ES_EDI_RDI, // by group: memory through ES:EDI or RDI DS_ESI_RSI, // by group: memory through DS:ESI or RSI DS_EAX_RAX, // by group: memory through DS:EAX or RAX DS_EBX_AL_RBX, // by group: memory through DS:EBX+AL or RBX+AL DS_EDI_RDI // by group: memory through DS:EDI or RDI } /** * Describes types of operands for opcodes that implicitly carry an * operand, e.g. certain variants of MOV always have EAX has target * register. * @author fwi * */ public enum DirectGroup { GENERIC, // AL, BX, ECX etc. SEGMENT, // CS, DS etc. X87FPU, // FPU register MMX, // MMX register XMM, // XMM register CONTROL, // control register DEBUG, // debug register MSR, // no idea SYSTABP, // no idea XCR // no idea } /** * Describes the size and type of an operand * @author fwi * */ public enum OperandType { TWO_INDICES, // two memory operands, adheres operand size attribute BYTE, // byte regardless of operand size BCD, // packed BCD BYTE_SGN, // byte, sign-extended to operand size BYTE_STACK, // byte, sign-extended to size of stack pointer DWORD, // dword, regardless of operand size DWORD_OPS, // dword according to opsize (implementation unchecked) DWORD_ADR, // dword according to address size (implementation unchecked) DWORD_INT_FPU, // dword integer for FPU DWORD_QWORD, // dword or qword depending on REX.W DWORD_QWORD_ADR, // dword or qword depending on address size DQWORD, // double quadword (128 bits), regardless of operand size DOUBLE_FPU, // double real for FPU FPU_ENV, // FPU environment REAL_EXT_FPU, // extended real for FPU REAL_SINGLE_FPU, // single precision real for FPU POINTER, // 32 or 48 bit address, depending on operand size QWORD_MMX, // MMX qword QWORD, // qword, regardless of operand size QWORD_STACK, // qwrod according to stack size QWORD_ADR, // qword according to address size QWORD_WORD, // qword (default) or word if op-size prefix set QWORD_FPU, // qword integer for FPU QWORD_REX, // qword, promoted by REX.W DOUBLE_128, // packed 128 bit double float SINGLE_128, // packed 128 bit single float SINGLE_64, // packed 64 bit single float POINTER_REX, // 32 or 48 bit pointer, but 80 if REX.W PSEUDO_DESC, // 6 byte pseudo descriptor FPU_STATE, // 94 / 108 bit FPU state SCALAR_DOUBLE, // scalar of 128 bit double float SCALAR_SINGLE, // scalar of 128 bit single float FPU_SIMD_STATE, // 512 bit FPU and SIMD state WORD, // word, regardless of operand size WORD_STACK, // word according to stack operand size WORD_ADR, // word according to address size WORD_OPS, // word according to operand size (implementation unchecked) WORD_FPU, // word integer for FPU WORD_DWORD, // word or dword (default) depending on opsize WORD_DWORD_ADR, // word or dword (default) depending on address size WORD_DWORD_STACK, // word or dword depending on stack pointer size WORD_DWORD_64, // word or dword (depdending op size) extended to 64 bit if REX.W WORD_DWORD_S64 // word or dword (depending op size) sign ext to 64 bit if REX.W } /** If the register has a hardcoded operand, its type will be stored here */ public DirectGroup directGroup; /** Some opcodes have a hardcoded operand in the XML, it will be stored here */ public String hardcoded; /** Some opcode have a hardcoded operand that is hardcoded as a register numer */ public long numForGroup; /** true if the operand is only indirectly modified, e.g. EBP when using LEAVE */ public boolean indirect; /** true if the result depends on its previous value */ public boolean depends; /** Whether the operand is a source or destination operand */ public UsageType usageType; /** The encoding mode of the operand */ public AddressType adrType; /** The type the operand */ public OperandType operType; @Override public String toString() { StringBuilder res = new StringBuilder(); if(!indirect) { res.append(String.format("<operand %s = %s / %s>", usageType, adrType, operType)); } else { res.append(String.format("<indirect operand %s = %s / %s>", usageType, adrType, operType)); } return res.toString(); } }
Java
package kianxali.decoder.arch.x86; import kianxali.decoder.Register; import kianxali.decoder.arch.x86.xml.OperandDesc; import kianxali.decoder.arch.x86.xml.OperandDesc.OperandType; /** * This utility class contains several constants and helper methods used * to work with the x86 architecture. * @author fwi * */ public final class X86CPU { /** * The different CPU models of the x86 architecture. * @author fwi * */ public enum Model { I8086, I80186, I80286, I80386, I80486, PENTIUM, PENTIUM_MMX, PENTIUM_PRO, PENTIUM_II, PENTIUM_III, PENTIUM_IV, CORE_1, CORE_2, CORE_I7, ITANIUM, ANY } // Utility class, no constructor private X86CPU() { } /** * Operand sizes in bits * @author fwi * */ public enum OperandSize { O8, O16, O32, O64, O80, O128, O512 } /** * Address sizes in bits * @author fwi * */ public enum AddressSize { A16, A32, A64 } /** * The x86 register set * @author fwi * */ public enum X86Register implements Register { // generic 8 bit AL, AH, BL, BH, CL, CH, DL, DH, // generic 16 bit AX, BX, CX, DX, BP, SP, SI, DI, // generic 32 bit EAX, EBX, ECX, EDX, EBP, ESP, ESI, EDI, // generic 64 bit RAX, RBX, RCX, RDX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15, // lower 8 bit SIL, DIL, BPL, SPL, R8B, R9B, R10B, R11B, R12B, R13B, R14B, R15B, // lower 16 bit R8W, R9W, R10W, R11W, R12W, R13W, R14W, R15W, // lower 32 bit R8D, R9D, R10D, R11D, R12D, R13D, R14D, R15D, // segment registers CS, DS, ES, FS, GS, SS, // Control registers CR0, CR2, CR3, CR4, // Debug registers DR0, DR1, DR2, DR3, DR4, DR5, DR6, DR7, // Test registers TR0, TR1, TR2, TR3, TR4, TR5, TR6, TR7, // FPU registers ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7, // MMX registers (are actually aliases for FPU registers) MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7, // SSE registers XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7, XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15 } /** * x86 execution modes * @author fwi * */ public enum ExecutionMode { REAL, PROTECTED, LONG, SMM } /** * x86 memory segments * @author fwi * */ public enum Segment { CS, DS, SS, ES, FS, GS } /** * x86 instruction set extensions * @author fwi * */ public enum InstructionSetExtension { MMX, SMX, VMX, SSE_1, SSE_2, SSE_3, SSE_4_1, SSE_4_2, SSSE_3 } /** * Given a context, return the current default address size * @param ctx the context used for the calculation * @return the expected address size */ public static AddressSize getAddressSize(X86Context ctx) { switch(ctx.getExecMode()) { case SMM: // TODO: not sure if fall-through to long mode is correct here case LONG: if(ctx.getPrefix().adrSizePrefix) { return AddressSize.A32; } else { return AddressSize.A64; } case PROTECTED: if(ctx.getPrefix().adrSizePrefix) { return AddressSize.A16; } else { return AddressSize.A32; } case REAL: return AddressSize.A16; default: throw new RuntimeException("invalid cpu mode: " + ctx.getExecMode()); } } /** * Given a context, return the default operand size * @param ctx the context used for the calculation * @return the expected operand size */ private static OperandSize getDefaultOperandSize(X86Context ctx) { switch(ctx.getExecMode()) { case SMM: // TODO: not sure if fall-through to long mode is correct here case LONG: if(ctx.getPrefix().rexWPrefix) { return OperandSize.O64; } else if(ctx.getPrefix().opSizePrefix) { return OperandSize.O16; } else { return OperandSize.O32; } case PROTECTED: if(ctx.getPrefix().opSizePrefix) { return OperandSize.O16; } else { return OperandSize.O32; } case REAL: return OperandSize.O16; default: throw new RuntimeException("invalid cpu mode: " + ctx.getExecMode()); } } /** * Given a context and an operand type, returns the expected size * of the operand * @param ctx the context to analyze * @param opType the operand type * @return the expected size of the operand */ public static OperandSize getOperandSize(X86Context ctx, OperandType opType) { switch(opType) { case BYTE: return OperandSize.O8; case WORD_OPS: // TODO: check case WORD_FPU: case WORD: return OperandSize.O16; case WORD_DWORD_64: case WORD_DWORD_S64: return getDefaultOperandSize(ctx); case WORD_DWORD: if(ctx.getPrefix().opSizePrefix) { return OperandSize.O16; } else { return OperandSize.O32; } case DWORD_QWORD: if(ctx.getPrefix().rexWPrefix) { return OperandSize.O64; } else { return OperandSize.O32; } case POINTER_REX: if(ctx.getPrefix().rexWPrefix) { return OperandSize.O80; } else if(ctx.getPrefix().opSizePrefix) { return OperandSize.O16; } else { return OperandSize.O32; } case TWO_INDICES: if(ctx.getPrefix().opSizePrefix) { return OperandSize.O32; } else { return OperandSize.O64; } case POINTER: if(ctx.getPrefix().opSizePrefix) { return OperandSize.O16; } else { return OperandSize.O32; } case DWORD_INT_FPU: case REAL_SINGLE_FPU: return OperandSize.O32; case DOUBLE_FPU: case QWORD_FPU: return OperandSize.O64; case DWORD: return OperandSize.O32; case QWORD: case QWORD_MMX: return OperandSize.O64; case QWORD_WORD: if(ctx.getPrefix().opSizePrefix) { return OperandSize.O16; } else { return OperandSize.O64; } case SINGLE_64: case SCALAR_DOUBLE: return OperandSize.O64; case SCALAR_SINGLE: return OperandSize.O32; case DQWORD: case DOUBLE_128: case SINGLE_128: return OperandSize.O128; case REAL_EXT_FPU: return OperandSize.O80; case FPU_SIMD_STATE: return OperandSize.O512; default: throw new UnsupportedOperationException("invalid operand type: " + opType); } } private static X86Register getGenericRegister8(short id) { switch(id) { case 0: return X86Register.AL; case 1: return X86Register.CL; case 2: return X86Register.DL; case 3: return X86Register.BL; case 4: return X86Register.AH; case 5: return X86Register.CH; case 6: return X86Register.DH; case 7: return X86Register.BH; case 8: return X86Register.R8B; case 9: return X86Register.R9B; case 10:return X86Register.R10B; case 11:return X86Register.R11B; case 12:return X86Register.R12B; case 13:return X86Register.R13B; case 14:return X86Register.R14B; case 15:return X86Register.R15B; default: throw new UnsupportedOperationException("invalid generic 8 bit register: " + id); } } private static X86Register getGenericRegister16(short id) { switch(id) { case 0: return X86Register.AX; case 1: return X86Register.CX; case 2: return X86Register.DX; case 3: return X86Register.BX; case 4: return X86Register.SP; case 5: return X86Register.BP; case 6: return X86Register.SI; case 7: return X86Register.DI; case 8: return X86Register.R8W; case 9: return X86Register.R9W; case 10:return X86Register.R10W; case 11:return X86Register.R11W; case 12:return X86Register.R12W; case 13:return X86Register.R13W; case 14:return X86Register.R14W; case 15:return X86Register.R15W; default: throw new UnsupportedOperationException("invalid generic 16 bit register: " + id); } } private static X86Register getGenericRegister32(short id) { switch(id) { case 0: return X86Register.EAX; case 1: return X86Register.ECX; case 2: return X86Register.EDX; case 3: return X86Register.EBX; case 4: return X86Register.ESP; case 5: return X86Register.EBP; case 6: return X86Register.ESI; case 7: return X86Register.EDI; case 8: return X86Register.R8D; case 9: return X86Register.R9D; case 10:return X86Register.R10D; case 11:return X86Register.R11D; case 12:return X86Register.R12D; case 13:return X86Register.R13D; case 14:return X86Register.R14D; case 15:return X86Register.R15D; default: throw new UnsupportedOperationException("invalid generic 32 bit register: " + id); } } private static X86Register getGenericRegister64(short id) { switch(id) { case 0: return X86Register.RAX; case 1: return X86Register.RCX; case 2: return X86Register.RDX; case 3: return X86Register.RBX; case 4: return X86Register.RSP; case 5: return X86Register.RBP; case 6: return X86Register.RSI; case 7: return X86Register.RDI; case 8: return X86Register.R8; case 9: return X86Register.R9; case 10:return X86Register.R10; case 11:return X86Register.R11; case 12:return X86Register.R12; case 13:return X86Register.R13; case 14:return X86Register.R14; case 15:return X86Register.R15; default: throw new UnsupportedOperationException("invalid generic 64 bit register: " + id); } } private static X86Register getSegmentRegister(short id) { switch(id & 0x7) { case 0: return X86Register.ES; case 1: return X86Register.CS; case 2: return X86Register.SS; case 3: return X86Register.DS; case 4: return X86Register.FS; case 5: return X86Register.GS; default: throw new UnsupportedOperationException("invalid segment register: " + id); } } private static X86Register getFPURegister(short id) { switch(id & 0x07) { case 0: return X86Register.ST0; case 1: return X86Register.ST1; case 2: return X86Register.ST2; case 3: return X86Register.ST3; case 4: return X86Register.ST4; case 5: return X86Register.ST5; case 6: return X86Register.ST6; case 7: return X86Register.ST7; default: throw new UnsupportedOperationException("invalid FPU register: " + id); } } private static X86Register getMMXRegister(short id) { switch(id & 0x07) { case 0: return X86Register.MM0; case 1: return X86Register.MM1; case 2: return X86Register.MM2; case 3: return X86Register.MM3; case 4: return X86Register.MM4; case 5: return X86Register.MM5; case 6: return X86Register.MM6; case 7: return X86Register.MM7; default: throw new UnsupportedOperationException("invalid MMX register: " + id); } } private static X86Register getXMMRegister(short id) { switch(id) { case 0: return X86Register.XMM0; case 1: return X86Register.XMM1; case 2: return X86Register.XMM2; case 3: return X86Register.XMM3; case 4: return X86Register.XMM4; case 5: return X86Register.XMM5; case 6: return X86Register.XMM6; case 7: return X86Register.XMM7; case 8: return X86Register.XMM8; case 9: return X86Register.XMM9; case 10: return X86Register.XMM10; case 11: return X86Register.XMM11; case 12: return X86Register.XMM12; case 13: return X86Register.XMM13; case 14: return X86Register.XMM14; case 15: return X86Register.XMM15; default: throw new UnsupportedOperationException("invalid XMM register: " + id); } } private static X86Register getControlRegister(short id) { switch(id) { case 0: return X86Register.CR0; case 2: return X86Register.CR2; case 3: return X86Register.CR3; case 4: return X86Register.CR4; default: throw new UnsupportedOperationException("invalid control register: " + id); } } private static X86Register getDebugRegister(short id) { switch(id) { case 0: return X86Register.DR0; case 1: return X86Register.DR1; case 2: return X86Register.DR2; case 3: return X86Register.DR3; case 4: return X86Register.DR4; case 5: return X86Register.DR5; case 6: return X86Register.DR6; case 7: return X86Register.DR7; default: throw new UnsupportedOperationException("invalid debug register: " + id); } } private static X86Register getTestRegister(short id) { switch(id) { case 0: return X86Register.TR0; case 1: return X86Register.TR1; case 2: return X86Register.TR2; case 3: return X86Register.TR3; case 4: return X86Register.TR4; case 5: return X86Register.TR5; case 6: return X86Register.TR6; case 7: return X86Register.TR7; default: throw new UnsupportedOperationException("invalid test register: " + id); } } /** * Given a register number and a context, return the general address register * that the number represents * @param ctx the context to analyze * @param id the register number * @return the register represented by the number */ public static X86Register getGenericAddressRegister(X86Context ctx, short id) { if(ctx.getExecMode() != ExecutionMode.LONG && id > 7) { throw new UnsupportedOperationException("used 64 bit register id in 32 bit mode"); } AddressSize adrSize = getAddressSize(ctx); switch(adrSize) { case A16: return getGenericRegister16(id); case A32: return getGenericRegister32(id); case A64: return getGenericRegister64(id); default: throw new UnsupportedOperationException("invalid adrSize: " + adrSize); } } /** * Given a register number and a context, return the general operand register * that the number represents * @param op the operand description of the operand * @param ctx the context to analyze * @param id the register number * @return the register represented by the number */ private static X86Register getOperandRegisterGeneral(OperandDesc op, X86Context ctx, short id) { if(ctx.getExecMode() != ExecutionMode.LONG && id > 7) { throw new UnsupportedOperationException("used 64 bit register id in 32 bit mode"); } OperandSize opSize = getOperandSize(ctx, op.operType); switch(opSize) { case O8: return getGenericRegister8(id); case O16: return getGenericRegister16(id); case O32: return getGenericRegister32(id); case O64: return getGenericRegister64(id); default: throw new UnsupportedOperationException("invalid opSize: " + opSize); } } /** * Given a register number and a context, return the register * that the number represents * @param op the operand description of the operand * @param ctx the context to analyze * @param id the register number * @return the register represented by the number */ public static X86Register getOperandRegister(OperandDesc op, X86Context ctx, short id) { switch(op.adrType) { case MOD_RM_R: case MOD_RM_M: case LEAST_REG: case MOD_RM_R_FORCE_GEN: case MOD_RM_M_FORCE_GEN: return getOperandRegisterGeneral(op, ctx, id); case MOD_RM_R_SEG: return getSegmentRegister(id); case MOD_RM_M_FPU: case MOD_RM_M_FPU_REG: return getFPURegister(id); case MOD_RM_MMX: case MOD_RM_R_MMX: case MOD_RM_M_MMX: return getMMXRegister(id); case MOD_RM_M_XMM_REG: case MOD_RM_XMM: case MOD_RM_R_XMM: return getXMMRegister(id); case SEGMENT2: return getSegmentRegister((short) ((id >> 3) & 0x3)); case SEGMENT33: return getSegmentRegister((short) ((id >> 3) & 0x7)); case MOD_RM_R_DEBUG: return getDebugRegister(id); case MOD_RM_R_CTRL: return getControlRegister(id); case MOD_RM_R_TEST: return getTestRegister(id); case GROUP: switch(op.directGroup) { case GENERIC: return getOperandRegisterGeneral(op, ctx, id); case X87FPU: return getFPURegister(id); default: throw new UnsupportedOperationException("invalid directGroup: " + op.directGroup); } default: throw new UnsupportedOperationException("invalid adrType: " + op.adrType); } } }
Java
/** * This package contains an instruction decoder for the x86 * architecture. It uses an XML to read the instruction set * and creates a prefix tree for parsing byte sequences into * instructions. */ package kianxali.decoder.arch.x86;
Java
package kianxali.decoder.arch.x86; import kianxali.decoder.arch.x86.X86CPU.X86Register; import kianxali.decoder.arch.x86.xml.OperandDesc; import kianxali.loader.ByteSequence; /** * This class is used to parse a SIB byte that can follow a ModR/M byte. * @author fwi * */ class SIB { private PointerOp sibOp; public SIB(ByteSequence seq, OperandDesc op, short mode, X86Context ctx) { short sib = seq.readUByte(); int scale = 1 << (sib >> 6); short index = (short) ((sib >> 3) & 0x07); if(ctx.getPrefix().rexXPrefix) { index |= 8; } short base = (short) (sib & 0x07); if(ctx.getPrefix().rexBPrefix) { base |= 8; } X86Register indexReg; if(index == 4) { indexReg = null; } else { indexReg = X86CPU.getGenericAddressRegister(ctx, index); } long disp; if(base == 5 || base == 13) { switch(mode) { case 0: disp = seq.readSDword(); sibOp = new PointerOp(ctx, scale, indexReg, disp); break; case 1: disp = seq.readSByte(); sibOp = new PointerOp(ctx, X86Register.EBP, scale, indexReg, disp); break; case 2: disp = seq.readSDword(); sibOp = new PointerOp(ctx, X86Register.EBP, scale, indexReg, disp); break; default: throw new RuntimeException("invalid base: " + mode); } } else { X86Register baseReg = X86CPU.getGenericAddressRegister(ctx, base); sibOp = new PointerOp(ctx, baseReg, scale, indexReg); } sibOp.setOpType(op.operType); sibOp.setUsage(op.usageType); } public PointerOp getOp() { return sibOp; } }
Java
package kianxali.decoder.arch.x86; import kianxali.decoder.Operand; import kianxali.decoder.arch.x86.X86CPU.AddressSize; import kianxali.decoder.arch.x86.X86CPU.X86Register; import kianxali.decoder.arch.x86.xml.OperandDesc; import kianxali.loader.ByteSequence; /** * Used to parse a ModR/M byte. * @author fwi * */ class ModRM { private final short codedMod; private final short codedReg; private final short codedMem; private final X86Context ctx; private final ByteSequence seq; public ModRM(ByteSequence seq, X86Context ctx) { this.seq = seq; this.ctx = ctx; short code = seq.readUByte(); codedMod = (short) (code >> 6); if(ctx.getPrefix().rexRPrefix) { codedReg = (short) (((code >> 3) & 0x07) | 8); } else { codedReg = (short) ((code >> 3) & 0x07); } if(ctx.getPrefix().rexBPrefix) { codedMem = (short) ((code & 0x07) | 8); } else { codedMem = (short) (code & 0x07); } } public boolean isRMMem() { return codedMod != 3; } public boolean isRMReg() { return codedMod == 3; } public Operand getReg(OperandDesc op) { X86Register reg = X86CPU.getOperandRegister(op, ctx, codedReg); return new RegisterOp(op.usageType, reg); } public Operand getMem(OperandDesc op, boolean allowRegister, boolean mustBeRegister) { AddressSize addrSize = X86CPU.getAddressSize(ctx); switch(addrSize) { case A16: return getMem16(op, allowRegister, mustBeRegister); case A32: return getMem32or64(false, op, allowRegister, mustBeRegister); case A64: return getMem32or64(true, op, allowRegister, mustBeRegister); default: throw new UnsupportedOperationException("invalid address size: " + addrSize); } } private Operand getMem16(OperandDesc op, boolean allowRegister, boolean mustBeRegister) { if(isRMReg()) { // encoding specifies register (or user forced so) if(!allowRegister) { return null; } return new RegisterOp(op.usageType, X86CPU.getOperandRegister(op, ctx, codedMem)); } else if(mustBeRegister) { return null; } X86Register baseReg = null, indexReg = null; switch(codedMem) { case 0: baseReg = X86Register.BX; indexReg = X86Register.SI; break; case 1: baseReg = X86Register.BX; indexReg = X86Register.DI; break; case 2: baseReg = X86Register.BP; indexReg = X86Register.SI; break; case 3: baseReg = X86Register.BP; indexReg = X86Register.DI; break; case 4: baseReg = X86Register.SI; break; case 5: baseReg = X86Register.DI; break; case 6: baseReg = X86Register.BP; break; case 7: baseReg = X86Register.BX; break; default: throw new UnsupportedOperationException("invalid mem type: " + codedMem); } switch(codedMod) { case 0: { if(codedMem != 6) { PointerOp res = new PointerOp(ctx, baseReg, 1, indexReg); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } else { long disp = seq.readSWord(); PointerOp res = new PointerOp(ctx, disp); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } } case 1: { long disp = seq.readSByte(); PointerOp res = new PointerOp(ctx, baseReg, 1, indexReg, disp); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } case 2: { long disp = seq.readSWord(); PointerOp res = new PointerOp(ctx, baseReg, 1, indexReg, disp); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } default: throw new UnsupportedOperationException("invalid mode: " + codedMod); } } private Operand getMem32or64(boolean is64, OperandDesc op, boolean allowRegister, boolean mustBeRegister) { if(isRMReg()) { // encoding specifies register (or user forced so) if(!allowRegister) { return null; } return new RegisterOp(op.usageType, X86CPU.getOperandRegister(op, ctx, codedMem)); } else if(mustBeRegister) { return null; } switch(codedMod) { case 0: if(codedMem == 4 || codedMem == 12) { SIB sib = new SIB(seq, op, codedMod, ctx); return sib.getOp(); } else if(codedMem == 5 || codedMem == 13) { long disp = seq.readUDword(); if(is64) { disp += ctx.getInstructionPointer(); } PointerOp res = new PointerOp(ctx, disp); if(is64) { res.setNeedSizeFix(true); } res.setOpType(op.operType); res.setUsage(op.usageType); return res; } else { PointerOp res; res = new PointerOp(ctx, X86CPU.getGenericAddressRegister(ctx, codedMem)); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } case 1: if(codedMem == 4 || codedMem == 12) { SIB sib = new SIB(seq, op, codedMod, ctx); PointerOp pOp = sib.getOp(); if(!pOp.hasOffset()) { pOp.setOffset(seq.readUByte()); } return pOp; } else { long disp = seq.readSByte(); PointerOp res; res = new PointerOp(ctx, X86CPU.getGenericAddressRegister(ctx, codedMem), disp); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } case 2: if(codedMem == 4 || codedMem == 12) { SIB sib = new SIB(seq, op, codedMod, ctx); PointerOp pOp = sib.getOp(); if(!pOp.hasOffset()) { pOp.setOffset(seq.readUDword()); } return pOp; } else { long disp = seq.readSDword(); PointerOp res; res = new PointerOp(ctx, X86CPU.getGenericAddressRegister(ctx, codedMem), disp); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } default: throw new UnsupportedOperationException("unsupported mode: " + codedMod); } } }
Java
package kianxali.decoder.arch.x86; import java.util.logging.Logger; import kianxali.decoder.Data; import kianxali.decoder.Operand; import kianxali.decoder.UsageType; import kianxali.decoder.Data.DataType; import kianxali.decoder.arch.x86.X86CPU.OperandSize; import kianxali.decoder.arch.x86.X86CPU.Segment; import kianxali.decoder.arch.x86.X86CPU.X86Register; import kianxali.decoder.arch.x86.xml.OperandDesc.OperandType; import kianxali.util.OutputFormatter; /** * This class is used to represent operands that contain * a dereferenced memory address, e.g. an operand of the * type [baseRegister + indexScale * indexRegister + offset] * @author fwi * */ public class PointerOp implements Operand { // TODO: context should be removed from here private static final Logger LOG = Logger.getLogger("kianxali.decoder.arch.x86"); private final X86Context context; private UsageType usage; private OperandType opType; private Segment segment; private X86Register baseRegister, indexRegister; private Integer indexScale; private Long offset; private boolean needSizeFix; // ptr [address] PointerOp(X86Context ctx, long offset) { this.context = ctx; this.offset = offset; } // ptr [register] PointerOp(X86Context ctx, X86Register baseRegister) { this.context = ctx; this.baseRegister = baseRegister; } PointerOp(X86Context ctx, X86Register baseRegister, long offset) { this.context = ctx; this.baseRegister = baseRegister; this.offset = offset; } // ptr [scale * register] PointerOp(X86Context ctx, X86Register indexRegister, int scale) { this.context = ctx; this.indexRegister = indexRegister; if(scale > 1 && indexRegister != null) { this.indexScale = scale; } } // ptr [scale * register + offset] PointerOp(X86Context ctx, X86Register indexRegister, int scale, long offset) { this.context = ctx; this.indexRegister = indexRegister; if(scale > 1 && indexRegister != null) { this.indexScale = scale; } this.offset = offset; } // ptr [base + scale * index] PointerOp(X86Context ctx, X86Register baseRegister, int scale, X86Register indexRegister) { this.context = ctx; this.baseRegister = baseRegister; if(scale > 1 && indexRegister != null) { this.indexScale = scale; } this.indexRegister = indexRegister; } // ptr [scale * index + offset] PointerOp(X86Context ctx, int scale, X86Register indexRegister, long offset) { this.context = ctx; if(scale > 1 && indexRegister != null) { this.indexScale = scale; } this.indexRegister = indexRegister; this.offset = offset; } // ptr [base + scale * index + offset] PointerOp(X86Context ctx, X86Register baseRegister, int scale, X86Register indexRegister, long offset) { this.context = ctx; this.baseRegister = baseRegister; if(scale > 1 && indexRegister != null) { this.indexScale = scale; } this.indexRegister = indexRegister; this.offset = offset; } /** * Returns whether the offset part of the address is present * @return true if the address contains an offset part */ public boolean hasOffset() { return offset != null; } void setOffset(long offset) { this.offset = offset; } /** * Returns the offset part of the address * @return the offset, can be null */ public Long getOffset() { return offset; } void setOpType(OperandType opType) { this.opType = opType; } void setUsage(UsageType usage) { this.usage = usage; } void setSegment(Segment segment) { this.segment = segment; } @Override public Number asNumber() { if(offset != null && baseRegister == null && indexRegister == null) { // only this combination is deterministic return offset; } return null; } /** * If possible, returns a {@link Data} object with address and type * set to match this operand. * @return */ public Data getProbableData() { if(offset == null) { // only register-based indexing, can't know address return null; } if(baseRegister == null && indexRegister == null) { DataType type; // only addressed by constant -> great because we know the size then // TODO: work on opType directly for more information try { OperandSize size = X86CPU.getOperandSize(context, opType); switch(size) { case O8: type = DataType.BYTE; break; case O16: type = DataType.WORD; break; case O32: type = DataType.DWORD; break; case O64: type = DataType.QWORD; break; case O128: type = DataType.DQWORD; break; case O512: type = DataType.DYWORD; break; default: type = DataType.UNKNOWN; } } catch(Exception e) { LOG.warning("Unknown operand size for " + opType); type = DataType.UNKNOWN; } return new Data(offset, type); } else { Data res = new Data(offset, DataType.UNKNOWN); if(indexScale != null) { res.setTableScaling(indexScale); } return res; } } void setNeedSizeFix(boolean b) { needSizeFix = b; } boolean needsSizeFix() { return needSizeFix; } @Override public Short getPointerDestSize() { switch(X86CPU.getOperandSize(context, opType)) { case O8: return 8; case O16: return 16; case O32: return 32; case O64: return 64; case O80: return 80; case O128: return 128; case O512: return 512; default: throw new RuntimeException("invalid operand size: " + opType); } } @Override public String asString(OutputFormatter formatter) { StringBuilder str = new StringBuilder(); switch(opType) { case SINGLE_128: case DOUBLE_128: str.append("xmmword ptr "); break; default: try { switch(X86CPU.getOperandSize(context, opType)) { case O8: str.append("byte ptr "); break; case O16: str.append("word ptr "); break; case O32: str.append("dword ptr "); break; case O64: str.append("qword ptr "); break; case O80: str.append("tbyte ptr "); break; case O128: str.append("dqword ptr "); break; case O512: str.append("dyword ptr "); break; default: throw new RuntimeException("invalid operand size: " + opType); } } catch(Exception e) { LOG.warning("Unknown operand size for " + opType); str.append("? ptr "); } } if(segment != null) { str.append(segment + ":"); } else if(context.getPrefix().overrideSegment != null) { str.append(context.getPrefix().overrideSegment + ":"); } str.append("["); boolean needsPlus = false; if(baseRegister != null) { str.append(formatter.formatRegister(baseRegister.toString())); needsPlus = true; } if(indexScale != null) { if(needsPlus) { str.append(" + "); } str.append(indexScale + " * "); needsPlus = false; } if(indexRegister != null) { if(needsPlus) { str.append(" + "); } str.append(formatter.formatRegister(indexRegister.toString())); needsPlus = true; } if(offset != null) { if(needsPlus) { str.append(offset < 0 ? " - " : " + "); } str.append(formatter.formatAddress(offset)); } str.append("]"); return str.toString(); } @Override public UsageType getUsage() { return usage; } }
Java
package kianxali.decoder.arch.x86; import kianxali.decoder.Operand; import kianxali.decoder.UsageType; import kianxali.util.OutputFormatter; /** * This class is used to represent operands that contain * an immediate value, e.g. the 123 in mov eax, 123. * Since it is not always possible to distinguish whether * an immediate is an address or just a number, this class * is used for both types. * @author fwi * */ public class ImmediateOp implements Operand { private final UsageType usage; private final long immediate; private final Long segment; ImmediateOp(UsageType usage, long immediate) { this.usage = usage; this.immediate = immediate; this.segment = null; } ImmediateOp(UsageType usage, long seg, long off) { this.usage = usage; this.immediate = off; this.segment = seg; } /** * Returns the actual immediate stored in the operand * @return the decoded immediate value */ public long getImmediate() { return immediate; } /** * If the immediate also contains a segment, it will be * returned here. * @return the segment belonging to the immediate, can be null */ public Long getSegment() { return segment; } @Override public UsageType getUsage() { return usage; } @Override public String asString(OutputFormatter options) { if(segment != null) { return options.formatImmediate(segment) + ":" + options.formatImmediate(immediate); } else { return options.formatImmediate(immediate); } } @Override public Number asNumber() { return immediate; } @Override public Short getPointerDestSize() { return null; } }
Java
package kianxali.decoder.arch.x86; import kianxali.decoder.Operand; import kianxali.decoder.UsageType; import kianxali.decoder.arch.x86.X86CPU.X86Register; import kianxali.util.OutputFormatter; /** * This class is used to describe operands that represent * direct register access. * @author fwi * */ public class RegisterOp implements Operand { private final UsageType usage; private final X86Register register; RegisterOp(UsageType usage, X86Register register) { this.usage = usage; this.register = register; } @Override public UsageType getUsage() { return usage; } @Override public String asString(OutputFormatter formatter) { return formatter.formatRegister(register.toString()); } @Override public Number asNumber() { return null; } @Override public Short getPointerDestSize() { return null; } }
Java
package kianxali.decoder.arch.x86; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import kianxali.decoder.Context; import kianxali.decoder.DecodeTree; import kianxali.decoder.Decoder; import kianxali.decoder.Instruction; import kianxali.decoder.arch.x86.X86CPU.ExecutionMode; import kianxali.decoder.arch.x86.X86CPU.Model; import kianxali.decoder.arch.x86.xml.OpcodeSyntax; import kianxali.decoder.arch.x86.xml.XMLParserX86; import kianxali.loader.ByteSequence; import org.xml.sax.SAXException; /** * An instruction decoder for the x86 architecture. * It uses an XML file to read the instruction set and creates a prefix * tree from that in order to parse opcodes and their operands. * @author fwi * */ public final class X86Decoder implements Decoder { private static final Logger LOG = Logger.getLogger("kianxali.decoder.arch.x86"); private static XMLParserX86 parser; private final DecodeTree<OpcodeSyntax> decodeTree; private X86Decoder(DecodeTree<OpcodeSyntax> tree) { this.decodeTree = tree; } /** * Construct a decoder for a given CPU * @param cpu the CPU model to use * @param mode the execution mode to use * @param xmlPath path to the XML file that contains the instruction set * @param dtdPath path to the DTD file that describes the syntax of the XML file * @return the configured decoder * @throws SAXException if the XML file couldn't be parsed * @throws IOException if the XML file couldn't be read */ public static synchronized X86Decoder fromXML(Model cpu, ExecutionMode mode, String xmlPath, String dtdPath) throws SAXException, IOException { DecodeTree<OpcodeSyntax> tree = createDecodeTree(cpu, mode, xmlPath, dtdPath); return new X86Decoder(tree); } private static DecodeTree<OpcodeSyntax> createDecodeTree(Model cpu, ExecutionMode mode, String xmlPath, String dtdPath) throws SAXException, IOException { if(parser == null) { LOG.config("Creating x86 decoding tree from XML..."); parser = new XMLParserX86(); parser.loadXML(xmlPath, dtdPath); } DecodeTree<OpcodeSyntax> tree = new DecodeTree<>(); // build decode tree for(final OpcodeSyntax entry : parser.getSyntaxEntries()) { // if an opcode isn't supported on this model, don't put it into the tree if(!entry.getOpcodeEntry().isSupportedOn(cpu, mode)) { continue; } short[] prefix = entry.getPrefix(); if(entry.hasEncodedRegister()) { int regIndex = prefix.length - 1 - entry.getEncodedRegisterRelativeIndex(); for(int i = 0; i < 8; i++) { tree.addEntry(prefix, entry); prefix[regIndex]++; } } else { tree.addEntry(prefix, entry); } } // filter decode tree: remove opcodes that have a special version in the requested mode filterTree(cpu, mode, tree); return tree; } private static void filterTree(Model cpu, ExecutionMode mode, DecodeTree<OpcodeSyntax> tree) { for(short s : tree.getLeaveCodes()) { List<OpcodeSyntax> syntaxes = tree.getLeaves(s); if(syntaxes.size() > 1) { Map<Short, List<OpcodeSyntax>> prefixLists = new HashMap<>(); // sort syntaxes by required prefix for(OpcodeSyntax syntax : syntaxes) { Short prefix = syntax.getOpcodeEntry().prefix; if(prefix == null) { prefix = 0; } List<OpcodeSyntax> list = prefixLists.get(prefix); if(list == null) { list = new ArrayList<>(); prefixLists.put(prefix, list); } list.add(syntax); } for(Short prefix : prefixLists.keySet()) { List<OpcodeSyntax> samePrefixSyntaxes = prefixLists.get(prefix); filterSpecializedMode(samePrefixSyntaxes, syntaxes, mode); filterReplaced(samePrefixSyntaxes, syntaxes, cpu); } // if(syntaxes.size() > 1) { // LOG.finest("Double prefix: " + syntaxes.get(0).getPrefixAsHexString()); // } } } for(DecodeTree<OpcodeSyntax> subTree : tree.getSubTrees()) { filterTree(cpu, mode, subTree); } } private static void filterReplaced(List<OpcodeSyntax> syntaxes, List<OpcodeSyntax> removeFrom, Model cpu) { Model latestStart = null; Short extension = null; for(OpcodeSyntax syntax : syntaxes) { if(syntax.getOpcodeEntry().particular) { continue; } if(latestStart == null || syntax.getOpcodeEntry().getStartModel().ordinal() > latestStart.ordinal()) { latestStart = syntax.getOpcodeEntry().getStartModel(); extension = syntax.getExtension(); } } for(OpcodeSyntax syntax : syntaxes) { if(syntax.getExtension() != extension) { continue; } // the check for memFormat is a hack - otherwise FIADD will be removed in favor of FCMOVB if(syntax.getOpcodeEntry().getStartModel().ordinal() < latestStart.ordinal() && syntax.getOpcodeEntry().memFormat == null) { removeFrom.remove(syntax); } } } private static boolean filterSpecializedMode(List<OpcodeSyntax> syntaxes, List<OpcodeSyntax> removeFrom, ExecutionMode mode) { Short extension = null; boolean hasSpecialMode = false; for(OpcodeSyntax syntax : syntaxes) { if(syntax.getOpcodeEntry().mode == mode) { hasSpecialMode = true; extension = syntax.getExtension(); } } if(hasSpecialMode) { for(OpcodeSyntax syntax : syntaxes) { if(syntax.getOpcodeEntry().mode != mode) { if(extension == null || extension == syntax.getExtension()) { // LOG.finest("Removing due to specialized version: " + syntax); removeFrom.remove(syntax); } } } } return false; } /** * Return all available opcode syntaxes. * @return a list of all available opcode syntaxes */ public List<OpcodeSyntax> getAllSyntaxes() { return getAllSyntaxesFromTree(decodeTree); } private List<OpcodeSyntax> getAllSyntaxesFromTree(DecodeTree<OpcodeSyntax> tree) { List<OpcodeSyntax> res = new LinkedList<>(); for(short s : tree.getLeaveCodes()) { res.addAll(tree.getLeaves(s)); } for(DecodeTree<OpcodeSyntax> subTree : tree.getSubTrees()) { res.addAll(getAllSyntaxesFromTree(subTree)); } return Collections.unmodifiableList(res); } @Override public Instruction decodeOpcode(Context context, ByteSequence seq) { X86Context ctx = (X86Context) context; ctx.reset(); X86Instruction inst = decodeNext(seq, ctx, decodeTree); return inst; } private X86Instruction decodeNext(ByteSequence sequence, X86Context ctx, DecodeTree<OpcodeSyntax> tree) { if(!sequence.hasMore()) { return null; } short s = sequence.readUByte(); ctx.getPrefix().pushPrefixByte(s); DecodeTree<OpcodeSyntax> subTree = tree.getSubTree(s); if(subTree != null) { X86Instruction res = decodeNext(sequence, ctx, subTree); if(res != null) { return res; } } // no success in sub tree -> could be in leaf List<OpcodeSyntax> leaves = tree.getLeaves(s); if(leaves == null) { sequence.skip(-1); ctx.getPrefix().popPrefixByte(); return null; } X86Instruction inst = new X86Instruction(ctx.getInstructionPointer(), leaves); if(!inst.decode(sequence, ctx)) { sequence.skip(-1); ctx.getPrefix().popPrefixByte(); return null; } if(inst.isPrefix()) { ctx.applyPrefix(inst); return decodeNext(sequence, ctx, decodeTree); } else { return inst; } } }
Java
package kianxali.decoder.arch.x86; import java.io.IOException; import kianxali.decoder.Context; import kianxali.decoder.Decoder; import kianxali.decoder.arch.x86.X86CPU.AddressSize; import kianxali.decoder.arch.x86.X86CPU.ExecutionMode; import kianxali.decoder.arch.x86.X86CPU.Model; import kianxali.decoder.arch.x86.X86CPU.Segment; import kianxali.decoder.arch.x86.xml.OpcodeEntry; import kianxali.decoder.arch.x86.xml.OpcodeGroup; import kianxali.decoder.arch.x86.xml.OpcodeSyntax; import org.xml.sax.SAXException; /** * This class stores information that is needed for and modified by parsing opcodes, * e.g. CPU model, present prefixes and current execution mode of the CPU. * @author fwi * */ public class X86Context implements Context { private Model model; private ExecutionMode execMode; private long instructionPointer; private Prefix prefix; /** * Create a context for a certain CPU model in a given execution mode. * @param model the CPU model to use * @param execMode the execution mode to use */ public X86Context(Model model, ExecutionMode execMode) { this.model = model; this.execMode = execMode; reset(); } @Override public void setInstructionPointer(long instructionPointer) { this.instructionPointer = instructionPointer; } @Override public long getInstructionPointer() { return instructionPointer; } Prefix getPrefix() { return prefix; } boolean acceptsOpcode(OpcodeSyntax syntax) { if(!syntax.getOpcodeEntry().isSupportedOn(model, execMode)) { return false; } switch(syntax.getOpcodeEntry().mode) { case LONG: if(execMode != ExecutionMode.LONG) { return false; } break; case PROTECTED: if(execMode == ExecutionMode.REAL) { return false; } break; case REAL: case SMM: break; default: throw new UnsupportedOperationException("invalid execution mode: " + syntax.getOpcodeEntry().mode); } return true; } void applyPrefix(X86Instruction inst) { OpcodeEntry opcode = inst.getOpcode(); if(!opcode.belongsTo(OpcodeGroup.PREFIX)) { throw new UnsupportedOperationException("not a prefix"); } switch(opcode.opcode) { case 0xF0: prefix.lockPrefix = true; break; case 0xF2: prefix.repNZPrefix = true; break; case 0xF3: prefix.repZPrefix = true; break; case 0x2E: prefix.overrideSegment = Segment.CS; break; case 0x36: prefix.overrideSegment = Segment.SS; break; case 0x3E: prefix.overrideSegment = Segment.DS; break; case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: prefix.rexWPrefix = (opcode.opcode & 8) != 0; prefix.rexRPrefix = (opcode.opcode & 4) != 0; prefix.rexXPrefix = (opcode.opcode & 2) != 0; prefix.rexBPrefix = (opcode.opcode & 1) != 0; break; case 0x26: prefix.overrideSegment = Segment.ES; break; case 0x64: prefix.overrideSegment = Segment.FS; break; case 0x65: prefix.overrideSegment = Segment.GS; break; case 0x66: prefix.opSizePrefix = true; break; case 0x67: prefix.adrSizePrefix = true; break; case 0x9B: prefix.waitPrefix = true; break; default: throw new UnsupportedOperationException("unknown prefix: " + opcode); } } void hidePrefix(short s) { switch(s) { case 0xF0: prefix.lockPrefix = false; break; case 0xF2: prefix.repNZPrefix = false; break; case 0xF3: prefix.repZPrefix = false; break; case 0x2E: prefix.overrideSegment = Segment.CS; break; case 0x36: prefix.overrideSegment = Segment.SS; break; case 0x3E: prefix.overrideSegment = Segment.DS; break; case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: prefix.rexWPrefix = (s & 8) == 0; prefix.rexRPrefix = (s & 4) == 0; prefix.rexXPrefix = (s & 2) == 0; prefix.rexBPrefix = (s & 1) == 0; break; case 0x26: prefix.overrideSegment = null; break; case 0x64: prefix.overrideSegment = null; break; case 0x65: prefix.overrideSegment = null; break; case 0x66: prefix.opSizePrefix = false; break; case 0x67: prefix.adrSizePrefix = false; break; case 0x9B: prefix.waitPrefix = false; break; default: throw new UnsupportedOperationException("unknown prefix: " + s); } } public void setMode(ExecutionMode mode) { this.execMode = mode; } public void setModel(Model model) { this.model = model; } public Model getModel() { return model; } public ExecutionMode getExecMode() { return execMode; } public void reset() { prefix = new Prefix(); } @Override public Decoder createInstructionDecoder() { try { return X86Decoder.fromXML(model, execMode, "./xml/x86/x86reference.xml", "./xml/x86/x86reference.dtd"); } catch(SAXException | IOException e) { System.err.println("Couldn't create X86 decoder: " + e.getMessage()); e.printStackTrace(); return null; } } @Override public int getDefaultAddressSize() { AddressSize size = X86CPU.getAddressSize(this); switch(size) { case A16: return 2; case A32: return 4; case A64: return 8; default: throw new UnsupportedOperationException("invalid address size: " + size); } } }
Java
package kianxali.decoder.arch.x86; import java.util.ArrayList; import java.util.List; import kianxali.decoder.arch.x86.X86CPU.Segment; /** * This class is used to store the information that can be encoded in * prefixes to opcodes. The information are stored in flags and as raw * bytes (in case the opcode needs to check whether a mandatory prefix * is present). * @author fwi * */ public class Prefix { public Segment overrideSegment; public boolean lockPrefix, waitPrefix; public boolean repZPrefix, repNZPrefix, opSizePrefix, adrSizePrefix; public boolean rexWPrefix, rexRPrefix, rexBPrefix, rexXPrefix; public List<Short> prefixBytes; public Prefix() { prefixBytes = new ArrayList<>(5); } public void pushPrefixByte(short b) { prefixBytes.add(b); } public void popPrefixByte() { int size = prefixBytes.size(); if(size > 0) { prefixBytes.remove(size - 1); } } @Override public String toString() { StringBuilder res = new StringBuilder(); if(lockPrefix) { res.append("lock "); } else if(waitPrefix) { res.append("wait "); } if(repZPrefix) { res.append("repz "); } else if(repNZPrefix) { res.append("repnz "); } return res.toString(); } }
Java
package kianxali.decoder.arch.x86; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import kianxali.decoder.Data; import kianxali.decoder.Instruction; import kianxali.decoder.Operand; import kianxali.decoder.UsageType; import kianxali.decoder.arch.x86.X86CPU.Segment; import kianxali.decoder.arch.x86.X86CPU.X86Register; import kianxali.decoder.arch.x86.xml.OpcodeEntry; import kianxali.decoder.arch.x86.xml.OpcodeGroup; import kianxali.decoder.arch.x86.xml.OpcodeSyntax; import kianxali.decoder.arch.x86.xml.OperandDesc; import kianxali.loader.ByteSequence; import kianxali.util.OutputFormatter; /** * This class represents a fully decoded x86 instruction, e.g. including * all operands. Its main task is to select the correct syntax and parse * all operands. * @author fwi * */ class X86Instruction implements Instruction { private final long memAddr; private final List<OpcodeSyntax> syntaxes; private OpcodeSyntax syntax; private final List<Operand> operands; private Short parsedExtension; private String prefixString; private short[] rawData; // the size is not known during while decoding operands, so this will cause a (desired) NullPointerException private Integer size; public X86Instruction(long memAddr, List<OpcodeSyntax> leaves) { this.memAddr = memAddr; this.syntaxes = leaves; this.operands = new ArrayList<>(5); } public boolean decode(ByteSequence seq, X86Context ctx) { OpcodeSyntax selected = null; int bestScore = 0; for(OpcodeSyntax syn : syntaxes) { this.syntax = syn; int score; long oldPos = seq.getPosition(); try { score = tryDecode(seq, ctx); } catch(Exception e) { continue; } finally { seq.seek(oldPos); } if(score > bestScore) { selected = syn; bestScore = score; } } syntax = selected; if(syntax != null) { Short needPrefix = syntax.getOpcodeEntry().prefix; if(needPrefix != null) { ctx.hidePrefix(needPrefix); } prefixString = ctx.getPrefix().toString(); tryDecode(seq, ctx); return true; } else { return false; } } // the prefix has been read from seq already // returns score where 0 means don't accept public int tryDecode(ByteSequence seq, X86Context ctx) { int score = 1; Prefix prefix = ctx.getPrefix(); if(syntax.isExtended()) { if(parsedExtension == null) { if(syntax.getOpcodeEntry().secondOpcode != null) { // TODO: verify that this is always correct parsedExtension = (short) ((syntax.getOpcodeEntry().secondOpcode >> 3) & 0x07); } else { parsedExtension = (short) ((seq.readUByte() >> 3) & 0x07); seq.skip(-1); } } if(syntax.getExtension() != parsedExtension) { return 0; } } // check if required prefix is present, but only actual prefixes Short needPrefix = syntax.getOpcodeEntry().prefix; boolean prefixOk = true; if(needPrefix != null) { prefixOk = false; List<Short> prefixBytes = prefix.prefixBytes; for(int i = 0; i < prefixBytes.size() - syntax.getPrefix().length; i++) { if(prefixBytes.get(i).equals(needPrefix)) { prefixOk = true; score++; break; } } } if(!prefixOk) { return 0; } operands.clear(); ModRM modRM = null; long operandPos = seq.getPosition(); OpcodeEntry entry = syntax.getOpcodeEntry(); if(entry.modRM) { modRM = new ModRM(seq, ctx); if(/*(syntax.isModRMMustMem() && !modRM.isRMMem()) || */(syntax.isModRMMustReg() && !modRM.isRMReg())) { seq.skip(-1); return 0; } } for(OperandDesc op : syntax.getOperands()) { if(op.indirect) { continue; } Operand decodedOp = decodeOperand(op, seq, ctx, modRM); if(decodedOp != null) { operands.add(decodedOp); } else { // failure to decode one operand -> failure to decode instruction seq.seek(operandPos); return 0; } } size = (int) (prefix.prefixBytes.size() + seq.getPosition() - operandPos); // now that the size is known, convert RelativeOps to ImmediateOps etc. for(int i = 0; i < operands.size(); i++) { Operand op = operands.get(i); if(op instanceof RelativeOp) { operands.set(i, ((RelativeOp) op).toImmediateOp(size)); } else if(op instanceof PointerOp) { PointerOp res = (PointerOp) op; if(res.needsSizeFix()) { res.setOffset(res.getOffset() + size); } } } // prefer NOP over xchg eax, eax if(syntax.getMnemonic() == X86Mnemonic.NOP && size == 1) { score++; } // finally, retrieve the raw bytes rawData = new short[size]; seq.skip(-size); for(int i = 0; i < size; i++) { rawData[i] = seq.readUByte(); } return score; } public boolean isPrefix() { return syntax.getOpcodeEntry().belongsTo(OpcodeGroup.PREFIX); } public OpcodeSyntax getSyntax() { return syntax; } public OpcodeEntry getOpcode() { return syntax.getOpcodeEntry(); } private Operand decodeOperand(OperandDesc op, ByteSequence seq, X86Context ctx, ModRM modRM) { switch(op.adrType) { case GROUP: return decodeGroup(op, ctx); case OFFSET: return decodeOffset(seq, op, ctx); case LEAST_REG: return decodeLeastReg(op, ctx); case MOD_RM_R_CTRL: case MOD_RM_R_DEBUG: case MOD_RM_R_TEST: case MOD_RM_R_MMX: case MOD_RM_R_SEG: case MOD_RM_R_XMM: case MOD_RM_R: if(modRM == null) { modRM = new ModRM(seq, ctx); } return modRM.getReg(op); case MOD_RM_R_FORCE_GEN: // sic! if(modRM == null) { modRM = new ModRM(seq, ctx); } return modRM.getMem(op, true, false); case MOD_RM_MUST_M: if(modRM == null) { modRM = new ModRM(seq, ctx); } return modRM.getMem(op, false, false); case MOD_RM_M_FPU_REG: case MOD_RM_M_XMM_REG: if(modRM == null) { modRM = new ModRM(seq, ctx); } return modRM.getMem(op, true, true); case MOD_RM_M_FORCE_GEN: return modRM.getMem(op, true, true); case MOD_RM_M_FPU: case MOD_RM_M_MMX: case MOD_RM_M: if(modRM == null) { modRM = new ModRM(seq, ctx); } return modRM.getMem(op, true, false); case DIRECT: case IMMEDIATE: return decodeImmediate(seq, op, ctx); case RELATIVE: return decodeRelative(seq, op); case ES_EDI_RDI: { // TODO: check PointerOp res; switch(X86CPU.getAddressSize(ctx)) { case A16: res = new PointerOp(ctx, X86Register.DI); break; case A32: res = new PointerOp(ctx, X86Register.EDI); break; case A64: res = new PointerOp(ctx, X86Register.RDI); break; default: throw new UnsupportedOperationException("unsupported address size: " + X86CPU.getAddressSize(ctx)); } res.setSegment(Segment.ES); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } case DS_ESI_RSI: { // TODO: check PointerOp res; switch(X86CPU.getAddressSize(ctx)) { case A16: res = new PointerOp(ctx, X86Register.SI); break; case A32: res = new PointerOp(ctx, X86Register.ESI); break; case A64: res = new PointerOp(ctx, X86Register.RSI); break; default: throw new UnsupportedOperationException("unsupported address size: " + X86CPU.getAddressSize(ctx)); } res.setSegment(Segment.DS); res.setOpType(op.operType); res.setUsage(op.usageType); return res; } case MOD_RM_MMX: case MOD_RM_XMM: // TODO: not sure about those two if(modRM == null) { modRM = new ModRM(seq, ctx); } return modRM.getMem(op, true, false); case SEGMENT2: case SEGMENT33: case SEGMENT30: X86Register reg = X86CPU.getOperandRegister(op, ctx, syntax.getOpcodeEntry().opcode); return new RegisterOp(op.usageType, reg); case DS_EBX_AL_RBX: { PointerOp res; switch(X86CPU.getAddressSize(ctx)) { case A16: res = new PointerOp(ctx, X86Register.BX, 1, X86Register.AL); break; case A32: res = new PointerOp(ctx, X86Register.EBX, 1, X86Register.AL); break; case A64: res = new PointerOp(ctx, X86Register.RBX, 1, X86Register.AL); break; default: throw new UnsupportedOperationException("invalid address size: " + X86CPU.getAddressSize(ctx)); } res.setOpType(op.operType); res.setUsage(op.usageType); res.setSegment(Segment.DS); return res; } case DS_EAX_RAX: case DS_EDI_RDI: case FLAGS: case STACK: default: throw new UnsupportedOperationException("unsupported address type: " + op.adrType); } } private Operand decodeRelative(ByteSequence seq, OperandDesc op) { long relOffset; switch(op.operType) { case WORD_DWORD_S64: relOffset = seq.readSDword(); break; case BYTE_SGN: relOffset = seq.readSByte(); break; default: throw new UnsupportedOperationException("unsupported relative type: " + op.operType); } return new RelativeOp(op.usageType, memAddr, relOffset); } private Operand decodeImmediate(ByteSequence seq, OperandDesc op, X86Context ctx) { long immediate; if(op.hardcoded != null) { immediate = Long.parseLong(op.hardcoded, 16); } else { switch(op.operType) { case BYTE: immediate = seq.readUByte(); break; case BYTE_STACK: immediate = seq.readSByte(); break; case BYTE_SGN: immediate = seq.readSByte(); break; case WORD: immediate = seq.readUWord(); break; case WORD_DWORD_STACK: immediate = seq.readSDword(); break; case WORD_DWORD_64: switch(X86CPU.getOperandSize(ctx, op.operType)) { case O16: immediate = seq.readUWord(); break; case O32: immediate = seq.readUDword(); break; case O64: // TODO: not sure if this is correct if(syntax.getOpcodeEntry().opSize) { immediate = seq.readUDword(); } else { immediate = seq.readSQword(); } break; default: throw new UnsupportedOperationException("invalid size: " + X86CPU.getOperandSize(ctx, op.operType)); } break; case WORD_DWORD_S64: switch(X86CPU.getOperandSize(ctx, op.operType)) { case O16: immediate = seq.readSWord(); break; case O32: immediate = seq.readSDword(); break; case O64: immediate = seq.readSDword(); break; // sign extended doesn't mean the immediate is 64 bit already default: throw new UnsupportedOperationException("invalid size: " + X86CPU.getOperandSize(ctx, op.operType)); } break; case POINTER: { long seg, off; switch(X86CPU.getOperandSize(ctx, op.operType)) { case O16: off = seq.readUWord(); break; case O32: off = seq.readUDword(); break; default: throw new UnsupportedOperationException("unsupported pointer type: " + X86CPU.getOperandSize(ctx, op.operType)); } seg = seq.readUWord(); return new ImmediateOp(op.usageType, seg, off); } default: throw new UnsupportedOperationException("unsupported immediate type: " + op.operType); } } return new ImmediateOp(op.usageType, immediate); } private Operand decodeOffset(ByteSequence seq, OperandDesc op, X86Context ctx) { long offset; switch(X86CPU.getAddressSize(ctx)) { case A16: offset = seq.readUWord(); break; case A32: offset = seq.readUDword(); break; case A64: offset = seq.readSQword(); break; default: throw new UnsupportedOperationException("invalid address size: " + X86CPU.getAddressSize(ctx)); } PointerOp res = new PointerOp(ctx, offset); res.setOpType(op.operType); return res; } private Operand decodeLeastReg(OperandDesc op, X86Context ctx) { int regIndex = ctx.getPrefix().prefixBytes.size() - 1 - syntax.getEncodedRegisterRelativeIndex(); short regId = (short) (ctx.getPrefix().prefixBytes.get(regIndex) & 0x7); if(ctx.getPrefix().rexBPrefix) { regId |= 8; } X86Register reg = X86CPU.getOperandRegister(op, ctx, regId); return new RegisterOp(op.usageType, reg); } private Operand decodeGroup(OperandDesc op, X86Context ctx) { X86Register reg = X86CPU.getOperandRegister(op, ctx, (short) op.numForGroup); return new RegisterOp(op.usageType, reg); } // whether this instruction stops an execution trace @Override public boolean stopsTrace() { X86Mnemonic mnemonic = syntax.getMnemonic(); if(mnemonic == null) { return true; } switch(mnemonic) { case JMP: case JMPE: case JMPF: case RETN: case RETF: return true; default: return false; } } @Override public String asString(OutputFormatter options) { StringBuilder res = new StringBuilder(); if(options.shouldIncludeRawBytes()) { res.append(OutputFormatter.formatByteString(rawData)); res.append("\t"); } res.append(prefixString); if(syntax.getMnemonic() == null) { res.append("NO_MNEM"); } else { res.append(syntax.getMnemonic().toString().toLowerCase()); } for(int i = 0; i < operands.size(); i++) { if(i == 0) { res.append(" "); } else { res.append(", "); } res.append(operands.get(i).asString(options)); } return res.toString(); } @Override public long getMemAddress() { return memAddr; } @Override public int getSize() { return size; } @Override public List<Operand> getOperands() { return Collections.unmodifiableList(operands); } @Override public List<Operand> getDestOperands() { List<Operand> res = new ArrayList<>(); for(Operand op : operands) { if(op.getUsage() == UsageType.DEST) { res.add(op); } } return res; } @Override public List<Operand> getSrcOperands() { List<Operand> res = new ArrayList<>(); for(Operand op : operands) { if(op.getUsage() == UsageType.SOURCE) { res.add(op); } } return res; } @Override public List<Long> getBranchAddresses() { List<Long> res = new ArrayList<>(3); // we only want call, jmp, jnz etc. if(!syntax.getOpcodeEntry().belongsTo(OpcodeGroup.GENERAL_BRANCH)) { return res; } X86Mnemonic mnem = syntax.getMnemonic(); if(mnem == X86Mnemonic.RETF || mnem == X86Mnemonic.RETN) { // these are considered branches, but we can't know their address return res; } for(Operand op : operands) { if(op instanceof ImmediateOp) { res.add(((ImmediateOp) op).getImmediate()); } else if(op instanceof PointerOp) { // TODO: think about this. Probably not return because it's [addr] and therefore data and not inst continue; } } return res; } @Override public Map<Data, Boolean> getAssociatedData() { Map<Data, Boolean> res = new HashMap<Data, Boolean>(); for(Operand op : operands) { if(op instanceof PointerOp) { Data data = ((PointerOp) op).getProbableData(); if(data != null) { res.put(data, op.getUsage() == UsageType.DEST); } } } return res; } @Override public Map<Long, Boolean> getProbableDataPointers() { Map<Long, Boolean> res = new HashMap<Long, Boolean>(); for(Operand op : operands) { if(op instanceof ImmediateOp) { res.put(((ImmediateOp) op).getImmediate(), op.getUsage() == UsageType.DEST); } } return res; } @Override public String getMnemonic() { return syntax.getMnemonic().toString(); } @Override public short[] getRawBytes() { return rawData; } @Override public boolean isFunctionCall() { X86Mnemonic mnem = syntax.getMnemonic(); if(mnem == X86Mnemonic.CALL || mnem == X86Mnemonic.CALLF) { return true; } return false; } @Override public boolean isUnconditionalJump() { X86Mnemonic mnem = syntax.getMnemonic(); if(mnem == X86Mnemonic.JMP || mnem == X86Mnemonic.JMPE || mnem == X86Mnemonic.JMPF) { return true; } return false; } @Override public String getDescription() { return syntax.getOpcodeEntry().briefDescription; } } // lives only temporarily, will be converted to ImmediateOp class RelativeOp implements Operand { private final UsageType usage; private final long relOffset, baseAddr; public RelativeOp(UsageType usage, long baseAddr, long relOffset) { this.usage = usage; this.baseAddr = baseAddr; this.relOffset = relOffset; } public ImmediateOp toImmediateOp(int instSize) { return new ImmediateOp(usage, baseAddr + instSize + relOffset); } @Override public UsageType getUsage() { return usage; } @Override public String asString(OutputFormatter options) { return null; } @Override public Number asNumber() { return null; } @Override public Short getPointerDestSize() { return null; } }
Java
package kianxali.decoder; import kianxali.loader.ByteSequence; /** * A decoder reads bytes from a sequence until an instruction is fully * decoded with all its operands. * @author fwi * */ public interface Decoder { /** * Decode the next instruction from a byte sequence * @param ctx the current context * @param seq the byte sequence to read the instruction from * @return */ Instruction decodeOpcode(Context ctx, ByteSequence seq); }
Java
package kianxali.decoder; import kianxali.util.OutputFormatter; /** * Represents an operand for an instruction * @author fwi * */ public interface Operand { /** * Returns whether the operand is a source or destination operand * @return the usage type of the operand */ UsageType getUsage(); /** * If the operand is a pointer, returns the destination size in bits * @return the dereferences size in bits or null if not applicable */ Short getPointerDestSize(); /** * Tries to coerce this operand into a number representation * @return a number if the operand can be deterministically converted to a number, null otherwise */ Number asNumber(); /** * Returns a string representation of the operand * @param options the formatter to be used to format the operand * @return a string describing this operand */ String asString(OutputFormatter options); }
Java
package kianxali.decoder; /** * This interface is used to tag enumerations that represent CPU registers * @author fwi * */ public interface Register { }
Java
package kianxali.disassembler; /** * This is the main listener interface for the disassembler. * It can be used to register at the {@link DisassemblyData} instance * to get notified when the information of an address changes. * @author fwi * */ public interface DataListener { /** * Will be called when the information for a memory address changes * @param memAddr the memory address that was just analyzed * @param entry the new entry for this memory address or null if it was cleared */ void onAnalyzeChange(long memAddr, DataEntry entry); }
Java
package kianxali.disassembler; import kianxali.decoder.Instruction; /** * Implementation of this interface can be passed to {@link DisassemblyData#visitInstructions(InstructionVisitor)} * to allow a traversal through all instructions of the image. * @author fwi * */ public interface InstructionVisitor { /** * Will be called for each instruction discovered in the image. * They will be called in order of the addresses * @param inst a discovered instruction */ void onVisit(Instruction inst); }
Java
package kianxali.disassembler; import java.util.Collections; import java.util.HashMap; import java.util.Map; import kianxali.decoder.Data; import kianxali.decoder.DecodedEntity; import kianxali.decoder.Instruction; import kianxali.loader.ImageFile; import kianxali.loader.Section; /** * This class represents all information that can be associated with a memory address, * such as the start of a function, actual instructions, data, comments made by the user * etc. * The setter methods are package private because the entries should be made through the * {@link DisassemblyData} class so the listeners get informed. * @author fwi * */ public class DataEntry { private final long address; private ImageFile startImageFile; private Section startSection, endSection; private Function startFunction, endFunction; private DecodedEntity entity; private Data attachedData; private String comment; private final Map<DataEntry, Boolean> references; DataEntry(long address) { this.address = address; references = new HashMap<>(); } /** * Returns the memory address of this entry * @return the memory address of this entry */ public long getAddress() { return address; } void attachData(Data data) { this.attachedData = data; } /** * Get the data object that is associated with this entry, * e.g. for lea eax, offset "some string" it will return the * data entry for "some string" * @return the data object associated with this entry or null */ public Data getAttachedData() { return attachedData; } void clearAttachedData() { attachedData = null; } void clearReferences() { references.clear(); } void addReferenceFrom(DataEntry src, boolean isWrite) { references.put(src, isWrite); } boolean removeReference(DataEntry src) { Boolean res = references.remove(src); return (res != null); } /** * Get all from-references to this entry, i.e. all locations that * refer to this address. The boolean is true iff it is a write-access. * @return a set of entries that refer to this address */ public Map<DataEntry, Boolean> getReferences() { return Collections.unmodifiableMap(references); } /** * Checks if this entry is a data entry * @return true if {@link DataEntry#getEntity()} is of type {@link Data} */ public boolean hasData() { return entity instanceof Data; } /** * Checks if this entry is an instruction entry * @return true if {@link DataEntry#getEntity()} is of type {@link Instruction} */ public boolean hasInstruction() { return entity instanceof Instruction; } void setStartImageFile(ImageFile startImageFile) { this.startImageFile = startImageFile; } void setStartSection(Section startSection) { this.startSection = startSection; } void setStartFunction(Function startFunction) { this.startFunction = startFunction; } void setEntity(DecodedEntity entity) { this.entity = entity; } void setEndFunction(Function endFunction) { this.endFunction = endFunction; } void setEndSection(Section endSection) { this.endSection = endSection; } void setComment(String comment) { this.comment = comment; } /** * Returns the image file if this address is the start of an image file * @return the image file associated with this address if it starts the image, or null */ public ImageFile getStartImageFile() { return startImageFile; } /** * Returns the section if this address is the start of a section * @return the section started by this address or null */ public Section getStartSection() { return startSection; } /** * Returns the function if this address is the start of a function * @return the function started by this address or null */ public Function getStartFunction() { return startFunction; } /** * Returns the entity (instruction or data) stored at the address * @return the entity contained in this entry or null */ public DecodedEntity getEntity() { return entity; } /** * Returns the user comment associated with this entry * @return the user comment stored at this entry or null */ public String getComment() { return comment; } /** * Returns the function that ends on this address * @return the function that ends on this address or null */ public Function getEndFunction() { return endFunction; } /** * Returns the section if this address is the end of a section * @return the section ended by this address or null */ public Section getEndSection() { return endSection; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (int) (address ^ (address >>> 32)); return result; } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(obj == null) { return false; } if(getClass() != obj.getClass()) { return false; } DataEntry other = (DataEntry) obj; if(address != other.address) { return false; } return true; } }
Java
package kianxali.disassembler; /** * Implementations of this interface can register at the disassembler * to be notified when the disassembly starts, ends or runs into an * error * @author fwi * */ public interface DisassemblyListener { /** * Will be called when the analysis starts */ void onAnalyzeStart(); /** * Will be called when the analysis runs into an error * @param memAddr the erroneous memory address * @param reason reason for the error */ void onAnalyzeError(long memAddr, String reason); /** * Will be called when the analysis stops */ void onAnalyzeStop(); }
Java
package kianxali.disassembler; /** * This class represents a function discovered by the disassembler * @author fwi * */ public class Function { private final long startAddress; private long endAddress; private String name; private final AddressNameListener nameListener; Function(long startAddr, AddressNameListener nameListener) { this.startAddress = startAddr; this.nameListener = nameListener; this.endAddress = startAddr; this.name = String.format("sub_%X", startAddr); } /** * Changes the name of the function * @param name the new name */ public void setName(String name) { this.name = name; nameListener.onFunctionNameChange(this); } /** * Returns the name of the function * @return name of the function */ public String getName() { return name; } void setEndAddress(long endAddress) { this.endAddress = endAddress; } /** * Returns the starting address of the function * @return the start address of the function */ public long getStartAddress() { return startAddress; } /** * Returns the last address of this function * @return the last address of the function */ public long getEndAddress() { return endAddress; } @Override public String toString() { return getName(); } }
Java
/** * This package implements a recursive-traversal disassembler. The {@link kianxali.disassembler.Disassembler} * gets an {@link ImageFile} and fills a {@link DisassemblyData} instance, * informing {@link DisassemblyListener} implementations during the analysis. * Information about the discovered entries can be received by {@link kianxali.disassembler.DataListener} * implementations that register at the {@link kianxali.disassembler.DisassemblyData} * @author fwi * */ package kianxali.disassembler;
Java
package kianxali.disassembler; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.TreeMap; import java.util.concurrent.CopyOnWriteArraySet; import kianxali.decoder.DecodedEntity; import kianxali.decoder.Instruction; import kianxali.loader.ImageFile; import kianxali.loader.Section; /** * This data structure stores the result of the disassembly. It creates a memory map * for the image file to reconstruct the actual runtime layout. It is passed to the * disassembler that will fill it. * @author fwi * */ public class DisassemblyData { private final CopyOnWriteArraySet<DataListener> listeners; private final NavigableMap<Long, DataEntry> memoryMap; /** * Construct a new disassembly data object. */ public DisassemblyData() { this.listeners = new CopyOnWriteArraySet<>(); this.memoryMap = new TreeMap<>(); } /** * Adds a listener that will be informed about changes of * the memory map, i.e. when a new instruction or data was found * by the disassembler * @param listener the listener to add */ public void addListener(DataListener listener) { listeners.add(listener); } /** * Removes a listener * @param listener the listener to remove */ public void removeListener(DataListener listener) { listeners.remove(listener); } void tellListeners(long memAddr) { DataEntry entry = getInfoOnExactAddress(memAddr); for(DataListener listener : listeners) { listener.onAnalyzeChange(memAddr, entry); } } private void put(long memAddr, DataEntry entry) { memoryMap.put(memAddr, entry); tellListeners(memAddr); } synchronized void clear(long addr) { memoryMap.remove(addr); tellListeners(addr); } // clears instruction or data and attached data, but not function start, image start etc. synchronized void clearDecodedEntity(long memAddr) { DataEntry entry = getInfoCoveringAddress(memAddr); if(entry == null) { // nothing to do as there is no code or data return; } entry.setEntity(null); entry.clearAttachedData(); // entry.clearReferences(); tellListeners(memAddr); // clear to-references (stored as from-references at destination) for(Long refAddr : memoryMap.keySet()) { DataEntry refEntry = memoryMap.get(refAddr); if(refEntry.removeReference(entry)) { tellListeners(refAddr); } } } synchronized void insertImageFileWithSections(ImageFile file) { long imageAddress = 0L; if(file.getSections().size() > 0) { imageAddress = file.getSections().get(0).getStartAddress(); } DataEntry old = getInfoOnExactAddress(imageAddress); if(old != null) { old.setStartImageFile(file); tellListeners(imageAddress); } else { DataEntry entry = new DataEntry(imageAddress); entry.setStartImageFile(file); put(imageAddress, entry); } for(Section section : file.getSections()) { long memAddrStart = section.getStartAddress(); long memAddrEnd = section.getEndAddress(); old = getInfoOnExactAddress(memAddrStart); if(old != null) { old.setStartSection(section); tellListeners(memAddrStart); } else { DataEntry entry = new DataEntry(memAddrStart); entry.setStartSection(section); put(memAddrStart, entry); } old = getInfoOnExactAddress(memAddrEnd); if(old != null) { old.setEndSection(section); tellListeners(memAddrEnd); } else { DataEntry entry = new DataEntry(memAddrEnd); entry.setEndSection(section); put(memAddrEnd, entry); } } } synchronized DataEntry insertEntity(DecodedEntity entity) { long memAddr = entity.getMemAddress(); DataEntry old = getInfoOnExactAddress(memAddr); if(old != null) { // already got info for this address, add entity old.setEntity(entity); tellListeners(memAddr); return old; } else { // check if another entry covers this address, i.e. there is data or an opcode that starts before DecodedEntity covering = findEntityOnAddress(memAddr); if(covering != null) { throw new IllegalArgumentException("address covered by other entity"); } else { // new entity entry as nothing covered the address DataEntry entry = new DataEntry(memAddr); entry.setEntity(entity); put(memAddr, entry); return entry; } } } synchronized void insertFunction(Function function) { long start = function.getStartAddress(); long end = function.getEndAddress(); DataEntry startEntry = getInfoOnExactAddress(start); DataEntry endEntry = getInfoOnExactAddress(end); if(startEntry != null && startEntry.getStartFunction() == function && endEntry != null && endEntry.getEndFunction() == function) { // nothing changed return; } if(startEntry == null) { startEntry = new DataEntry(start); put(start, startEntry); } startEntry.setStartFunction(function); tellListeners(start); if(endEntry != null) { endEntry.setEndFunction(function); } // TODO: add an else case tellListeners(end); } synchronized void updateFunctionEnd(Function function, long newEnd) { long oldEnd = function.getEndAddress(); function.setEndAddress(newEnd); DataEntry oldEntry = getInfoOnExactAddress(oldEnd); if(oldEntry != null) { oldEntry.setEndFunction(null); tellListeners(oldEnd); } DataEntry newEntry = getInfoOnExactAddress(newEnd); if(newEntry == null) { newEntry = new DataEntry(newEnd); put(newEnd, newEntry); } newEntry.setEndFunction(function); tellListeners(newEnd); } synchronized void insertReference(DataEntry srcEntry, long dstAddress, boolean isWrite) { DataEntry entry = getInfoOnExactAddress(dstAddress); if(entry == null) { entry = new DataEntry(dstAddress); put(dstAddress, entry); } entry.addReferenceFrom(srcEntry, isWrite); tellListeners(dstAddress); } /** * Attaches a user comment to a given memory address * @param memAddr the memory address to attach the comment to * @param comment the user comment */ public synchronized void insertComment(long memAddr, String comment) { DataEntry entry = getInfoOnExactAddress(memAddr); if(entry == null) { entry = new DataEntry(memAddr); put(memAddr, entry); } entry.setComment(comment); tellListeners(memAddr); } /** * Retrieves the data entry for a given memory address. * The address must be the exact starting address of the entry, * i.e. if an address is passed that covers the middle of an entry, * it will not be returned. {@link DisassemblyData#getInfoCoveringAddress(long)} * should be used for those cases. * @param memAddr the address to retrieve * @return the data entry started at the given address or null */ public synchronized DataEntry getInfoOnExactAddress(long memAddr) { DataEntry entry = memoryMap.get(memAddr); return entry; } /** * Retrieves the data entry for a given memory address. * The address needn't be the exact starting address of the entry, * i.e. if an address is passed that covers the middle of an entry, * it will still be returned. * @param memAddr the address to retrieve * @return the data entry that covers the given address or null */ public synchronized DataEntry getInfoCoveringAddress(long memAddr) { // check if the last instruction at lower addresses overlaps Entry<Long, DataEntry> floorEntry = memoryMap.floorEntry(memAddr); if(floorEntry == null) { return null; } long lastAddress = floorEntry.getKey(); DataEntry res = floorEntry.getValue(); DecodedEntity entity = res.getEntity(); if(entity == null) { return res; } if(memAddr < lastAddress || memAddr >= lastAddress + entity.getSize()) { return null; } return res; } /** * Returns the entity (instruction or data) associated with a given address. * It will only be returned if the exact starting address is passed. * @param memAddr the address to retrieve * @return the entity starting at the exact given address or null */ public synchronized DecodedEntity getEntityOnExactAddress(long memAddr) { DataEntry entry = getInfoOnExactAddress(memAddr); if(entry == null) { return null; } return entry.getEntity(); } synchronized DecodedEntity findEntityOnAddress(long memAddr) { DataEntry entry = getInfoCoveringAddress(memAddr); if(entry == null) { return null; } return entry.getEntity(); } /** * Returns the total number of entries in the memory map * @return the number of entries contained in the memory map */ public synchronized int getEntryCount() { return memoryMap.size(); } /** * Allows a visitor to visit all entries in the memory map. * @param visitor a visitor that will be called with each entry */ public synchronized void visitInstructions(InstructionVisitor visitor) { for(long addr : memoryMap.keySet()) { DataEntry entry = memoryMap.get(addr); DecodedEntity entity = entry.getEntity(); if(entity instanceof Instruction) { visitor.onVisit((Instruction) entity); } } } }
Java
package kianxali.disassembler; /** * Implementations of this interface can register at a {@link Function} to be * notified when the name changes. * @author fwi * */ public interface AddressNameListener { /** * Will be called when the name of the function changes. * @param fun the function whose name changed */ void onFunctionNameChange(Function fun); }
Java
package kianxali.disassembler; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; import java.util.logging.Logger; import kianxali.decoder.Context; import kianxali.decoder.Data; import kianxali.decoder.Data.DataType; import kianxali.decoder.DecodedEntity; import kianxali.decoder.Decoder; import kianxali.decoder.Instruction; import kianxali.decoder.JumpTable; import kianxali.loader.ByteSequence; import kianxali.loader.ImageFile; import kianxali.loader.Section; import kianxali.util.AddressNameResolver; /** * This class implements a recursive-traversal disassembler. It gets * an {@link ImageFile} and fills a {@link DisassemblyData} instance, * informing {@link DisassemblyListener} implementations during the analysis. * @author fwi * */ public class Disassembler implements AddressNameResolver, AddressNameListener { private static final Logger LOG = Logger.getLogger("kianxali.disassembler"); // TODO: start at first address of the code segment, walking linear to the end // while building the queue. Then iterate again until queue is empty private final Queue<WorkItem> workQueue; private final Set<DisassemblyListener> listeners; private final Map<Long, Function> functionInfo; // stores which trace start belongs to which function private final DisassemblyData disassemblyData; private final ImageFile imageFile; private final Context ctx; private final Decoder decoder; private Thread analyzeThread; private boolean unknownDiscoveryRan; private class WorkItem implements Comparable<WorkItem> { // determines whether the work should analyze code (data == null) or data (data has type set) public Data data; public Long address; // only add trace if it runs without decoder errors; used for unknown function detection etc. public boolean careful; public WorkItem(Long address, Data data) { this.address = address; this.data = data; } @Override public int compareTo(WorkItem o) { return address.compareTo(o.address); } } /** * Create a new disassembler that can analyze an image file to * fill a disassembly data object. The actual analysis can be started * by calling {@link Disassembler#startAnalyzer()}. * @param imageFile the image file to disassemble * @param data the data object to fill during the analysis */ public Disassembler(ImageFile imageFile, DisassemblyData data) { this.imageFile = imageFile; this.disassemblyData = data; this.functionInfo = new TreeMap<Long, Function>(); this.listeners = new CopyOnWriteArraySet<>(); this.workQueue = new PriorityQueue<>(); this.ctx = imageFile.createContext(); this.decoder = ctx.createInstructionDecoder(); this.unknownDiscoveryRan = false; disassemblyData.insertImageFileWithSections(imageFile); Map<Long, String> imports = imageFile.getImports(); // add imports as functions for(Long memAddr : imports.keySet()) { detectFunction(memAddr, imports.get(memAddr)); } long entry = imageFile.getCodeEntryPointMem(); addCodeWork(entry, false); } /** * Adds a listener that will be informed about the start, end and errors * of the analysis. * @param listener the listener to register */ public void addListener(DisassemblyListener listener) { listeners.add(listener); } /** * Removes a listener * @param listener */ public void removeListener(DisassemblyListener listener) { listeners.remove(listener); } /** * Starts the actual disassembly. It will be run in a separate thread, i.e. this method * won't block. The listeners will be informed when the analysis is done or runs into * an error. */ public synchronized void startAnalyzer() { if(analyzeThread != null) { throw new IllegalStateException("disassembler already running"); } for(DisassemblyListener listener : listeners) { listener.onAnalyzeStart(); } analyzeThread = new Thread(new Runnable() { public void run() { analyze(); } }); LOG.fine("Starting analyzer"); analyzeThread.start(); } /** * Stops the analysis thread. It can be started again with {@link Disassembler#startAnalyzer()}. */ public synchronized void stopAnalyzer() { if(analyzeThread != null) { analyzeThread.interrupt(); analyzeThread = null; for(DisassemblyListener listener : listeners) { listener.onAnalyzeStop(); } LOG.fine("Stopped analyzer"); } } /** * Informs the disassembler that the given address should be analyzed again. * Subsequent addresses will also be analyzed. * @param addr the address to visit again */ public synchronized void reanalyze(long addr) { disassemblyData.clearDecodedEntity(addr); addCodeWork(addr, false); if(analyzeThread == null) { startAnalyzer(); } } private void workOnQueue() { while(!Thread.interrupted()) { WorkItem item = workQueue.poll(); if(item == null) { // no more work break; } if(item.data == null) { disassembleTrace(item); } else { try { analyzeData(item.data); } catch(Exception e) { LOG.info(String.format("Couldn't parse data at %X: %s", item.data.getMemAddress(), e.getMessage())); } } } } private void analyze() { // Analyze code and data workOnQueue(); // Propagate function information for(Function fun : functionInfo.values()) { disassemblyData.insertFunction(fun); // identify trampoline functions long start = fun.getStartAddress(); DataEntry entry = disassemblyData.getInfoOnExactAddress(start); if(entry != null && entry.getEntity() instanceof Instruction) { Instruction inst = (Instruction) entry.getEntity(); if(inst.isUnconditionalJump() && inst.getAssociatedData().size() == 1) { // the function immediately jumps somewhere else, take name from there Data data = inst.getAssociatedData().keySet().iterator().next(); long branch = data.getMemAddress(); Function realFun = functionInfo.get(branch); if(realFun != null) { fun.setName("!" + realFun.getName()); disassemblyData.tellListeners(branch); } } } } // Now try to fill black holes by discovering functions that were not directly called if(!unknownDiscoveryRan) { discoverUncalledFunctions(); workOnQueue(); unknownDiscoveryRan = true; } stopAnalyzer(); } private void addCodeWork(long address, boolean careful) { WorkItem itm = new WorkItem(address, null); itm.careful = careful; workQueue.add(itm); } private void addDataWork(Data data) { workQueue.add(new WorkItem(data.getMemAddress(), data)); } private void disassembleTrace(WorkItem item) { long memAddr = item.address; Function function = functionInfo.get(memAddr); while(true) { DecodedEntity old = disassemblyData.getEntityOnExactAddress(memAddr); if(old instanceof Instruction) { // Already visited this trace // If it is data, now we'll overwrite it to code break; } DecodedEntity covering = disassemblyData.findEntityOnAddress(memAddr); if(covering != null) { LOG.warning(String.format("%08X already covered", memAddr)); // TODO: covers other instruction or data break; } if(!imageFile.isValidAddress(memAddr)) { // TODO: Signal this somehow? break; } ctx.setInstructionPointer(memAddr); Instruction inst = null; ByteSequence seq = null; try { seq = imageFile.getByteSequence(memAddr, true); inst = decoder.decodeOpcode(ctx, seq); } catch(Exception e) { LOG.log(Level.WARNING, String.format("Disassemble error (%s) at %08X: %s", e, memAddr, inst), e); if(item.careful) { // TODO: undo everything or something } break; } finally { if(seq != null) { seq.unlock(); } } if(inst == null) { // couldn't decode instruction // TODO: change to data for(DisassemblyListener listener : listeners) { listener.onAnalyzeError(memAddr, "Couldn't decode instruction"); } break; } disassemblyData.insertEntity(inst); examineInstruction(inst, function); if(inst.stopsTrace()) { break; } memAddr += inst.getSize(); // Check if we are in a different function now. This can happen // if a function doesn't end with ret but just runs into a different function, // e.g. after a call to ExitProcess Function newFunction = functionInfo.get(memAddr); if(newFunction != null) { function = newFunction; } } if(function != null && function.getEndAddress() < memAddr) { disassemblyData.updateFunctionEnd(function, memAddr); } } private void analyzeData(Data data) { long memAddr = data.getMemAddress(); DataEntry cover = disassemblyData.getInfoCoveringAddress(memAddr); if(cover != null) { if(cover.hasInstruction()) { // data should not overwrite instruction return; } else if(cover.hasData()) { // TODO: new information about data, e.g. DWORD also accessed byte-wise return; } } ByteSequence seq = imageFile.getByteSequence(memAddr, true); try { // jump tables are a special case: need to guess the number of entries if(data instanceof JumpTable) { analyzeJumpTable(seq, (JumpTable) data); } else { data.analyze(seq); } DataEntry entry = disassemblyData.insertEntity(data); // attach data information to entries that point to this data for(DataEntry ref : entry.getReferences().keySet()) { ref.attachData(data); disassemblyData.tellListeners(ref.getAddress()); } } catch(Exception e) { LOG.log(Level.WARNING, String.format("Data decode error (%s) at %08X", e, data.getMemAddress())); // TODO: change to raw data for(DisassemblyListener listener : listeners) { listener.onAnalyzeError(data.getMemAddress(), "Couldn't decode data"); } throw e; } finally { seq.unlock(); } } private void analyzeJumpTable(ByteSequence seq, JumpTable table) { // strategy: evaluate entries until either an invalid memory address is found // or something that is already covered by code but not the start of an instruction int entrySize = table.getTableScaling(); boolean badEntry = false; int i = 0; do { long entryAddr; switch(entrySize) { case 1: entryAddr = seq.readUByte(); break; case 2: entryAddr = seq.readUWord(); break; case 4: entryAddr = seq.readUDword(); break; case 8: entryAddr = seq.readSDword(); break; // FIXME default: throw new UnsupportedOperationException("invalid jump table entry size: " + entrySize); } if(!imageFile.isCodeAddress(entryAddr)) { // invalid address -> can't be a valid entry, i.e. table ended badEntry = true; } else { DataEntry entry = disassemblyData.getInfoCoveringAddress(entryAddr); if(entry != null) { DecodedEntity entity = entry.getEntity(); if((entity instanceof Instruction && entry.getAddress() != entryAddr) || entity instanceof Data) { // the entry points to a code location but not to a start of an instruction -> bad entry badEntry = true; } } } if(!badEntry) { table.addEntry(entryAddr); disassemblyData.insertComment(entryAddr, String.format("Entry %d of jump table %08X", i, table.getMemAddress())); addCodeWork(entryAddr, true); i++; } } while(!badEntry); } private Function detectFunction(long addr, String name) { if(!functionInfo.containsKey(addr)) { Function fun = new Function(addr, this); functionInfo.put(addr, fun); disassemblyData.insertFunction(fun); if(name != null) { fun.setName(name); } onFunctionNameChange(fun); return fun; } return null; } // checks whether the instruction's operands could start a new trace or data private void examineInstruction(Instruction inst, Function function) { DataEntry srcEntry = disassemblyData.getInfoCoveringAddress(inst.getMemAddress()); // check if we have branch addresses to be analyzed later for(long addr : inst.getBranchAddresses()) { if(imageFile.isValidAddress(addr)) { disassemblyData.insertReference(srcEntry, addr, false); if(inst.isFunctionCall()) { detectFunction(addr, null); } else if(function != null) { // if the branch is not a function call, it should belong to the current function functionInfo.put(addr, function); } addCodeWork(addr, false); return; } else { LOG.warning(String.format("Code at %08X references invalid address %08X", inst.getMemAddress(), addr)); } } // check if we have associated data to be analyzed later Map<Data, Boolean> dataMap = inst.getAssociatedData(); for(Data data : dataMap.keySet()) { long addr = data.getMemAddress(); if(!imageFile.isValidAddress(addr)) { continue; } if(inst.isUnconditionalJump() && !imageFile.getImports().containsKey(addr)) { // a jump into a dereferenced data pointer means that the data is a table with jump destinations // imports are a trivial single-entry jump table, hence they are discarded LOG.finer(String.format("Probable jump table: %08X into %08X", inst.getMemAddress(), addr)); // contents of the jump table will be evaluated in the data analyze pass JumpTable table = new JumpTable(addr); if(data.getTableScaling() == 0) { table.setTableScaling(ctx.getDefaultAddressSize()); } else { table.setTableScaling(data.getTableScaling()); } disassemblyData.insertReference(srcEntry, addr, dataMap.get(data)); addDataWork(table); } else { disassemblyData.insertReference(srcEntry, addr, dataMap.get(data)); addDataWork(data); } } // Check for probable pointers Map<Long, Boolean> pointers = inst.getProbableDataPointers(); for(long addr : pointers.keySet()) { if(imageFile.isValidAddress(addr)) { if(disassemblyData.getEntityOnExactAddress(addr) != null) { continue; } disassemblyData.insertReference(srcEntry, addr, pointers.get(addr)); if(imageFile.isCodeAddress(addr)) { addCodeWork(addr, true); } else { Data data = new Data(addr, DataType.UNKNOWN); addDataWork(data); } } } } private void discoverUncalledFunctions() { LOG.fine("Discovering uncalled functions..."); for(Section section : imageFile.getSections()) { if(!section.isExecutable()) { continue; } // searching for signature 55 8B EC or 55 89 E5 (both are push ebp; mov ebp, esp) boolean got55 = false, got558B = false, got5589 = false; long startAddr = section.getStartAddress(); ByteSequence seq = imageFile.getByteSequence(startAddr, false); long size = section.getEndAddress() - startAddr; for(long i = 0; i < size; i++) { short s = seq.readUByte(); if(disassemblyData.findEntityOnAddress(startAddr + i) != null) { continue; } if(s == 0x55) { got55 = true; got558B = false; got5589 = false; } else if(s == 0x8B && got55) { got55 = false; got558B = true; got5589 = false; } else if(s == 0x89 && got55) { got55 = false; got558B = false; got5589 = true; } else if((s == 0xEC && got558B) || (s == 0xE5 && got5589)) { // found signature got55 = false; got558B = false; got5589 = false; long funAddr = startAddr + i - 2; LOG.finer(String.format("Discovered indirect function %08X", funAddr)); Function fun = detectFunction(funAddr, null); if(fun != null) { fun.setName(fun.getName() + "_i"); // mark as indirectly called } addCodeWork(funAddr, true); } else { got55 = false; got558B = false; got5589 = false; } } } } @Override public String resolveAddress(long memAddr) { Function fun = functionInfo.get(memAddr); if(fun != null) { if(fun.getStartAddress() == memAddr) { return fun.getName(); } } return null; } @Override public void onFunctionNameChange(Function fun) { DataEntry entry = disassemblyData.getInfoOnExactAddress(fun.getStartAddress()); if(entry == null) { LOG.warning("Unkown function renamed: " + fun.getName()); return; } disassemblyData.tellListeners(fun.getStartAddress()); disassemblyData.tellListeners(fun.getEndAddress()); for(DataEntry ref : entry.getReferences().keySet()) { disassemblyData.tellListeners(ref.getAddress()); } } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package untils; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; /** * * @author Kanet */ public class DoiTuong { String ten; ArrayList<Double> giaTri; public DoiTuong(){ ten=""; giaTri=new ArrayList<>(); } public DoiTuong(DoiTuong x){ ten=x.ten; giaTri=new ArrayList<>(x.giaTri); } public DoiTuong(String ten,int size){ this.ten=ten; this.giaTri=new ArrayList<>(); for(int i=0;i<size;i++) this.giaTri.add(0.0); } public DoiTuong(String ten,ArrayList<Double> giaTri){ this.ten=ten; this.giaTri=giaTri; } double KhoangCach(DoiTuong x) { double kc=0; for(int i=0;i<x.giaTri.size();i++) kc+=Math.pow(x.giaTri.get(i)-this.giaTri.get(i), 2); return Math.sqrt(kc); } void TinhTrungBinh(int mau){ for(int i=0;i<this.giaTri.size();i++){ double temp=this.giaTri.get(i)/mau; this.giaTri.set(i, temp); } } void PhucHoiTrungTam(){ for(int i=0;i<this.giaTri.size();i++) this.giaTri.set(i,0.0); } void TongDoiTuong(DoiTuong x){ for(int i=0;i<x.giaTri.size();i++){ double temp=this.giaTri.get(i)+x.giaTri.get(i); this.giaTri.set(i, temp); } } int DocDuLieu(String line){ String []s=line.split(","); int i=0; if(DoiTuong.isNumber(s[0])==false){ this.ten=s[i]; i++; } for(;i<s.length;i++){ if(DoiTuong.isNumber(s[i])==true){ double value=Double.parseDouble(s[i]); giaTri.add(value); }else{ return -1; } } return giaTri.size(); } public boolean SoSanh(DoiTuong x){ for(int i=0;i<x.giaTri.size();i++) if(x.giaTri.get(i).compareTo(this.giaTri.get(i))!=0) return false; return true; } void GhiTapTin(BufferedWriter bw){ try { bw.write(this.ten); for(int i=0;i<this.giaTri.size();i++) bw.write(","+this.giaTri.get(i).toString()); } catch (IOException ex) { ex.printStackTrace(); } } public static boolean isNumber(String str){ try{ Double.parseDouble(str); }catch(NumberFormatException nfe){ return false; } return true; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package untils; import java.io.*; import java.util.ArrayList; /** * * @author Kanet */ public class PhanLop { ArrayList<Nhom> kNhom; ArrayList<DoiTuong> tapHuanLuyen; int k; public int getK() { return k; } public void setK(int k) { this.k = k; } public PhanLop() { tapHuanLuyen = new ArrayList<>(); } public boolean DocTapTin(String ten) throws FileNotFoundException, IOException { try (FileReader fr = new FileReader(ten); BufferedReader br = new BufferedReader(fr)) { String str = br.readLine(); DoiTuong d = new DoiTuong(); int f1 = d.DocDuLieu(str); if (f1 == -1) { return false; } this.tapHuanLuyen.add(d); str = br.readLine(); while (str != null) { d = new DoiTuong(); int f2 = d.DocDuLieu(str); if (f2 != -1 && f2 == f1) { tapHuanLuyen.add(d); } else { return false; } str = br.readLine(); } } return true; } /* * Gán giá trị trung tâm đầu cho các nhóm. * */ void GanTrungTamDau(ArrayList<Nhom> x) { for (int i = 0; i < this.k; i++) { DoiTuong trungTam = new DoiTuong("Trung tam " + i, this.tapHuanLuyen.get(i).giaTri); Nhom nhom = new Nhom(trungTam); x.add(nhom); } } void TimNhomChoDoiTuong(ArrayList<Nhom> x) { for (int i = 0; i < x.size(); i++) { x.get(i).nhom.clear(); } for (int i = 0; i < this.tapHuanLuyen.size(); i++) { int idMin = 0;//Chi so nhom nho nhat double min = x.get(0).trungTam.KhoangCach(this.tapHuanLuyen.get(i));;//Gia tri khoang cach nho nhat so voi trung tam for (int j = 1; j < x.size(); j++) { double khoangCach = x.get(j).trungTam.KhoangCach(this.tapHuanLuyen.get(i)); if (min > khoangCach) { min = khoangCach; idMin = j; } } x.get(idMin).nhom.add(this.tapHuanLuyen.get(i)); } } void TinhLaiTrungTam(ArrayList<Nhom> x) { for (int i = 0; i < x.size(); i++) { x.get(i).TinhTrungTam(); } } boolean SoSanh(ArrayList<Nhom> x, ArrayList<Nhom> y) { for (int i = 0; i < x.size(); i++) { if (x.get(i).SoSanh(y.get(i)) == false) { return false; } } return true; } public void GhiTapTin(File fn) throws IOException { FileWriter fw = new FileWriter(fn); BufferedWriter bw = new BufferedWriter(fw); int size = this.k; String str = String.format("%d", size); bw.write(str); for (int i = 0; i < this.kNhom.size(); i++) { bw.newLine(); bw.write(i + "," + this.kNhom.get(i).nhom.size()); this.kNhom.get(i).GhiTapTin(bw); } bw.close(); fw.close(); } void GanNhom(ArrayList<Nhom> x, ArrayList<Nhom> y) { x.clear(); for (int i = 0; i < y.size(); i++) { Nhom nhom = new Nhom(y.get(i)); x.add(nhom); } } public void TienHanhPhanLop(int k) { ArrayList<Nhom> f1 = new ArrayList<>(k); ArrayList<Nhom> f2 = new ArrayList<>(k); GanTrungTamDau(f1); do { GanNhom(f2, f1); TimNhomChoDoiTuong(f1); this.TinhLaiTrungTam(f1); } while (SoSanh(f2, f1) == false); this.kNhom = f1; } public String TinhTyLePhanNhom() { String s = ""; String str = "Số mẫu : " + this.tapHuanLuyen.size() + "\n"; s += str; str = "Số phân lớp : " + this.kNhom.size() + "\n"; s += str; for (int i = 0; i < this.kNhom.size(); i++) { double tyLe = (1.0 * this.kNhom.get(i).nhom.size() / this.tapHuanLuyen.size()) * 100; str = String.format("Phân lớp thứ %d có : %d mẫu. Chiếm tỷ lệ : %.3f", i + 1, this.kNhom.get(i).nhom.size(), tyLe); str = str + "%\n"; s += str; } return s; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package untils; import java.io.BufferedWriter; import java.io.IOException; import java.util.ArrayList; /** * * @author Kanet */ public class Nhom { ArrayList<DoiTuong> nhom; DoiTuong trungTam; public DoiTuong getTrungTam() { return trungTam; } public void setTrungTam(DoiTuong trungTam) { this.trungTam = trungTam; } public Nhom(DoiTuong trungTam){ this.trungTam=trungTam; this.nhom=new ArrayList<>(); } public Nhom(){ this.trungTam=new DoiTuong(); this.nhom=new ArrayList<>(); } public Nhom(Nhom x){ this.trungTam=new DoiTuong(x.trungTam); this.nhom=new ArrayList<>(x.nhom); } double KhoangCachVoiNhom(DoiTuong x){ return trungTam.KhoangCach(x); } void GhiTapTin(BufferedWriter bw){ try { bw.newLine(); this.trungTam.GhiTapTin(bw); for(int i=0;i<this.nhom.size();i++){ try { bw.newLine(); this.nhom.get(i).GhiTapTin(bw); } catch (IOException ex) { } } } catch (IOException ex) { } } void TinhTrungTam(){ DoiTuong temp=new DoiTuong(this.trungTam.ten,this.trungTam.giaTri.size()); for(int i=0;i<this.nhom.size();i++){ temp.TongDoiTuong(this.nhom.get(i)); } temp.TinhTrungBinh(this.nhom.size()); this.setTrungTam(temp); } public boolean SoSanh(Nhom x){ if(this.trungTam.SoSanh(x.trungTam)==false) return false; if(x.nhom.size()!=this.nhom.size()) return false; return true; } }
Java
package untils; import java.io.File; import java.util.Hashtable; import java.util.Enumeration; import javax.swing.*; import javax.swing.filechooser.*; public class ExampleFileFilter extends FileFilter { private static String TYPE_UNKNOWN = "Type Unknown"; private static String HIDDEN_FILE = "Hidden File"; private Hashtable filters = null; private String description = null; private String fullDescription = null; private boolean useExtensionsInDescription = true; public ExampleFileFilter() { this.filters = new Hashtable(); } public ExampleFileFilter(String extension) { this(extension,null); } public ExampleFileFilter(String extension, String description) { this(); if(extension!=null) addExtension(extension); if(description!=null) setDescription(description); } public ExampleFileFilter(String[] filters) { this(filters, null); } public ExampleFileFilter(String[] filters, String description) { this(); for (int i = 0; i < filters.length; i++) { addExtension(filters[i]); } if(description!=null) setDescription(description); } public boolean accept(File f) { if(f != null) { if(f.isDirectory()) { return true; } String extension = getExtension(f); if(extension != null && filters.get(getExtension(f)) != null) { return true; }; } return false; } public String getExtension(File f) { if(f != null) { String filename = f.getName(); int i = filename.lastIndexOf('.'); if(i>0 && i<filename.length()-1) { return filename.substring(i+1).toLowerCase(); }; } return null; } public void addExtension(String extension) { if(filters == null) { filters = new Hashtable(5); } filters.put(extension.toLowerCase(), this); fullDescription = null; } public String getDescription() { if(fullDescription == null) { if(description == null || isExtensionListInDescription()) { fullDescription = description==null ? "(" : description + " ("; Enumeration extensions = filters.keys(); if(extensions != null) { fullDescription += "." + (String) extensions.nextElement(); while (extensions.hasMoreElements()) { fullDescription += ", ." + (String) extensions.nextElement(); } } fullDescription += ")"; } else { fullDescription = description; } } return fullDescription; } public String fileFilter(){ return ""; } public void setDescription(String description) { this.description = description; fullDescription = null; } public void setExtensionListInDescription(boolean b) { useExtensionsInDescription = b; fullDescription = null; } public boolean isExtensionListInDescription() { return useExtensionsInDescription; } }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * jfMain.java * * Created on Feb 7, 2012, 12:15:43 PM */ package kmean; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.filechooser.FileFilter; import untils.ExampleFileFilter; import untils.PhanLop; /** * * @author Kanet */ public class jfMain extends javax.swing.JFrame { /** * Creates new form jfMain */ public jfMain() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnBrowser = new javax.swing.JButton(); tfSoPhanLop = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); btnBatDau = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); txtTapTinDoc = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); txtThongKe = new javax.swing.JTextArea(); btnGhiTapTin = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("K-mean clustering"); btnBrowser.setText("Browser"); btnBrowser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBrowserActionPerformed(evt); } }); tfSoPhanLop.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N tfSoPhanLop.setEnabled(false); jLabel1.setText("Số K:"); btnBatDau.setText("Phân lớp"); btnBatDau.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBatDauActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel2.setText("Phân lớp K-means"); txtTapTinDoc.setEditable(false); txtTapTinDoc.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N txtTapTinDoc.setEnabled(false); txtThongKe.setColumns(20); txtThongKe.setRows(5); jScrollPane1.setViewportView(txtThongKe); btnGhiTapTin.setText("Ghi Tập Tin"); btnGhiTapTin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGhiTapTinActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(tfSoPhanLop, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(btnBatDau))) .addContainerGap(314, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 113, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(113, 113, 113)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(txtTapTinDoc, javax.swing.GroupLayout.DEFAULT_SIZE, 334, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnBrowser) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addComponent(btnGhiTapTin) .addContainerGap(336, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addGap(45, 45, 45) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtTapTinDoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnBrowser)) .addGap(11, 11, 11) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(tfSoPhanLop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnBatDau) .addGap(11, 11, 11) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 301, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(btnGhiTapTin) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents File tapTin = null; PhanLop phanLop; private void btnBrowserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBrowserActionPerformed try { // TODO add your handling code here: JFileChooser jchooser = new JFileChooser(); //Tạo định dạng file //Thêm định dạng file test ExampleFileFilter ff = new ExampleFileFilter("txt", "Text File"); jchooser.addChoosableFileFilter(ff); //Thêm định dạng file csv ff = new ExampleFileFilter("csv", "Comma delimited"); jchooser.addChoosableFileFilter(ff); jchooser.showOpenDialog(this); tapTin = jchooser.getSelectedFile(); this.txtTapTinDoc.setText(tapTin.getPath()); phanLop = new PhanLop(); phanLop.DocTapTin(tapTin.getPath().toString()); this.tfSoPhanLop.enable(true); } catch (FileNotFoundException ex) { Logger.getLogger(jfMain.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(jfMain.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btnBrowserActionPerformed private void btnBatDauActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBatDauActionPerformed // TODO add your handling code here: Date d = new Date(); long t1 = d.getTime(); phanLop.setK(Integer.parseInt(this.tfSoPhanLop.getText())); phanLop.TienHanhPhanLop(phanLop.getK()); d = new Date(); long t2 = d.getTime(); double t = (double) (t2 - t1) / 1000; String tocDoThuatToan = String.format("Tốc độ thuật toán = %.3f s", t); this.txtThongKe.setText(tocDoThuatToan); //Tính tỷ lệ phân lớp cho từng nhóm String s = phanLop.TinhTyLePhanNhom(); this.txtThongKe.setText(this.txtThongKe.getText() + "\n" + s); }//GEN-LAST:event_btnBatDauActionPerformed private void btnGhiTapTinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGhiTapTinActionPerformed try { // TODO add your handling code here: JFileChooser jchooser = new JFileChooser(); //Thêm định dạng file //Thêm định dạng file text ExampleFileFilter ff = new ExampleFileFilter("txt", "Text File"); jchooser.addChoosableFileFilter(ff); //Thêm định dạng file csv ff = new ExampleFileFilter("csv", "Comma delimited"); jchooser.addChoosableFileFilter(ff); jchooser.showSaveDialog(this); tapTin = jchooser.getSelectedFile(); ff = (ExampleFileFilter) jchooser.getFileFilter(); int s = ff.getDescription().indexOf("."); String str = ff.getDescription().substring(s, s + 4); tapTin = new File(tapTin.getPath() + str); phanLop.GhiTapTin(tapTin); } catch (IOException ex) { ex.printStackTrace(); } }//GEN-LAST:event_btnGhiTapTinActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new jfMain().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBatDau; private javax.swing.JButton btnBrowser; private javax.swing.JButton btnGhiTapTin; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField tfSoPhanLop; private javax.swing.JTextField txtTapTinDoc; private javax.swing.JTextArea txtThongKe; // End of variables declaration//GEN-END:variables }
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package kmean; import java.awt.Dimension; import java.awt.Point; import java.awt.Toolkit; import javax.swing.UIManager; /** * * @author TerryBoward */ public class KMean { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) {} jfMain frm=new jfMain(); frm.setLocation(KMean.setFrameCenterScreen()); frm.setVisible(true); } public static Point setFrameCenterScreen() { Point topleft = new Point(); // Get the default toolkit Toolkit toolkit = Toolkit.getDefaultToolkit(); // Get the current screen size Dimension scrnsize = toolkit.getScreenSize(); topleft.x = scrnsize.width/2 - 400; topleft.y = scrnsize.height/2 - 300; return topleft; } }
Java
package game; import java.awt.Graphics2D; import com.golden.gamedev.object.Sprite; public class Part { double x; double y; double vx; double vy; Sprite icon; double life; double speed; ProgBob progBob; Part next; public Part (ProgBob progBob, double x, double y, Sprite icon, double speed) { this.progBob = progBob; this.x = x; this.y = y; this.icon = icon; this.speed = speed; life = 0.99; } public void draw (Graphics2D context) { icon.render(context, (int)x, (int)y); } }
Java
package game; import java.awt.Color; import java.awt.Graphics2D; public class PartString extends Part { String text; public PartString (ProgBob progBob, double x, double y, String text, double speed) { super(progBob, x, y, null, speed); this.text = text; } @Override public void draw (Graphics2D context) { if (life < 0.25) { context.setFont(progBob.fnts[(int)(4 * life * 10)]); } else { context.setFont(progBob.fnts[9]); } context.setColor(Color.WHITE); context.drawString(text, (int)x, (int)y); } }
Java
package game; import java.awt.Image; import java.awt.image.BufferedImage; import com.golden.gamedev.object.Sprite; public class BonusPause extends AbstractBonus { private static final long serialVersionUID = 1L; private double time_paused = 0; public BonusPause (ProgBob progBob, String name, Sprite icon) { super(progBob, name, icon); } public BonusPause(){ time_paused = 0; new BonusPause(super.progBob, "Pause", new Sprite(createBufferedImage("resources/bonus_pause.png"))); } @Override protected void toggleBonus() { if (time_paused > 0){ time_paused = 5; } else{ time_paused = 6; } } @Override public boolean isOn() { return bonusBoolean; } //This method updates the time_passed to average the elaspedTime and original time public void updatetime_passed(int elapsedTime){ time_paused = Math.max(0, time_paused - elapsedTime); } /* * This method returns the time_passed value */ public double gettime_paused(){ return time_paused; } @Override public void turnOff() { bonusBoolean = false; } @Override public void turnOn() { bonusBoolean = true; } @Override protected void setBonusPosition(int mouseX, int mouseY, int offset){} }
Java
package game; import com.golden.gamedev.object.Sprite; public class BonusRewind extends AbstractBonus { private static final long serialVersionUID = 1L; private double time_rewind; public BonusRewind (ProgBob progBob, String name, Sprite icon) { super(progBob, name, icon); } public BonusRewind(){ time_rewind = 0; new BonusRewind(super.progBob, "Rewind", new Sprite(createBufferedImage("resources/bonus_rewind.png"))); } @Override public void toggleBonus() { if (time_rewind > 0){ time_rewind = 3; } else{ time_rewind = 4; } } @Override protected void setBonusPosition(int mouseX, int mouseY, int offset){} @Override public boolean isOn() { return bonusBoolean; } @Override public void turnOff() { time_rewind = 0; bonusBoolean = false; } @Override public void turnOn() { bonusBoolean = true; } }
Java
package game; import com.golden.gamedev.object.Sprite; public class BonusTorpedo extends AbstractBonus { private static final long serialVersionUID = 1L; public BonusTorpedo(){ new BonusTorpedo(super.progBob, "Torpedo", new Sprite(createBufferedImage("resources/bon_torpedo.png"))); } public BonusTorpedo (ProgBob progBob, String name, Sprite icon) { super(progBob, name, icon); } @Override protected void toggleBonus(){ bonusBoolean = true; } @Override public boolean isOn() { return bonusBoolean; } @Override public void turnOff() { bonusBoolean = false; } @Override public void turnOn() { bonusBoolean = true; } }
Java
package game; import java.awt.geom.Point2D; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; /** * * @author Shun Fan * This class represents a level in bubblefish */ public class Level { PathPoint path[]; int path_inc_x; int path_inc_y; int num_path_points; double path_speed; int path_start_t; int fishToSaveAtStartOfLevel; TxtParser txtParser = new TxtParser(); public Level() { File levelFile = new File("resources/level1properties.txt"); TxtParser textParser = new TxtParser(levelFile); fishToSaveAtStartOfLevel = textParser.getFishLeftToSave(); path_speed = textParser.getBubblePathSpeed(); path_inc_x = textParser.getPathXOffset(); path_inc_y = textParser.getPathYOffset(); path_start_t = textParser.getBubblePathStartPos(); num_path_points = textParser.getNumberOfBubblePathPoints(); path = new PathPoint[num_path_points]; ArrayList<Point2D.Double> pathPoints = textParser.getBubblePathPoints(); for (int i = 0; i < pathPoints.size(); i++) { setPathPoint(i,(int) pathPoints.get(i).x,(int) pathPoints.get(i).y); } } public Level(int sub_level) { String levelFileName = "resources/properties/level"+sub_level+"properties.txt"; //System.out.println(levelFileName); File levelFile = new File(levelFileName); TxtParser textParser = new TxtParser(levelFile); fishToSaveAtStartOfLevel = textParser.getFishLeftToSave(); path_speed = textParser.getBubblePathSpeed(); path_inc_x = textParser.getPathXOffset(); path_inc_y = textParser.getPathYOffset(); path_start_t = textParser.getBubblePathStartPos(); num_path_points = textParser.getNumberOfBubblePathPoints(); path = new PathPoint[num_path_points]; ArrayList<Point2D.Double> pathPoints = textParser.getBubblePathPoints(); for (int i = 0; i < pathPoints.size(); i++) { setPathPoint(i,(int) pathPoints.get(i).x,(int) pathPoints.get(i).y); } } public double getBubblePathSpeed() { return path_speed; } public int getFishLeftToSave() { return fishToSaveAtStartOfLevel; } public int getBubblePathStartPos() { return path_start_t; } public int getNumberOfBubblePathPoints() { return num_path_points; } public PathPoint[] getBubblePath(){ return path; } void setPathPoint (int idx, double x, double y) { path[idx] = new PathPoint(); path[idx].x = (x + path_inc_x) * 0.71; path[idx].y = (y + path_inc_y - 10) * 0.71; if (idx > 0) { double dx = path[idx - 1].x - path[idx].x; double dy = path[idx - 1].y - path[idx].y; path[idx - 1].dist_to_next = Math.sqrt(dx * dx + dy * dy); } num_path_points = idx + 1; } }
Java
package game; public class BonusFactory { public BonusFactory(){ } /* * Returns a new specified Bonus object */ @SuppressWarnings("unchecked") public AbstractBonus getBonusInstance(String panelType) { Class<AbstractBonus> myClass = null; try { myClass = (Class<AbstractBonus>) Class.forName(panelType); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } AbstractBonus bonus = null; try { bonus = myClass.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return bonus; } }
Java
package game; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import java.io.File; import java.util.ArrayList; import com.golden.gamedev.Game; import com.golden.gamedev.object.Sprite; /** * backup version 4 * @author Shun * */ public class ProgBob4 { int testIfPointer; final static int RAD_BUBBLE = 13; final static int W_SMFISH = 8; final static int H_SMFISH = 6; final static int GS_MAINMENU = 0; final static int GS_PLAY = 1; final static int GS_LEVEL_COMPLETED = 2; final static int GS_GAME_OVER = 3; final static int ITEM_FREE = 0; final static int ITEM_BUBBLE = 1; final static int ITEM_TORPEDO = 2; final static int ITEM_BONUS = 3; final static int ITEM_SMROCKS = 4; final static int NUM_BOB_STATES = 11; final static int MAX_BUBBLES = 128; final static double MAX_TIME_PAUSED = 6; final static double MAX_TIME_REWIND = 4; final static double PI_2 = 2 * Math.PI; Font fnt; Font fnt2; Font fnt3; Font fnts[]; Sprite bm_bob[]; Sprite bm_bubbles[]; Sprite bm_evil_fish; Sprite bm_smfish; Sprite bm_torpedo; Sprite bm_smrock; Sprite bm_fisho; Sprite bm_click_to_continue; Sprite bm_congrats; Sprite bm_bg_menu; Sprite bm_bg_game; Sprite bm_lev_comp; Sprite bm_loading; Sprite bm_game_over; Sprite bm_part_bub[]; String snd_level_start; String snd_explosion; String snd_shoot_bubble; String snd_plip_plop; String snd_pop; String snd_bob_loses; String snd_pick; String snd_swap; String snd_lev_comp; String snd_combo[]; boolean torpedo; int smrocks; double name_show; int episode; int sub_level; int total_fish_saved; int longest_combo; double handicap; int game_state; boolean game_starting; boolean completed_the_game; double time_rewind; double time_paused; int num_bonuses; Bonus bonuses; Part parts; Item items; int num_path_points; PathPoint path[]; double path_t0; double path_speed; int fish_to_save; int fish_to_save_at_start; double path_last_t; double path_start_t; Bubble bubbles[]; Bubble first_bub; Bubble shot_bubble; Sprite next_bubble; Sprite next_bubble2; int bob_y; int bob_x; double bob_akey; double akey0; double akey1; double akey2; double akey3; double shoot_time; boolean game_over; double go_speedup; int level; boolean level_completed; double st_timer; int level_score; int total_score; int score_show; boolean paused; int path_inc_x;//accounted for int path_inc_y; Game game; TxtParser txtParser = new TxtParser(); boolean isSomeBonusActing () { return time_rewind > 0 || time_paused > 0 || items != null || smrocks > 0 || torpedo; } public void init (Game game) { this.game = game; fnt = Font.decode("Arial-BOLD-16"); fnt2 = Font.decode("Arial-BOLD-20"); fnt3 = Font.decode("Arial-PLAIN-14"); fnts = new Font[11]; for (int k = 0; k < 11; k++) { fnts[k] = Font.decode("Arial-PLAIN-" + (k + 2)); } Part part = new Part(this, 10, 10, null, 0); for (int k = 0; k < 100; k++) { part.next = new Part(this, 10, 10, null, 0); part = part.next; } for (int k = 0; k < 100; k++) { part.next = new PartBub(this, 10, 10, null, 0); part = part.next; } bm_loading = new Sprite(game.getImage("resources/loading.jpg")); bm_click_to_continue = new Sprite(game.getImage("resources/click_to_continue.png")); bm_congrats = new Sprite(game.getImage("resources/congrats.png")); bm_bob = new Sprite[NUM_BOB_STATES]; bm_bob[0] = new Sprite(game.getImage("resources/bob_0000.png")); bm_bob[1] = new Sprite(game.getImage("resources/bob_0002.png")); bm_bob[2] = new Sprite(game.getImage("resources/bob_0004.png")); bm_bob[3] = new Sprite(game.getImage("resources/bob_0006.png")); bm_bob[4] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[5] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[6] = new Sprite(game.getImage("resources/bob_0010.png")); bm_bob[7] = new Sprite(game.getImage("resources/bob_0012.png")); bm_bob[8] = new Sprite(game.getImage("resources/bob_0014.png")); bm_bob[9] = new Sprite(game.getImage("resources/bob_0016.png")); bm_bob[10] = new Sprite(game.getImage("resources/bob_0018.png")); bm_evil_fish = new Sprite(game.getImage("resources/evil_fish.png")); bm_smfish = new Sprite(game.getImage("resources/smfish.png")); snd_shoot_bubble = "resources/release_bubble.au"; snd_combo = new String[8]; snd_combo[0] = "resources/combo_01.au"; snd_combo[1] = "resources/combo_02.au"; snd_combo[2] = "resources/combo_03.au"; snd_combo[3] = "resources/combo_04.au"; snd_combo[4] = "resources/combo_05.au"; snd_combo[5] = "resources/combo_06.au"; snd_combo[6] = "resources/combo_07.au"; snd_combo[7] = "resources/combo_08.au"; snd_plip_plop ="resources/pop_01.au"; snd_pop = "resources/pop_01.au"; snd_bob_loses = "resources/bob_loses.au"; snd_pick = "resources/pickup.au"; snd_swap = "resources/gulp.au"; snd_lev_comp = "resources/lev_comp_song.au"; snd_level_start = "resources/level_start.au"; snd_explosion = "resources/explosion.au"; bm_bubbles = new Sprite[7]; bm_bubbles[0] = new Sprite(game.getImage("resources/blue.png")); bm_bubbles[1] = new Sprite(game.getImage("resources/red.png")); bm_bubbles[2] = new Sprite(game.getImage("resources/green.png")); bm_bubbles[3] = new Sprite(game.getImage("resources/orange.png")); bm_bubbles[4] = new Sprite(game.getImage("resources/purple.png")); bm_bubbles[5] = new Sprite(game.getImage("resources/cyan.png")); bm_bubbles[6] = new Sprite(game.getImage("resources/white.png")); bm_bg_game = new Sprite(game.getImage("resources/seagrass.jpg")); bm_bg_menu = new Sprite(game.getImage("resources/bg_menu.jpg")); bm_lev_comp = new Sprite(game.getImage("resources/lev_comp.png")); bm_game_over = new Sprite(game.getImage("resources/game_over.png")); bm_part_bub = new Sprite[4]; bm_part_bub[0] = new Sprite(game.getImage("resources/part_bub_01.png")); bm_part_bub[1] = new Sprite(game.getImage("resources/part_bub_02.png")); bm_part_bub[2] = new Sprite(game.getImage("resources/part_bub_03.png")); bm_part_bub[3] = new Sprite(game.getImage("resources/part_bub_04.png")); bm_torpedo = new Sprite(game.getImage("resources/torpedo.png")); bm_smrock = new Sprite(game.getImage("resources/smrock.png")); bm_fisho = new Sprite(game.getImage("resources/fisho_full.png")); bonuses = new BonusPause(this, "Pause", new Sprite(game.getImage("resources/bonus_pause.png"))); bonuses.next = new BonusRewind(this, "Rewind", new Sprite(game.getImage("resources/bonus_rewind.png"))); bonuses.next.next = new BonusTorpedo(this, "Torpedo", new Sprite(game.getImage("resources/bon_torpedo.png"))); bonuses.next.next.next = new BonusSmRocks(this, "Small Rocks", new Sprite(game.getImage("resources/bon_smrocks.png"))); num_bonuses = 4; game_state = GS_MAINMENU; initLevel(1); } void initGame () { total_fish_saved = 0; total_score = 0; level_score = 0; shoot_time = 0; completed_the_game = false; game_over = false; paused = false; } void initLevel (int level_num) { paused = false; level_completed = false; handicap = 1; longest_combo = 0; torpedo = false; smrocks = 0; name_show = 0; time_rewind = 0; time_paused = 0; items = null; game_starting = true; level_score = 0; go_speedup = 0; st_timer = 0; shot_bubble = new Bubble(); shot_bubble.bm = null; path_speed = 0.5; bob_y = 290; bob_akey = 0; level = level_num; episode = (level - 1) / 5; sub_level = (level - 1) % 5 + 1; Level level = new Level(sub_level); fish_to_save_at_start = fish_to_save = level.getFishLeftToSave(); path_speed = level.getBubblePathSpeed(); path_start_t = level.getBubblePathStartPos(); num_path_points = level.getNumberOfBubblePathPoints(); path = level.getBubblePath(); path_speed += episode * 0.08; path_t0 = 0; path_last_t = 0; for (int k = 0; k < num_path_points; k++) { path_last_t += path[k].dist_to_next; } path_last_t /= 2 * RAD_BUBBLE; bubbles = new Bubble[MAX_BUBBLES]; for (int k = 0; k < bubbles.length; k++) { bubbles[k] = new Bubble(); } first_bub = new Bubble(); first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; Point2D.Double pnt = getPathPoint(0); first_bub.x = pnt.x; first_bub.y = pnt.y; next_bubble = getRandomBubble(true); next_bubble2 = getRandomBubble(true); } public void draw (Graphics2D context) { if (game_state == GS_MAINMENU) { bm_bg_menu.render(context); } else if (game_state == GS_LEVEL_COMPLETED) { bm_bg_game.render(context, 0, 0); bm_lev_comp.render(context, 90, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 151, "Fish Saved:"); drawOutlined(context, 340, 168, "" + total_fish_saved); drawOutlined(context, 140, 151, "Max Combo:"); drawOutlined(context, 140, 168, "" + longest_combo); drawOutlined(context, 240, 205, "Level Score:"); drawOutlined(context, 240, 222, "" + level_score); context.setFont(fnt); context.setColor(Color.WHITE); bm_click_to_continue.render(context, 156, 290); drawParts(context); drawBar(context); } else if (game_state == GS_GAME_OVER) { bm_bg_game.render(context, 0, 0); if (completed_the_game) { context.setColor(Color.WHITE); context.setFont(fnt2); bm_congrats.render(context, 50, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 175, "Fish Saved:"); drawOutlined(context, 340, 192, "" + total_fish_saved); drawOutlined(context, 140, 175, "Final Score:"); drawOutlined(context, 140, 192, "" + total_score); } else { bm_game_over.render(context, 132, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 240, 111, "Fish Saved:"); drawOutlined(context, 240, 128, "" + total_fish_saved); drawOutlined(context, 240, 155, "Final Score:"); drawOutlined(context, 240, 172, "" + total_score); } drawParts(context); drawBar(context); bm_click_to_continue.render(context, 156, 290); } else if (game_state == GS_PLAY) { bm_bg_game.render(context, 0, 0); drawPath(context); drawParts(context); drawItems(context); bob_x = game.getMouseX(); int y_offset = (int)(5 * Math.sin(shoot_time * Math.PI)); if (torpedo) { bm_torpedo.setX(bob_x - bm_torpedo.getWidth() / 2); bm_torpedo.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_torpedo.render(context); } else if (smrocks > 0) { bm_smrock.setX(bob_x - bm_torpedo.getWidth() / 2); bm_smrock.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_smrock.render(context); } else { if (shoot_time >= 1) { next_bubble.setX(bob_x - next_bubble.getWidth() / 2); next_bubble.setY(bob_y - next_bubble.getHeight() + y_offset); next_bubble.render(context); } else { int x_offset = (int)(shoot_time * 2 * RAD_BUBBLE); next_bubble.setX(bob_x - x_offset / 2); next_bubble.setY((bob_y + (1 - shoot_time) * 4 * RAD_BUBBLE) - next_bubble.getHeight() + y_offset); next_bubble.render(context); } // BUGBUG: change size to 16x16 next_bubble2.render(context, (int)((bob_x - 16 / 2) + 1), (int)(((bob_y - 4) + y_offset) + (1 - shoot_time) * 16)); } bm_bob[(int)bob_akey].render(context, bob_x - 22, bob_y + y_offset); drawBar(context); if (name_show < 1 && !paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Level " + (episode + 1) + "-" + sub_level); } } if (paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Paused"); context.setFont(fnt); context.setColor(Color.BLACK); context.drawString("Press space to continue", 240, 190); } } void drawParts (Graphics2D context) { for (Part part = parts; part != null; part = part.next) { if (part.life < 0.999) { part.draw(context); } } } void drawPath (Graphics2D context) { int x = 0; int y = 0; double t = 0; for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (path_t0 + bubble.t < path_last_t - 1) { if (bubble.fish_inside) { bm_smfish.setX(bubble.x - 8); bm_smfish.setY(bubble.y - 6 + 2 * Math.sin(bubble.phase * PI_2)); bm_smfish.render(context); } double x_scale = 1 - bubble.trans; x = (int)(bubble.trans * bubble.attach_x + x_scale * bubble.x); if (path_t0 + bubble.t >= path_last_t - 4) { double y_scale = ((path_t0 + bubble.t) - (path_last_t - 4)) / 4; y = (int)((bubble.trans * bubble.attach_y + x_scale * bubble.y) + 3 * Math.sin(bubble.phase * PI_2) * (1 - y_scale) + 4 * Math.sin(PI_2 * akey2) * y_scale); } else { y = (int)(bubble.trans * bubble.attach_y + x_scale * bubble.y + 3 * Math.sin(bubble.phase * PI_2)); } bubble.bm.render(context, x - RAD_BUBBLE, y - RAD_BUBBLE); } t = bubble.t; } t += path_t0 + 1 + st_timer * (path_t0 + path_last_t - t); for (double t1 = Math.floor(t); t1 < path_last_t; t1 += 0.5) { Point2D.Double pnt = getPathPoint(t1); y = (int)(pnt.y + 3 * Math.sin(PI_2 * akey1 + t1)); bm_part_bub[3].render(context, (int)pnt.x - 2, y - 2); } x = (int)(path[num_path_points - 1].x - 55 + (1 - Math.sin(0.5 * Math.PI + 0.5 * Math.PI * st_timer)) * (480 - x)); y = (int)path[num_path_points - 1].y; bm_evil_fish.render(context, x, (y + (int)(4 * Math.sin(PI_2 * akey2))) - 40); } void drawItems (Graphics2D context) { for (Item item = items; item != null; item = item.next) { int x = (int)(item.x + 3 * Math.sin(PI_2 * akey1)); int y = (int)item.y; if (4 * item.time_existed < 1 && item.vel_y > 0) { double t = 4 * item.time_existed; int w = (int)(item.bm.getWidth() * t); int h = (int)(item.bm.getHeight() * t); // BUGBUG: change size item.bm.render(context, x - w / 2, y - h / 2); } else { item.bm.render(context, x, y); } } if (shot_bubble.bm != null) { shot_bubble.bm.render(context, (int)shot_bubble.x, (int)shot_bubble.y); } } void drawBar (Graphics2D context) { int w = bm_fisho.getWidth(); @SuppressWarnings("unused") int h = (int)(w * ((fish_to_save_at_start - fish_to_save) / fish_to_save_at_start)); // BUGBUG: change size bm_fisho.render(context, 276, 342); context.setColor(Color.WHITE); context.setFont(fnt); context.drawString(scoreString(), 63, 354); context.drawString((episode + 1) + " - " + sub_level, 190, 354); } void drawOutlined (Graphics2D context, int x, int y, String text) { // BUGBUG: center context.setColor(Color.BLACK); context.drawString(text, x - 2, y - 2); context.drawString(text, x - 2, y + 2); context.drawString(text, x + 2, y + 2); context.drawString(text, x + 2, y - 2); context.drawString(text, x - 2, y); context.drawString(text, x, y + 2); context.drawString(text, x + 2, y); context.drawString(text, x, y - 2); context.setColor(new Color(0xECD300)); context.drawString(text, x, y); } public void update (double elapsedTime) { if (paused || game_state != GS_PLAY) { return; } if (!level_completed && !game_over && !existsInPath(next_bubble)) { next_bubble = getRandomBubble(false); } akey0 = (akey0 + elapsedTime) % 1.0; akey1 = (akey1 + 0.7 * elapsedTime) % 1.0; akey2 = (akey2 + 0.5 * elapsedTime) % 1.0; akey3 = (akey3 + 0.3 * elapsedTime) % 1.0; bob_akey = (bob_akey + 2 * elapsedTime) % NUM_BOB_STATES; time_paused = Math.max(0, time_paused - elapsedTime); time_rewind = Math.max(0, time_rewind - elapsedTime); shoot_time = Math.min(1, shoot_time + 3 * elapsedTime); name_show += 0.7 * elapsedTime; score_show += Math.min(4, (int)(5 * elapsedTime * (total_score - score_show))); score_show = Math.min(score_show, total_score); updateParts(elapsedTime); updateItems(elapsedTime); updateBubbles(elapsedTime); } void updateParts (double time) { Part dead = null; for (Part part = parts; part != null; part = part.next) { part.life -= part.speed * time; if (part.life <= 0.001) { if (dead == null) { parts = part.next; } else { dead.next = part.next; } } else if (part.life < 0.999) { part.x += time * part.vx; part.y += time * part.vy; dead = part; } } } void updateItems (double time) { Item dead = null; for (Item item = items; item != null; item = item.next) { item.y += time * item.vel_y; if (item.y < -21 || item.y > 380 || item.type == ITEM_FREE) { if (dead == null) { items = items.next; } else { dead.next = item.next; } } else { item.time_existed += time; if (item.type == ITEM_TORPEDO || item.type == ITEM_SMROCKS) { if (item.type == ITEM_TORPEDO) { item.vel_y -= 400 * time; } for ( ; Math.abs(item.y - item.py) > 4; item.py -= 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-5, 5); addPart(partbub); } for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { double dx = item.x - bubble.x; double dy = item.y - bubble.y; if (dx * dx + dy * dy < RAD_BUBBLE * RAD_BUBBLE) { if (item.type == ITEM_TORPEDO) { for (Bubble bubble1 = first_bub; bubble1 != null; bubble1 = bubble1.next) { spawnBiggerBurst(item.x, item.y); double ddx = item.x - bubble1.x; double ddy = item.y - bubble1.y; if (ddx * ddx + ddy * ddy < 4096 && path_t0 + bubble1.t > 0) { spawnBurst(bubble1.x, bubble1.y); if (bubble1.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble1.next != null) { bubble1.next.shot = true; bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } else { first_bub = bubble1.next; } } } game.playSound(snd_explosion); shoot_time = 0.5; } else if (item.type == ITEM_SMROCKS) { spawnBurst(bubble.x, bubble.y); if (bubble.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble.x, bubble.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble.next != null) { bubble.next.shot = true; bubble.next.prev = bubble.prev; } if (bubble.prev != null) { bubble.prev.next = bubble.next; } else { first_bub = bubble.next; } game.playSound(snd_pop); } item.type = ITEM_FREE; if (first_bub == null) { if (fish_to_save <= 0) { level_completed = true; } else { first_bub = new Bubble(); first_bub.t = -path_t0 - 1; first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; } } } } } else { for ( ; Math.abs(item.y - item.py) > 4; item.py += 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-5, 5); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-7, 7); addPart(partbub); } if (item.bonus != null && Math.abs(item.x - bob_x) < 25 && Math.abs(item.y - (bob_y + 20)) < 38) { spawnBurst(item.x, item.y); game.playSound(snd_pick); PartString partstring = new PartString(this, item.x, item.y, item.bonus.name, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); shoot_time = 0.5; item.bonus.act(); if (dead == null) { items = items.next; } else { dead.next = item.next; } } } dead = item; } } } void updateBubbles (double elapsedTime) { double acc = path_speed * 1.5; Bubble bubble = getLastBubble(); if (bubble != null) { if (game_starting) { double t = path_t0 + bubble.t; if (t < path_start_t - 8) { acc *= 25; } else if (t < path_start_t) { acc *= 1 + (24 * (path_start_t - t)) / 8; } else { game_starting = false; } } double t = (path_t0 + bubble.t) / path_last_t; if (time_paused <= 0) { if (t < 0.7) { if (t > 0.1) { handicap += 0.1 * (0.7 - t) * elapsedTime; } else { handicap += 0.06 * elapsedTime; } } else if (t > 0.7) { handicap -= 0.15 * (t - 0.7) * elapsedTime; } } handicap = Math.max(0.95, Math.min(handicap, 4)); acc *= handicap; if (t < 0.4) { t = 1 + 15 * (0.4 - t); } else if (t > 0.8) { if (t > 0.95) { t = 0.95; } t = 2.5 * (1 - t); if (t < 0.15) { t = 0.15; } } else { t = 0.5 + 0.5 * (1 - (t - 0.4) / 0.4); } acc *= t; } acc = Math.max(0.2, acc); if (time_paused > 0) { double factor = 1; if (time_paused > 5) { factor = 1 - (MAX_TIME_PAUSED - time_paused); } else if (time_paused > 1) { factor = 0; } else if (time_paused > 0) { factor = 1 - time_paused; } acc *= factor; } if (time_rewind > 0) { double factor = 0; if (time_rewind > 3) { factor = 4 - time_rewind; } else if (time_rewind > 1) { factor = 1; } else if (time_rewind > 0) { factor = 1 * time_rewind; } acc = acc * (1 - factor) - 3 * factor; } if (game_over) { acc += go_speedup; go_speedup += 32 * elapsedTime; } else { acc = Math.max(-12, Math.min(acc, 12)); } acc *= elapsedTime; if (bubble != null && (path_t0 + bubble.t > 0 || acc > 0)) { path_t0 += acc; } if (game_over) { if (first_bub == null) { st_timer += elapsedTime; } if (st_timer > 1) { game_state = GS_GAME_OVER; } } if (level_completed) { st_timer += elapsedTime; if (st_timer > 1) { if (game_state != GS_LEVEL_COMPLETED) { game.playSound(snd_lev_comp); } game_state = GS_LEVEL_COMPLETED; } return; } double shot_y = shot_bubble.y; shot_bubble.y -= 620 * elapsedTime; if (shot_bubble.bm != null) { for (double part_y = shot_bubble.y; part_y < shot_y; part_y += 5) { PartBub partbub = new PartBub(this, shot_bubble.x, part_y, bm_part_bub[0], randDouble(3, 4.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-40, 0); partbub.x += randDouble(-7, 7); addPart(partbub); } } if (shot_bubble.y < -2 * RAD_BUBBLE) { shot_bubble.bm = null; } Bubble bubble1 = first_bub; while (!game_over && fish_to_save > 0 && first_bub.x > -2 * RAD_BUBBLE) { bubble1 = new Bubble(); bubble1.phase = first_bub.phase - 0.1; bubble1.fish_inside = true; bubble1.shot = false; first_bub.prev = bubble1; bubble1.next = first_bub; bubble1.t = first_bub.t - 1; bubble1.bm = getRandomBubble(true); first_bub = bubble1; updateBubble(first_bub); } for ( ; bubble1 != null; bubble1 = bubble1.next) { if (path_t0 + bubble1.t >= path_last_t) { if (!game_over) { game.playSound(snd_bob_loses); } game_over = true; if (bubble1.prev != null) { bubble1.prev.next = null; } if (bubble1 == first_bub) { first_bub = null; return; } } bubble1.phase += (elapsedTime % 1.0); bubble1.trans = Math.max(0, bubble1.trans - 4 * elapsedTime); updateBubble(bubble1); if (shot_bubble.bm != null && shot_bubble.y - 2 * RAD_BUBBLE <= bubble1.y + 8 && shot_y + 2 * RAD_BUBBLE + 10 > bubble1.y + 8 && Math.abs(shot_bubble.x - bubble1.x) < 15) { Bubble bubble2 = new Bubble(); bubble2.bm = shot_bubble.bm; bubble2.shot = true; bubble2.trans = 1; bubble2.attach_x = shot_bubble.x; bubble2.attach_y = shot_bubble.y; double f10 = (bubble1.prev != null) ? Math.min(bubble1.prev.x, bubble1.x) : bubble1.x - RAD_BUBBLE; double f11 = (bubble1.prev != null) ? Math.max(bubble1.prev.x, bubble1.x) : bubble1.x; double f12 = (bubble1.prev != null) ? bubble1.prev.x - bubble1.x : (bubble1.next != null) ? bubble1.x - bubble1.next.x : 1; double f15 = (bubble1.prev != null) ? bubble1.prev.y - bubble1.y : (bubble1.next != null) ? bubble1.y - bubble1.next.y : 0; double f16 = Math.sqrt(f12 * f12 + f15 * f15); f15 /= f16; boolean flag2 = true; if (Math.abs(f15) > 0.4) { flag2 = (f15 < 0); } else { flag2 = ! ((bubble1.prev != null && shot_bubble.x > f10 || bubble1.prev == null) && shot_bubble.x < f11); } if (!flag2) { bubble2.next = bubble1; bubble2.prev = bubble1.prev; bubble2.t = bubble1.t - 0.5; if (bubble1.prev != null) { bubble1.prev.next = bubble2; } else { first_bub = bubble2; } bubble1.prev = bubble2; } else { bubble2.prev = bubble1; bubble2.next = bubble1.next; bubble2.t = bubble1.t + 0.5; if (bubble1.next != null) { bubble1.next.prev = bubble2; } bubble1.next = bubble2; } shot_bubble.bm = null; } if (bubble1.next != null) { int i = 1; boolean flag = bubble1.shot; if (bubble1.prev == null || bubble1.prev.bm != bubble1.bm) { for (Bubble bubble3 = bubble1.next; bubble3 != null && bubble3.bm == bubble1.bm; bubble3 = bubble3.next) { if (bubble3.t - (i + bubble1.t) > 0.01) { i = 0; break; } if (bubble3.shot) { flag = true; } i++; } } if (flag && i >= 3) { game.playSound(snd_plip_plop); level_score += i * 50; total_score += i * 50; if (!isSomeBonusActing() && (randInt(16) == 4 || i >= 4 && randInt(10) <= i)) { double f13 = (path_t0 + bubble.t) / path_last_t; if(f13 > 0.4) { Item item = new Item(); item.type = 3; item.x = bubble1.x; item.y = item.py = bubble1.y; item.vel_y = 70; item.bonus = getRandomBonus(); item.bm = item.bonus.icon; if(items == null) { items = item; } else { item.next = items.next; items.next = item; } } } boolean flag1 = false; int j = 1; double curr_x = 0; double curr_y = 0; for (int k = i; k > 0; k--) { curr_x += bubble1.x; curr_y += bubble1.y; j += bubble1.combo; if (bubble1.fish_inside) { total_fish_saved++; fish_to_save--; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } spawnBurst(bubble1.x, bubble1.y); if (bubble1.next != null) { bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } if (bubble1 == first_bub) { first_bub = bubble1.next; } if (bubble1.next != null) { bubble1 = bubble1.next; } else { flag1 = true; bubble1 = bubble1.prev; } } curr_x /= i; curr_y /= i; if (bubble1 != null && adjIsGoingToBurst(bubble1)) { bubble1.combo = j; } if (j > 1) { PartString partstring = new PartString(this, curr_x, curr_y, "Combo " + j + "x", 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } if (longest_combo < j) { longest_combo = j; } if (j > 0) { j--; } if (j > 7) { j = 7; } game.playSound(snd_combo[j]); Bubble bubble6 = bubble1; if (bubble6 != null && bubble6.prev != null && bubble6.bm == bubble6.prev.bm && !flag1) { bubble6.shot = true; } } if (bubble1 == null) { if (fish_to_save <= 0) { level_completed = true; } if (level_completed) { first_bub = null; return; } else { first_bub = bubble1 = new Bubble(); bubble1.bm = getRandomBubble(false); bubble1.t = -path_t0; updateBubble(bubble1); return; } } if (bubble1.next == null) { return; } double f14 = Math.abs(bubble1.next.t - bubble1.t); if (f14 < 0.99) { for (Bubble bubble4 = bubble1.next; bubble4 != null; bubble4 = bubble4.next) { double f18 = 6 * (1 - f14) * elapsedTime; if (f18 > f14) f18 = f14; bubble4.t += f18; } } if (f14 > 1.01) { for(Bubble bubble5 = bubble1.next; bubble5 != null; bubble5 = bubble5.next) { double f19 = 2 * f14 * elapsedTime; if (f19 > 0.15) { f19 = 0.15; } if (f19 > f14) { f19 = f14; } bubble5.t -= f19; } } } if (bubble1.combo > 0 && !adjIsGoingToBurst(bubble1)) { bubble1.combo = 0; } } } void updateBubble (Bubble bubble) { Point2D.Double tp = getPathPoint(path_t0 + bubble.t); bubble.x = tp.x; bubble.y = tp.y; } public void handleInput () { if (game.keyPressed(KeyEvent.VK_SPACE)) { if (game_state == GS_PLAY) { game.playSound(snd_pick); paused = !paused; } else { paused = false; } } if (game.click()) { if (game_state == GS_LEVEL_COMPLETED) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; if (level / 5 + 1 >= 4) { completed_the_game = true; game_state = GS_GAME_OVER; } initLevel(level + 1); } else if (game_state == GS_GAME_OVER) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_MAINMENU) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_PLAY && !paused) { if (smrocks > 0) { game.playSound(snd_shoot_bubble); smrocks--; Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -360; item.type = ITEM_SMROCKS; item.bonus = null; item.bm = bm_smrock; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; PartString partstring = new PartString(this, item.x, item.y, "" + smrocks, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } else if (torpedo) { torpedo = false; game.playSound(snd_shoot_bubble); Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -120; item.type = ITEM_TORPEDO; item.bonus = null; item.bm = bm_torpedo; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; } else if (shot_bubble.bm != null) { return; } else if (shoot_time < 0.8) { return; } else { game.playSound(snd_shoot_bubble); shot_bubble.bm = next_bubble; next_bubble = next_bubble2; next_bubble2 = getRandomBubble(false); shot_bubble.x = game.getMouseX(); shot_bubble.y = bob_y - 10; shoot_time = 0; } } } if (game.rightClick()) { game.playSound(snd_swap); Sprite next = next_bubble; next_bubble = next_bubble2; next_bubble2 = next; shoot_time = 0.5; } } void addPart (Part part) { if (parts == null) { parts = part; } else { part.next = parts; parts = part; } } Point2D.Double getPathPoint (double idx) { if (idx < 0) { return new Point2D.Double(-30, -400); } double idx_dist = idx * 2 * RAD_BUBBLE; double curr_dist = 0; for (int i = 0; i < num_path_points; i++) { double next_dist = curr_dist + path[i].dist_to_next; if (idx_dist < next_dist) { double curr_idx = (idx_dist - curr_dist) / path[i].dist_to_next; return new Point2D.Double(path[i].x + (path[i + 1].x - path[i].x) * curr_idx, path[i].y + (path[i + 1].y - path[i].y) * curr_idx); } curr_dist = next_dist; } return new Point2D.Double(path[num_path_points - 1].x, path[num_path_points - 1].y); } void setPathPoint (int idx, double x, double y) { path[idx] = new PathPoint(); path[idx].x = (x + path_inc_x) * 0.71; path[idx].y = (y + path_inc_y - 10) * 0.71; if (idx > 0) { double dx = path[idx - 1].x - path[idx].x; double dy = path[idx - 1].y - path[idx].y; path[idx - 1].dist_to_next = Math.sqrt(dx * dx + dy * dy); } num_path_points = idx + 1; } boolean existsInPath (Sprite bub) { for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (bubble.bm == bub) { return true; } } return false; } Bubble getLastBubble () { if (first_bub == null) return null; Bubble bubble; for (bubble = first_bub; bubble.next != null; bubble = bubble.next) ; return bubble; } boolean adjIsGoingToBurst (Bubble bubble) { Sprite s = bubble.bm; int i = 1; for (Bubble b = bubble.prev; b != null && b.bm == s; b = b.prev) i++; for (Bubble b = bubble.next; b != null && b.bm == s; b = b.next) i++; return i >= 3; } void spawnBiggerBurst (double x, double y) { for (int i = 0; i < 30; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(140, 310); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 3.8)); partbub.life += randDouble(0, 0.4); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle); partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } void spawnBurst (double x, double y) { y += 5; for (int i = 0; i < 26; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(50, 100); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 4.2)); partbub.life += randDouble(0, 0.2); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle) - magnitude; partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } Sprite getRandomBubble (boolean totally_random) { int max = 3 + (episode + 1) / 2; if (totally_random) { return bm_bubbles[randInt(max)]; } for (int j = 0; j < 300; j++) { Sprite bub = bm_bubbles[randInt(max)]; if (existsInPath(bub)) { return bub; } } System.out.println("stalled."); return bm_bubbles[randInt(max)]; } Bonus getRandomBonus () { int i = randInt(num_bonuses); Bonus bonus = bonuses; for (bonus = bonuses; i != 0; bonus = bonus.next, i--) ; return bonus; } int randInt (int max) { return (int)(Math.random() * max); } double randDouble (double min, double max) { return min + Math.random() * (max - min); } String scoreString () { StringBuffer stringbuffer = new StringBuffer(score_show); for (int i = stringbuffer.length() - 1 - 2; i > 0; i -= 3) { stringbuffer.insert(i, "0"); } return stringbuffer.toString(); } }
Java
package game; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import com.golden.gamedev.object.Sprite; /* * This abstract bonus class handle all types of bonuses/rewards that are alloted in the game. */ public abstract class AbstractBonus extends Sprite { private static final long serialVersionUID = 1L; String name; Sprite icon; ProgBob progBob; AbstractBonus next; protected boolean bonusBoolean = false; public AbstractBonus(){ } public AbstractBonus (ProgBob progBob, String name, Sprite icon) { this.progBob = progBob; this.name = name; this.icon = icon; } /* * This class turns the bonus award operator on */ protected abstract void toggleBonus(); /* * This checks to make sure the bonus option is on */ public abstract boolean isOn(); public abstract void turnOff(); public abstract void turnOn(); protected ProgBob getMain(){ return progBob; } protected void setBonusPosition(int mouseX, int mouseY, int offset){ this.setX(mouseX - this.getWidth() / 2); this.setY(mouseY - this.getHeight() / 2 + offset); } public BufferedImage createBufferedImage(String filename) { ImageIcon icon = new ImageIcon(filename); Image image = icon.getImage(); // Create empty BufferedImage, sized to Image BufferedImage buffImage = new BufferedImage(image.getWidth(null), image.getHeight(null) , BufferedImage.TYPE_INT_ARGB); // Draw Image into BufferedImage Graphics g = buffImage.createGraphics(); g.drawImage(image, 0, 0, null); g.dispose(); return buffImage; } }
Java
package game; import com.golden.gamedev.object.Sprite; public class Item { int type; double x; double y; double py; double vel_y; double time_existed; Sprite bm; AbstractBonus bonus; Item next; }
Java
package game; import java.awt.geom.Point2D; import java.awt.geom.Point2D.Double; import java.util.ArrayList; /** * * @author Shun * allows user to parse different types of input// *not sure if this is needed, with creation of level class *this class is not used, but was created in case the user needed diferent ways *of parsing data. for example the user could upload an image and *parse the path from that. */ public abstract class AbstractParser { public abstract ArrayList<Point2D.Double> parseBubblePathPoints(Object source); }
Java
package game; import com.golden.gamedev.object.Sprite; public class Bubble { double x; double y; double t; double phase; Sprite bm; Bubble next; Bubble prev; boolean shot; boolean fish_inside; double attach_x; double attach_y; double trans; int combo; }
Java
package game; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import java.io.File; import java.util.ArrayList; import com.golden.gamedev.Game; import com.golden.gamedev.object.Sprite; /** * backup version 2 * @author Shun * */ public class ProgBob2 { int testIfPointer; final static int RAD_BUBBLE = 13; final static int W_SMFISH = 8; final static int H_SMFISH = 6; final static int GS_MAINMENU = 0; final static int GS_PLAY = 1; final static int GS_LEVEL_COMPLETED = 2; final static int GS_GAME_OVER = 3; final static int ITEM_FREE = 0; final static int ITEM_BUBBLE = 1; final static int ITEM_TORPEDO = 2; final static int ITEM_BONUS = 3; final static int ITEM_SMROCKS = 4; final static int NUM_BOB_STATES = 11; final static int MAX_BUBBLES = 128; final static double MAX_TIME_PAUSED = 6; final static double MAX_TIME_REWIND = 4; final static double PI_2 = 2 * Math.PI; Font fnt; Font fnt2; Font fnt3; Font fnts[]; Sprite bm_bob[]; Sprite bm_bubbles[]; Sprite bm_evil_fish; Sprite bm_smfish; Sprite bm_torpedo; Sprite bm_smrock; Sprite bm_fisho; Sprite bm_click_to_continue; Sprite bm_congrats; Sprite bm_bg_menu; Sprite bm_bg_game; Sprite bm_lev_comp; Sprite bm_loading; Sprite bm_game_over; Sprite bm_part_bub[]; String snd_level_start; String snd_explosion; String snd_shoot_bubble; String snd_plip_plop; String snd_pop; String snd_bob_loses; String snd_pick; String snd_swap; String snd_lev_comp; String snd_combo[]; boolean torpedo; int smrocks; double name_show; int episode; int sub_level; int total_fish_saved; int longest_combo; double handicap; int game_state; boolean game_starting; boolean completed_the_game; double time_rewind; double time_paused; int num_bonuses; Bonus bonuses; Part parts; Item items; int num_path_points; PathPoint path[]; double path_t0; double path_speed; int fish_to_save; int fish_to_save_at_start; double path_last_t; double path_start_t; Bubble bubbles[]; Bubble first_bub; Bubble shot_bubble; Sprite next_bubble; Sprite next_bubble2; int bob_y; int bob_x; double bob_akey; double akey0; double akey1; double akey2; double akey3; double shoot_time; boolean game_over; double go_speedup; int level; boolean level_completed; double st_timer; int level_score; int total_score; int score_show; boolean paused; int path_inc_x;//accounted for int path_inc_y; Game game; TxtParser txtParser = new TxtParser(); boolean isSomeBonusActing () { return time_rewind > 0 || time_paused > 0 || items != null || smrocks > 0 || torpedo; } public void init (Game game) { this.game = game; fnt = Font.decode("Arial-BOLD-16"); fnt2 = Font.decode("Arial-BOLD-20"); fnt3 = Font.decode("Arial-PLAIN-14"); fnts = new Font[11]; for (int k = 0; k < 11; k++) { fnts[k] = Font.decode("Arial-PLAIN-" + (k + 2)); } Part part = new Part(this, 10, 10, null, 0); for (int k = 0; k < 100; k++) { part.next = new Part(this, 10, 10, null, 0); part = part.next; } for (int k = 0; k < 100; k++) { part.next = new PartBub(this, 10, 10, null, 0); part = part.next; } bm_loading = new Sprite(game.getImage("resources/loading.jpg")); bm_click_to_continue = new Sprite(game.getImage("resources/click_to_continue.png")); bm_congrats = new Sprite(game.getImage("resources/congrats.png")); bm_bob = new Sprite[NUM_BOB_STATES]; bm_bob[0] = new Sprite(game.getImage("resources/bob_0000.png")); bm_bob[1] = new Sprite(game.getImage("resources/bob_0002.png")); bm_bob[2] = new Sprite(game.getImage("resources/bob_0004.png")); bm_bob[3] = new Sprite(game.getImage("resources/bob_0006.png")); bm_bob[4] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[5] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[6] = new Sprite(game.getImage("resources/bob_0010.png")); bm_bob[7] = new Sprite(game.getImage("resources/bob_0012.png")); bm_bob[8] = new Sprite(game.getImage("resources/bob_0014.png")); bm_bob[9] = new Sprite(game.getImage("resources/bob_0016.png")); bm_bob[10] = new Sprite(game.getImage("resources/bob_0018.png")); bm_evil_fish = new Sprite(game.getImage("resources/evil_fish.png")); bm_smfish = new Sprite(game.getImage("resources/smfish.png")); snd_shoot_bubble = "resources/release_bubble.au"; snd_combo = new String[8]; snd_combo[0] = "resources/combo_01.au"; snd_combo[1] = "resources/combo_02.au"; snd_combo[2] = "resources/combo_03.au"; snd_combo[3] = "resources/combo_04.au"; snd_combo[4] = "resources/combo_05.au"; snd_combo[5] = "resources/combo_06.au"; snd_combo[6] = "resources/combo_07.au"; snd_combo[7] = "resources/combo_08.au"; snd_plip_plop ="resources/pop_01.au"; snd_pop = "resources/pop_01.au"; snd_bob_loses = "resources/bob_loses.au"; snd_pick = "resources/pickup.au"; snd_swap = "resources/gulp.au"; snd_lev_comp = "resources/lev_comp_song.au"; snd_level_start = "resources/level_start.au"; snd_explosion = "resources/explosion.au"; bm_bubbles = new Sprite[7]; bm_bubbles[0] = new Sprite(game.getImage("resources/blue.png")); bm_bubbles[1] = new Sprite(game.getImage("resources/red.png")); bm_bubbles[2] = new Sprite(game.getImage("resources/green.png")); bm_bubbles[3] = new Sprite(game.getImage("resources/orange.png")); bm_bubbles[4] = new Sprite(game.getImage("resources/purple.png")); bm_bubbles[5] = new Sprite(game.getImage("resources/cyan.png")); bm_bubbles[6] = new Sprite(game.getImage("resources/white.png")); bm_bg_game = new Sprite(game.getImage("resources/seagrass.jpg")); bm_bg_menu = new Sprite(game.getImage("resources/bg_menu.jpg")); bm_lev_comp = new Sprite(game.getImage("resources/lev_comp.png")); bm_game_over = new Sprite(game.getImage("resources/game_over.png")); bm_part_bub = new Sprite[4]; bm_part_bub[0] = new Sprite(game.getImage("resources/part_bub_01.png")); bm_part_bub[1] = new Sprite(game.getImage("resources/part_bub_02.png")); bm_part_bub[2] = new Sprite(game.getImage("resources/part_bub_03.png")); bm_part_bub[3] = new Sprite(game.getImage("resources/part_bub_04.png")); bm_torpedo = new Sprite(game.getImage("resources/torpedo.png")); bm_smrock = new Sprite(game.getImage("resources/smrock.png")); bm_fisho = new Sprite(game.getImage("resources/fisho_full.png")); bonuses = new BonusPause(this, "Pause", new Sprite(game.getImage("resources/bonus_pause.png"))); bonuses.next = new BonusRewind(this, "Rewind", new Sprite(game.getImage("resources/bonus_rewind.png"))); bonuses.next.next = new BonusTorpedo(this, "Torpedo", new Sprite(game.getImage("resources/bon_torpedo.png"))); bonuses.next.next.next = new BonusSmRocks(this, "Small Rocks", new Sprite(game.getImage("resources/bon_smrocks.png"))); num_bonuses = 4; game_state = GS_MAINMENU; initLevel(1); } void initGame () { total_fish_saved = 0; total_score = 0; level_score = 0; shoot_time = 0; completed_the_game = false; game_over = false; paused = false; } void initLevel (int level_num) { paused = false; level_completed = false; handicap = 1; longest_combo = 0; torpedo = false; smrocks = 0; name_show = 0; time_rewind = 0; time_paused = 0; items = null; game_starting = true; level_score = 0; go_speedup = 0; st_timer = 0; shot_bubble = new Bubble(); shot_bubble.bm = null; path_speed = 0.5; bob_y = 290; bob_akey = 0; level = level_num; episode = (level - 1) / 5; sub_level = (level - 1) % 5 + 1; if (sub_level == 1) { Level level = new Level(sub_level); fish_to_save_at_start = fish_to_save = level.getFishLeftToSave(); path_speed = level.getBubblePathSpeed(); path_start_t = level.getBubblePathStartPos(); num_path_points = level.getNumberOfBubblePathPoints(); path = level.getBubblePath(); // // fish_to_save_at_start = fish_to_save = 1;//fish to save at start accounted for // //fish to save, need to pass // path_speed = 0.4;//need to pass // path_inc_x = 320;//accounted for // path_inc_y = -10;//accounted for // path_start_t = 32;//need to pass // // num_path_points = 53;//need to pass // path = new PathPoint[num_path_points];//need to pass // int j = 0; // File pointsFile = new File("resources/level1.txt"); // ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); // System.out.println(levelPathPoints.size()); // for (int ii = 0; ii < levelPathPoints.size(); ii++) { // System.out.println(ii); // setPathPoint(ii,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); // //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); // } } else if (sub_level == 2) { Level level = new Level(sub_level); fish_to_save_at_start = fish_to_save = level.getFishLeftToSave(); path_speed = level.getBubblePathSpeed(); path_start_t = level.getBubblePathStartPos(); num_path_points = level.getNumberOfBubblePathPoints(); path = level.getBubblePath(); /*fish_to_save_at_start = fish_to_save = -1; //fish_to_save_at_start = fish_to_save = 180; path_speed = 0.5; path_inc_x = 0; path_inc_y = 59; path_start_t = 14; num_path_points = 78; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level2.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); }*/ } else if (sub_level == 3) { fish_to_save_at_start = fish_to_save = -1; //fish_to_save_at_start = fish_to_save = 128; path_speed = 0.65; path_inc_x = 10; path_inc_y = 323; path_start_t = 15; num_path_points = 21; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level3.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } else if (sub_level == 4) { fish_to_save_at_start = fish_to_save = -1; //fish_to_save_at_start = fish_to_save = 150; path_speed = 0.8; path_inc_x = 67; path_inc_y = 0; path_start_t = 6; num_path_points = 58; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level4.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } else if (sub_level == 5) { fish_to_save_at_start = fish_to_save = 150; path_speed = 0.4; path_inc_x = 0; path_inc_y = 60; path_start_t = 24; num_path_points = 48; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level5.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } path_speed += episode * 0.08; path_t0 = 0; path_last_t = 0; for (int k = 0; k < num_path_points; k++) { path_last_t += path[k].dist_to_next; } path_last_t /= 2 * RAD_BUBBLE; bubbles = new Bubble[MAX_BUBBLES]; for (int k = 0; k < bubbles.length; k++) { bubbles[k] = new Bubble(); } first_bub = new Bubble(); first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; Point2D.Double pnt = getPathPoint(0); first_bub.x = pnt.x; first_bub.y = pnt.y; next_bubble = getRandomBubble(true); next_bubble2 = getRandomBubble(true); } public void draw (Graphics2D context) { if (game_state == GS_MAINMENU) { bm_bg_menu.render(context); } else if (game_state == GS_LEVEL_COMPLETED) { bm_bg_game.render(context, 0, 0); bm_lev_comp.render(context, 90, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 151, "Fish Saved:"); drawOutlined(context, 340, 168, "" + total_fish_saved); drawOutlined(context, 140, 151, "Max Combo:"); drawOutlined(context, 140, 168, "" + longest_combo); drawOutlined(context, 240, 205, "Level Score:"); drawOutlined(context, 240, 222, "" + level_score); context.setFont(fnt); context.setColor(Color.WHITE); bm_click_to_continue.render(context, 156, 290); drawParts(context); drawBar(context); } else if (game_state == GS_GAME_OVER) { bm_bg_game.render(context, 0, 0); if (completed_the_game) { context.setColor(Color.WHITE); context.setFont(fnt2); bm_congrats.render(context, 50, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 175, "Fish Saved:"); drawOutlined(context, 340, 192, "" + total_fish_saved); drawOutlined(context, 140, 175, "Final Score:"); drawOutlined(context, 140, 192, "" + total_score); } else { bm_game_over.render(context, 132, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 240, 111, "Fish Saved:"); drawOutlined(context, 240, 128, "" + total_fish_saved); drawOutlined(context, 240, 155, "Final Score:"); drawOutlined(context, 240, 172, "" + total_score); } drawParts(context); drawBar(context); bm_click_to_continue.render(context, 156, 290); } else if (game_state == GS_PLAY) { bm_bg_game.render(context, 0, 0); drawPath(context); drawParts(context); drawItems(context); bob_x = game.getMouseX(); int y_offset = (int)(5 * Math.sin(shoot_time * Math.PI)); if (torpedo) { bm_torpedo.setX(bob_x - bm_torpedo.getWidth() / 2); bm_torpedo.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_torpedo.render(context); } else if (smrocks > 0) { bm_smrock.setX(bob_x - bm_torpedo.getWidth() / 2); bm_smrock.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_smrock.render(context); } else { if (shoot_time >= 1) { next_bubble.setX(bob_x - next_bubble.getWidth() / 2); next_bubble.setY(bob_y - next_bubble.getHeight() + y_offset); next_bubble.render(context); } else { int x_offset = (int)(shoot_time * 2 * RAD_BUBBLE); next_bubble.setX(bob_x - x_offset / 2); next_bubble.setY((bob_y + (1 - shoot_time) * 4 * RAD_BUBBLE) - next_bubble.getHeight() + y_offset); next_bubble.render(context); } // BUGBUG: change size to 16x16 next_bubble2.render(context, (int)((bob_x - 16 / 2) + 1), (int)(((bob_y - 4) + y_offset) + (1 - shoot_time) * 16)); } bm_bob[(int)bob_akey].render(context, bob_x - 22, bob_y + y_offset); drawBar(context); if (name_show < 1 && !paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Level " + (episode + 1) + "-" + sub_level); } } if (paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Paused"); context.setFont(fnt); context.setColor(Color.BLACK); context.drawString("Press space to continue", 240, 190); } } void drawParts (Graphics2D context) { for (Part part = parts; part != null; part = part.next) { if (part.life < 0.999) { part.draw(context); } } } void drawPath (Graphics2D context) { int x = 0; int y = 0; double t = 0; for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (path_t0 + bubble.t < path_last_t - 1) { if (bubble.fish_inside) { bm_smfish.setX(bubble.x - 8); bm_smfish.setY(bubble.y - 6 + 2 * Math.sin(bubble.phase * PI_2)); bm_smfish.render(context); } double x_scale = 1 - bubble.trans; x = (int)(bubble.trans * bubble.attach_x + x_scale * bubble.x); if (path_t0 + bubble.t >= path_last_t - 4) { double y_scale = ((path_t0 + bubble.t) - (path_last_t - 4)) / 4; y = (int)((bubble.trans * bubble.attach_y + x_scale * bubble.y) + 3 * Math.sin(bubble.phase * PI_2) * (1 - y_scale) + 4 * Math.sin(PI_2 * akey2) * y_scale); } else { y = (int)(bubble.trans * bubble.attach_y + x_scale * bubble.y + 3 * Math.sin(bubble.phase * PI_2)); } bubble.bm.render(context, x - RAD_BUBBLE, y - RAD_BUBBLE); } t = bubble.t; } t += path_t0 + 1 + st_timer * (path_t0 + path_last_t - t); for (double t1 = Math.floor(t); t1 < path_last_t; t1 += 0.5) { Point2D.Double pnt = getPathPoint(t1); y = (int)(pnt.y + 3 * Math.sin(PI_2 * akey1 + t1)); bm_part_bub[3].render(context, (int)pnt.x - 2, y - 2); } x = (int)(path[num_path_points - 1].x - 55 + (1 - Math.sin(0.5 * Math.PI + 0.5 * Math.PI * st_timer)) * (480 - x)); y = (int)path[num_path_points - 1].y; bm_evil_fish.render(context, x, (y + (int)(4 * Math.sin(PI_2 * akey2))) - 40); } void drawItems (Graphics2D context) { for (Item item = items; item != null; item = item.next) { int x = (int)(item.x + 3 * Math.sin(PI_2 * akey1)); int y = (int)item.y; if (4 * item.time_existed < 1 && item.vel_y > 0) { double t = 4 * item.time_existed; int w = (int)(item.bm.getWidth() * t); int h = (int)(item.bm.getHeight() * t); // BUGBUG: change size item.bm.render(context, x - w / 2, y - h / 2); } else { item.bm.render(context, x, y); } } if (shot_bubble.bm != null) { shot_bubble.bm.render(context, (int)shot_bubble.x, (int)shot_bubble.y); } } void drawBar (Graphics2D context) { int w = bm_fisho.getWidth(); @SuppressWarnings("unused") int h = (int)(w * ((fish_to_save_at_start - fish_to_save) / fish_to_save_at_start)); // BUGBUG: change size bm_fisho.render(context, 276, 342); context.setColor(Color.WHITE); context.setFont(fnt); context.drawString(scoreString(), 63, 354); context.drawString((episode + 1) + " - " + sub_level, 190, 354); } void drawOutlined (Graphics2D context, int x, int y, String text) { // BUGBUG: center context.setColor(Color.BLACK); context.drawString(text, x - 2, y - 2); context.drawString(text, x - 2, y + 2); context.drawString(text, x + 2, y + 2); context.drawString(text, x + 2, y - 2); context.drawString(text, x - 2, y); context.drawString(text, x, y + 2); context.drawString(text, x + 2, y); context.drawString(text, x, y - 2); context.setColor(new Color(0xECD300)); context.drawString(text, x, y); } public void update (double elapsedTime) { if (paused || game_state != GS_PLAY) { return; } if (!level_completed && !game_over && !existsInPath(next_bubble)) { next_bubble = getRandomBubble(false); } akey0 = (akey0 + elapsedTime) % 1.0; akey1 = (akey1 + 0.7 * elapsedTime) % 1.0; akey2 = (akey2 + 0.5 * elapsedTime) % 1.0; akey3 = (akey3 + 0.3 * elapsedTime) % 1.0; bob_akey = (bob_akey + 2 * elapsedTime) % NUM_BOB_STATES; time_paused = Math.max(0, time_paused - elapsedTime); time_rewind = Math.max(0, time_rewind - elapsedTime); shoot_time = Math.min(1, shoot_time + 3 * elapsedTime); name_show += 0.7 * elapsedTime; score_show += Math.min(4, (int)(5 * elapsedTime * (total_score - score_show))); score_show = Math.min(score_show, total_score); updateParts(elapsedTime); updateItems(elapsedTime); updateBubbles(elapsedTime); } void updateParts (double time) { Part dead = null; for (Part part = parts; part != null; part = part.next) { part.life -= part.speed * time; if (part.life <= 0.001) { if (dead == null) { parts = part.next; } else { dead.next = part.next; } } else if (part.life < 0.999) { part.x += time * part.vx; part.y += time * part.vy; dead = part; } } } void updateItems (double time) { Item dead = null; for (Item item = items; item != null; item = item.next) { item.y += time * item.vel_y; if (item.y < -21 || item.y > 380 || item.type == ITEM_FREE) { if (dead == null) { items = items.next; } else { dead.next = item.next; } } else { item.time_existed += time; if (item.type == ITEM_TORPEDO || item.type == ITEM_SMROCKS) { if (item.type == ITEM_TORPEDO) { item.vel_y -= 400 * time; } for ( ; Math.abs(item.y - item.py) > 4; item.py -= 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-5, 5); addPart(partbub); } for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { double dx = item.x - bubble.x; double dy = item.y - bubble.y; if (dx * dx + dy * dy < RAD_BUBBLE * RAD_BUBBLE) { if (item.type == ITEM_TORPEDO) { for (Bubble bubble1 = first_bub; bubble1 != null; bubble1 = bubble1.next) { spawnBiggerBurst(item.x, item.y); double ddx = item.x - bubble1.x; double ddy = item.y - bubble1.y; if (ddx * ddx + ddy * ddy < 4096 && path_t0 + bubble1.t > 0) { spawnBurst(bubble1.x, bubble1.y); if (bubble1.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble1.next != null) { bubble1.next.shot = true; bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } else { first_bub = bubble1.next; } } } game.playSound(snd_explosion); shoot_time = 0.5; } else if (item.type == ITEM_SMROCKS) { spawnBurst(bubble.x, bubble.y); if (bubble.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble.x, bubble.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble.next != null) { bubble.next.shot = true; bubble.next.prev = bubble.prev; } if (bubble.prev != null) { bubble.prev.next = bubble.next; } else { first_bub = bubble.next; } game.playSound(snd_pop); } item.type = ITEM_FREE; if (first_bub == null) { if (fish_to_save <= 0) { level_completed = true; } else { first_bub = new Bubble(); first_bub.t = -path_t0 - 1; first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; } } } } } else { for ( ; Math.abs(item.y - item.py) > 4; item.py += 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-5, 5); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-7, 7); addPart(partbub); } if (item.bonus != null && Math.abs(item.x - bob_x) < 25 && Math.abs(item.y - (bob_y + 20)) < 38) { spawnBurst(item.x, item.y); game.playSound(snd_pick); PartString partstring = new PartString(this, item.x, item.y, item.bonus.name, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); shoot_time = 0.5; item.bonus.act(); if (dead == null) { items = items.next; } else { dead.next = item.next; } } } dead = item; } } } void updateBubbles (double elapsedTime) { double acc = path_speed * 1.5; Bubble bubble = getLastBubble(); if (bubble != null) { if (game_starting) { double t = path_t0 + bubble.t; if (t < path_start_t - 8) { acc *= 25; } else if (t < path_start_t) { acc *= 1 + (24 * (path_start_t - t)) / 8; } else { game_starting = false; } } double t = (path_t0 + bubble.t) / path_last_t; if (time_paused <= 0) { if (t < 0.7) { if (t > 0.1) { handicap += 0.1 * (0.7 - t) * elapsedTime; } else { handicap += 0.06 * elapsedTime; } } else if (t > 0.7) { handicap -= 0.15 * (t - 0.7) * elapsedTime; } } handicap = Math.max(0.95, Math.min(handicap, 4)); acc *= handicap; if (t < 0.4) { t = 1 + 15 * (0.4 - t); } else if (t > 0.8) { if (t > 0.95) { t = 0.95; } t = 2.5 * (1 - t); if (t < 0.15) { t = 0.15; } } else { t = 0.5 + 0.5 * (1 - (t - 0.4) / 0.4); } acc *= t; } acc = Math.max(0.2, acc); if (time_paused > 0) { double factor = 1; if (time_paused > 5) { factor = 1 - (MAX_TIME_PAUSED - time_paused); } else if (time_paused > 1) { factor = 0; } else if (time_paused > 0) { factor = 1 - time_paused; } acc *= factor; } if (time_rewind > 0) { double factor = 0; if (time_rewind > 3) { factor = 4 - time_rewind; } else if (time_rewind > 1) { factor = 1; } else if (time_rewind > 0) { factor = 1 * time_rewind; } acc = acc * (1 - factor) - 3 * factor; } if (game_over) { acc += go_speedup; go_speedup += 32 * elapsedTime; } else { acc = Math.max(-12, Math.min(acc, 12)); } acc *= elapsedTime; if (bubble != null && (path_t0 + bubble.t > 0 || acc > 0)) { path_t0 += acc; } if (game_over) { if (first_bub == null) { st_timer += elapsedTime; } if (st_timer > 1) { game_state = GS_GAME_OVER; } } if (level_completed) { st_timer += elapsedTime; if (st_timer > 1) { if (game_state != GS_LEVEL_COMPLETED) { game.playSound(snd_lev_comp); } game_state = GS_LEVEL_COMPLETED; } return; } double shot_y = shot_bubble.y; shot_bubble.y -= 620 * elapsedTime; if (shot_bubble.bm != null) { for (double part_y = shot_bubble.y; part_y < shot_y; part_y += 5) { PartBub partbub = new PartBub(this, shot_bubble.x, part_y, bm_part_bub[0], randDouble(3, 4.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-40, 0); partbub.x += randDouble(-7, 7); addPart(partbub); } } if (shot_bubble.y < -2 * RAD_BUBBLE) { shot_bubble.bm = null; } Bubble bubble1 = first_bub; while (!game_over && fish_to_save > 0 && first_bub.x > -2 * RAD_BUBBLE) { bubble1 = new Bubble(); bubble1.phase = first_bub.phase - 0.1; bubble1.fish_inside = true; bubble1.shot = false; first_bub.prev = bubble1; bubble1.next = first_bub; bubble1.t = first_bub.t - 1; bubble1.bm = getRandomBubble(true); first_bub = bubble1; updateBubble(first_bub); } for ( ; bubble1 != null; bubble1 = bubble1.next) { if (path_t0 + bubble1.t >= path_last_t) { if (!game_over) { game.playSound(snd_bob_loses); } game_over = true; if (bubble1.prev != null) { bubble1.prev.next = null; } if (bubble1 == first_bub) { first_bub = null; return; } } bubble1.phase += (elapsedTime % 1.0); bubble1.trans = Math.max(0, bubble1.trans - 4 * elapsedTime); updateBubble(bubble1); if (shot_bubble.bm != null && shot_bubble.y - 2 * RAD_BUBBLE <= bubble1.y + 8 && shot_y + 2 * RAD_BUBBLE + 10 > bubble1.y + 8 && Math.abs(shot_bubble.x - bubble1.x) < 15) { Bubble bubble2 = new Bubble(); bubble2.bm = shot_bubble.bm; bubble2.shot = true; bubble2.trans = 1; bubble2.attach_x = shot_bubble.x; bubble2.attach_y = shot_bubble.y; double f10 = (bubble1.prev != null) ? Math.min(bubble1.prev.x, bubble1.x) : bubble1.x - RAD_BUBBLE; double f11 = (bubble1.prev != null) ? Math.max(bubble1.prev.x, bubble1.x) : bubble1.x; double f12 = (bubble1.prev != null) ? bubble1.prev.x - bubble1.x : (bubble1.next != null) ? bubble1.x - bubble1.next.x : 1; double f15 = (bubble1.prev != null) ? bubble1.prev.y - bubble1.y : (bubble1.next != null) ? bubble1.y - bubble1.next.y : 0; double f16 = Math.sqrt(f12 * f12 + f15 * f15); f15 /= f16; boolean flag2 = true; if (Math.abs(f15) > 0.4) { flag2 = (f15 < 0); } else { flag2 = ! ((bubble1.prev != null && shot_bubble.x > f10 || bubble1.prev == null) && shot_bubble.x < f11); } if (!flag2) { bubble2.next = bubble1; bubble2.prev = bubble1.prev; bubble2.t = bubble1.t - 0.5; if (bubble1.prev != null) { bubble1.prev.next = bubble2; } else { first_bub = bubble2; } bubble1.prev = bubble2; } else { bubble2.prev = bubble1; bubble2.next = bubble1.next; bubble2.t = bubble1.t + 0.5; if (bubble1.next != null) { bubble1.next.prev = bubble2; } bubble1.next = bubble2; } shot_bubble.bm = null; } if (bubble1.next != null) { int i = 1; boolean flag = bubble1.shot; if (bubble1.prev == null || bubble1.prev.bm != bubble1.bm) { for (Bubble bubble3 = bubble1.next; bubble3 != null && bubble3.bm == bubble1.bm; bubble3 = bubble3.next) { if (bubble3.t - (i + bubble1.t) > 0.01) { i = 0; break; } if (bubble3.shot) { flag = true; } i++; } } if (flag && i >= 3) { game.playSound(snd_plip_plop); level_score += i * 50; total_score += i * 50; if (!isSomeBonusActing() && (randInt(16) == 4 || i >= 4 && randInt(10) <= i)) { double f13 = (path_t0 + bubble.t) / path_last_t; if(f13 > 0.4) { Item item = new Item(); item.type = 3; item.x = bubble1.x; item.y = item.py = bubble1.y; item.vel_y = 70; item.bonus = getRandomBonus(); item.bm = item.bonus.icon; if(items == null) { items = item; } else { item.next = items.next; items.next = item; } } } boolean flag1 = false; int j = 1; double curr_x = 0; double curr_y = 0; for (int k = i; k > 0; k--) { curr_x += bubble1.x; curr_y += bubble1.y; j += bubble1.combo; if (bubble1.fish_inside) { total_fish_saved++; fish_to_save--; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } spawnBurst(bubble1.x, bubble1.y); if (bubble1.next != null) { bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } if (bubble1 == first_bub) { first_bub = bubble1.next; } if (bubble1.next != null) { bubble1 = bubble1.next; } else { flag1 = true; bubble1 = bubble1.prev; } } curr_x /= i; curr_y /= i; if (bubble1 != null && adjIsGoingToBurst(bubble1)) { bubble1.combo = j; } if (j > 1) { PartString partstring = new PartString(this, curr_x, curr_y, "Combo " + j + "x", 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } if (longest_combo < j) { longest_combo = j; } if (j > 0) { j--; } if (j > 7) { j = 7; } game.playSound(snd_combo[j]); Bubble bubble6 = bubble1; if (bubble6 != null && bubble6.prev != null && bubble6.bm == bubble6.prev.bm && !flag1) { bubble6.shot = true; } } if (bubble1 == null) { if (fish_to_save <= 0) { level_completed = true; } if (level_completed) { first_bub = null; return; } else { first_bub = bubble1 = new Bubble(); bubble1.bm = getRandomBubble(false); bubble1.t = -path_t0; updateBubble(bubble1); return; } } if (bubble1.next == null) { return; } double f14 = Math.abs(bubble1.next.t - bubble1.t); if (f14 < 0.99) { for (Bubble bubble4 = bubble1.next; bubble4 != null; bubble4 = bubble4.next) { double f18 = 6 * (1 - f14) * elapsedTime; if (f18 > f14) f18 = f14; bubble4.t += f18; } } if (f14 > 1.01) { for(Bubble bubble5 = bubble1.next; bubble5 != null; bubble5 = bubble5.next) { double f19 = 2 * f14 * elapsedTime; if (f19 > 0.15) { f19 = 0.15; } if (f19 > f14) { f19 = f14; } bubble5.t -= f19; } } } if (bubble1.combo > 0 && !adjIsGoingToBurst(bubble1)) { bubble1.combo = 0; } } } void updateBubble (Bubble bubble) { Point2D.Double tp = getPathPoint(path_t0 + bubble.t); bubble.x = tp.x; bubble.y = tp.y; } public void handleInput () { if (game.keyPressed(KeyEvent.VK_SPACE)) { if (game_state == GS_PLAY) { game.playSound(snd_pick); paused = !paused; } else { paused = false; } } if (game.click()) { if (game_state == GS_LEVEL_COMPLETED) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; if (level / 5 + 1 >= 4) { completed_the_game = true; game_state = GS_GAME_OVER; } initLevel(level + 1); } else if (game_state == GS_GAME_OVER) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_MAINMENU) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_PLAY && !paused) { if (smrocks > 0) { game.playSound(snd_shoot_bubble); smrocks--; Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -360; item.type = ITEM_SMROCKS; item.bonus = null; item.bm = bm_smrock; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; PartString partstring = new PartString(this, item.x, item.y, "" + smrocks, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } else if (torpedo) { torpedo = false; game.playSound(snd_shoot_bubble); Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -120; item.type = ITEM_TORPEDO; item.bonus = null; item.bm = bm_torpedo; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; } else if (shot_bubble.bm != null) { return; } else if (shoot_time < 0.8) { return; } else { game.playSound(snd_shoot_bubble); shot_bubble.bm = next_bubble; next_bubble = next_bubble2; next_bubble2 = getRandomBubble(false); shot_bubble.x = game.getMouseX(); shot_bubble.y = bob_y - 10; shoot_time = 0; } } } if (game.rightClick()) { game.playSound(snd_swap); Sprite next = next_bubble; next_bubble = next_bubble2; next_bubble2 = next; shoot_time = 0.5; } } void addPart (Part part) { if (parts == null) { parts = part; } else { part.next = parts; parts = part; } } Point2D.Double getPathPoint (double idx) { if (idx < 0) { return new Point2D.Double(-30, -400); } double idx_dist = idx * 2 * RAD_BUBBLE; double curr_dist = 0; for (int i = 0; i < num_path_points; i++) { double next_dist = curr_dist + path[i].dist_to_next; if (idx_dist < next_dist) { double curr_idx = (idx_dist - curr_dist) / path[i].dist_to_next; return new Point2D.Double(path[i].x + (path[i + 1].x - path[i].x) * curr_idx, path[i].y + (path[i + 1].y - path[i].y) * curr_idx); } curr_dist = next_dist; } return new Point2D.Double(path[num_path_points - 1].x, path[num_path_points - 1].y); } void setPathPoint (int idx, double x, double y) { path[idx] = new PathPoint(); path[idx].x = (x + path_inc_x) * 0.71; path[idx].y = (y + path_inc_y - 10) * 0.71; if (idx > 0) { double dx = path[idx - 1].x - path[idx].x; double dy = path[idx - 1].y - path[idx].y; path[idx - 1].dist_to_next = Math.sqrt(dx * dx + dy * dy); } num_path_points = idx + 1; } boolean existsInPath (Sprite bub) { for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (bubble.bm == bub) { return true; } } return false; } Bubble getLastBubble () { if (first_bub == null) return null; Bubble bubble; for (bubble = first_bub; bubble.next != null; bubble = bubble.next) ; return bubble; } boolean adjIsGoingToBurst (Bubble bubble) { Sprite s = bubble.bm; int i = 1; for (Bubble b = bubble.prev; b != null && b.bm == s; b = b.prev) i++; for (Bubble b = bubble.next; b != null && b.bm == s; b = b.next) i++; return i >= 3; } void spawnBiggerBurst (double x, double y) { for (int i = 0; i < 30; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(140, 310); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 3.8)); partbub.life += randDouble(0, 0.4); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle); partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } void spawnBurst (double x, double y) { y += 5; for (int i = 0; i < 26; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(50, 100); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 4.2)); partbub.life += randDouble(0, 0.2); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle) - magnitude; partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } Sprite getRandomBubble (boolean totally_random) { int max = 3 + (episode + 1) / 2; if (totally_random) { return bm_bubbles[randInt(max)]; } for (int j = 0; j < 300; j++) { Sprite bub = bm_bubbles[randInt(max)]; if (existsInPath(bub)) { return bub; } } System.out.println("stalled."); return bm_bubbles[randInt(max)]; } Bonus getRandomBonus () { int i = randInt(num_bonuses); Bonus bonus = bonuses; for (bonus = bonuses; i != 0; bonus = bonus.next, i--) ; return bonus; } int randInt (int max) { return (int)(Math.random() * max); } double randDouble (double min, double max) { return min + Math.random() * (max - min); } String scoreString () { StringBuffer stringbuffer = new StringBuffer(score_show); for (int i = stringbuffer.length() - 1 - 2; i > 0; i -= 3) { stringbuffer.insert(i, "0"); } return stringbuffer.toString(); } }
Java
package game.tests; public class IEventHandler { }
Java
package game.tests; import com.golden.gamedev.Game; /** * @author Conrad, Shun * This abstractGameState class controls all states of the Game utilizing the GameLoop and * various added classes * also, we assume that game loop just initializes things */ public abstract class AbstractGameState { private GameManager gameManager; /** * This is the general constructor for the class, it is mainly implemented for reflection * purposes */ public AbstractGameState(){ } /** * This generic run method delegates different update and render methods to their respective * gameState classes */ public abstract void run(GameLoop gameLoop); /** * This abstract method adds a response/action sequence to generic list of registered events * that will eventually be passed onto the Event Team, gameManager class */ protected abstract void addEvent(String eventName, IEventHandler method); /** * This method is registered to an event. When that event occurs while in another * game state, this method will be called, setting the currentGameState within the * game loop, to this class * the next time the game loop executes, this class' run method will be called */ public void startGameState(GameLoop gameLoop){ //create an Event filter and alter other methods accordingly } }
Java
package game.tests; /** * @author Conrad, Shun * AbstractTransition class acts as the central hub to all transition classes that can be * implemented between gameState. It is used to add a visual element (be it fade, flashes, etc.) * to what goes on when the states change */ public abstract class AbstractTransition { /**' * This method adds commonly used visual transitions to the GTGE display as it moves through * different GamesStates. (Decorator) */ public AbstractTransition(GameLoop gameLoop){ runTransition(gameLoop); } /** * runTransition performs some commonly used visual transition on a GTGE display, renders */ public abstract void runTransition(GameLoop gameLoop); }
Java
package game.tests; public class GameManager { }
Java
package game.tests; import static org.junit.Assert.*; import game.TxtParser; import java.io.File; import org.junit.Test; public class TxtParserTest { @Test public void testParseInputObject() { File asdf = new File("resources/properties/level1properties.txt"); TxtParser t = new TxtParser(asdf); System.out.println(t.getBubblePathPoints()); } }
Java
package game.tests; import java.awt.Color; public class ExampleTransition extends AbstractTransition{ public ExampleTransition(GameLoop gameLoop){ super(gameLoop); } /** * I'm not sure what the exact syntax would be but the * method would basically render whatever the transition would * be for a set amount of time. */ public void runTransition(GameLoop gameLoop) { gameLoop.setBackground(Color.BLACK); } }
Java
package game.tests; /** * @author Conrad, Shun * The GenericGameStateClass acts as a basic extension to AbstractGameState. It allows the user to get * specific about what exactly they desire to update in each gameState. */ public class ExampleGameState extends AbstractGameState{ /** * myName is used to identify individual gameStates from one another. */ public String myName; /** * The GenericGameState constructor basically operates to set existing game conditions * to a Game. It is also used for reflective purposes. */ public ExampleGameState(String name){} @Override public void run(GameLoop gameLoop) {} @Override protected void addEvent(String eventName, IEventHandler method) {} @Override public void startGameState(GameLoop gameLoop){ } }
Java
package game.tests; public class GameLoop { }
Java
package game; import com.golden.gamedev.object.Sprite; public class BonusSmRocks extends AbstractBonus { private int smallRocks; public BonusSmRocks (ProgBob progBob, String name, Sprite icon){ super(progBob, name, icon); smallRocks = 0 ; } public BonusSmRocks(){ new BonusSmRocks(super.progBob, "Small Rocks", new Sprite(createBufferedImage("resources/bon_smrocks.png"))); } @Override public void toggleBonus(){ smallRocks = 6; } @Override public boolean isOn() { bonusBoolean = false; if(smallRocks>0){ bonusBoolean = true; } return bonusBoolean; } public void decrement(){ smallRocks--; } @Override public void turnOff() { smallRocks = 0; } @Override public void turnOn() { bonusBoolean = true; } public int getRocks(){ return smallRocks; } }
Java
package game; public class PathPoint { double x; double y; double dist_to_next; }
Java
package game; import java.awt.Graphics2D; import com.golden.gamedev.object.Sprite; public class PartBub extends Part { public PartBub (ProgBob progBob, double x, double y, Sprite icon, double speed) { super(progBob, x, y, icon, speed); } @Override public void draw (Graphics2D context) { icon = progBob.bm_part_bub[(int)((1 - life) * 4)]; super.draw(context); } }
Java
package game; //test import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import java.io.File; import java.util.ArrayList; import com.golden.gamedev.Game; import com.golden.gamedev.object.Sprite; /** * commented version of program bob * @author Shun * */ public class ProgBob1 { final static int RAD_BUBBLE = 13; //radius of bub //final static int RAD_BUBBLE = 7;//test final static int W_SMFISH = 8; final static int H_SMFISH = 6; final static int GS_MAINMENU = 0; final static int GS_PLAY = 1; final static int GS_LEVEL_COMPLETED = 2; final static int GS_GAME_OVER = 3; final static int ITEM_FREE = 0; final static int ITEM_BUBBLE = 1; final static int ITEM_TORPEDO = 2; final static int ITEM_BONUS = 3; final static int ITEM_SMROCKS = 4; final static int NUM_BOB_STATES = 11; final static int MAX_BUBBLES = 128; //final static int MAX_BUBBLES = 12;//test line final static double MAX_TIME_PAUSED = 6; //final static double MAX_TIME_PAUSED = 20;//test final static double MAX_TIME_REWIND = 4; final static double PI_2 = 2 * Math.PI; Font fnt; Font fnt2; Font fnt3; Font fnts[]; Sprite bm_bob[]; Sprite bm_bubbles[]; Sprite bm_evil_fish; Sprite bm_smfish; Sprite bm_torpedo; Sprite bm_smrock; Sprite bm_fisho; Sprite bm_click_to_continue; Sprite bm_congrats; Sprite bm_bg_menu; Sprite bm_bg_game; Sprite bm_lev_comp; Sprite bm_loading; Sprite bm_game_over; Sprite bm_part_bub[]; String snd_level_start; String snd_explosion; String snd_shoot_bubble; String snd_plip_plop; String snd_pop; String snd_bob_loses; String snd_pick; String snd_swap; String snd_lev_comp; String snd_combo[]; boolean torpedo; int smrocks; double name_show; int episode; int sub_level; int total_fish_saved; int longest_combo; double handicap; int game_state; // the state of the game boolean game_starting; boolean completed_the_game; double time_rewind; double time_paused; int num_bonuses; Bonus bonuses; Part parts; Item items; int num_path_points; PathPoint path[]; double path_t0; //position first little bubble? double path_speed; //speed of the path int fish_to_save; int fish_to_save_at_start; double path_last_t;//distance to last little bubble? double path_start_t; //at which little bubble does the big bubbles start. Bubble bubbles[]; Bubble first_bub;// first bub is actually the bubble farthest from the front Bubble shot_bubble; Sprite next_bubble; Sprite next_bubble2; int bob_y; int bob_x; double bob_akey; double akey0; double akey1; double akey2; double akey3; double shoot_time; boolean game_over; double go_speedup; int level; boolean level_completed; double st_timer; int level_score; int total_score; int score_show; boolean paused; int path_inc_x; int path_inc_y; Game game; int fansbubblecount = 0;//test boolean isSomeBonusActing () { return time_rewind > 0 || time_paused > 0 || items != null || smrocks > 0 || torpedo; //this is bad, long boolean statement } public void init (Game game) //called by game init resources { this.game = game; fnt = Font.decode("Arial-BOLD-16"); fnt2 = Font.decode("Arial-BOLD-20"); fnt3 = Font.decode("Arial-PLAIN-14"); fnts = new Font[11]; for (int k = 0; k < 11; k++) { fnts[k] = Font.decode("Arial-PLAIN-" + (k + 2)); } Part part = new Part(this, 10, 10, null, 0); for (int k = 0; k < 100; k++) { part.next = new Part(this, 10, 10, null, 0); part = part.next; } for (int k = 0; k < 100; k++) { part.next = new PartBub(this, 10, 10, null, 0); part = part.next; } // load resources bm_loading = new Sprite(game.getImage("resources/loading.jpg")); bm_click_to_continue = new Sprite(game.getImage("resources/click_to_continue.png")); bm_congrats = new Sprite(game.getImage("resources/congrats.png")); bm_bob = new Sprite[NUM_BOB_STATES]; bm_bob[0] = new Sprite(game.getImage("resources/bob_0000.png")); bm_bob[1] = new Sprite(game.getImage("resources/bob_0002.png")); bm_bob[2] = new Sprite(game.getImage("resources/bob_0004.png")); bm_bob[3] = new Sprite(game.getImage("resources/bob_0006.png")); bm_bob[4] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[5] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[6] = new Sprite(game.getImage("resources/bob_0010.png")); bm_bob[7] = new Sprite(game.getImage("resources/bob_0012.png")); bm_bob[8] = new Sprite(game.getImage("resources/bob_0014.png")); bm_bob[9] = new Sprite(game.getImage("resources/bob_0016.png")); bm_bob[10] = new Sprite(game.getImage("resources/bob_0018.png")); bm_evil_fish = new Sprite(game.getImage("resources/evil_fish.png")); bm_smfish = new Sprite(game.getImage("resources/smfish.png")); snd_shoot_bubble = "resources/release_bubble.au";//sound of combo snd_combo = new String[8]; snd_combo[0] = "resources/combo_01.au"; snd_combo[1] = "resources/combo_02.au"; snd_combo[2] = "resources/combo_03.au"; snd_combo[3] = "resources/combo_04.au"; snd_combo[4] = "resources/combo_05.au"; snd_combo[5] = "resources/combo_06.au"; snd_combo[6] = "resources/combo_07.au"; snd_combo[7] = "resources/combo_08.au"; snd_plip_plop ="resources/pop_01.au"; snd_pop = "resources/pop_01.au"; snd_bob_loses = "resources/bob_loses.au"; snd_pick = "resources/pickup.au"; snd_swap = "resources/gulp.au"; //sound when right click swap bubbles snd_lev_comp = "resources/lev_comp_song.au"; snd_level_start = "resources/level_start.au"; snd_explosion = "resources/explosion.au"; bm_bubbles = new Sprite[7]; bm_bubbles[0] = new Sprite(game.getImage("resources/blue.png")); bm_bubbles[1] = new Sprite(game.getImage("resources/red.png")); bm_bubbles[2] = new Sprite(game.getImage("resources/green.png")); bm_bubbles[3] = new Sprite(game.getImage("resources/orange.png")); bm_bubbles[4] = new Sprite(game.getImage("resources/purple.png")); bm_bubbles[5] = new Sprite(game.getImage("resources/cyan.png")); bm_bubbles[6] = new Sprite(game.getImage("resources/white.png")); bm_bg_game = new Sprite(game.getImage("resources/seagrass.jpg")); bm_bg_menu = new Sprite(game.getImage("resources/bg_menu.jpg")); bm_lev_comp = new Sprite(game.getImage("resources/lev_comp.png")); bm_game_over = new Sprite(game.getImage("resources/game_over.png")); bm_part_bub = new Sprite[4]; bm_part_bub[0] = new Sprite(game.getImage("resources/part_bub_01.png"));//small bubbles bm_part_bub[1] = new Sprite(game.getImage("resources/part_bub_02.png")); bm_part_bub[2] = new Sprite(game.getImage("resources/part_bub_03.png")); bm_part_bub[3] = new Sprite(game.getImage("resources/part_bub_04.png")); bm_torpedo = new Sprite(game.getImage("resources/torpedo.png")); bm_smrock = new Sprite(game.getImage("resources/smrock.png")); bm_fisho = new Sprite(game.getImage("resources/fisho_full.png")); bonuses = new BonusPause(this, "Pause", new Sprite(game.getImage("resources/bonus_pause.png"))); bonuses.next = new BonusRewind(this, "Rewind", new Sprite(game.getImage("resources/bonus_rewind.png"))); bonuses.next.next = new BonusTorpedo(this, "Torpedo", new Sprite(game.getImage("resources/bon_torpedo.png"))); bonuses.next.next.next = new BonusSmRocks(this, "Small Rocks", new Sprite(game.getImage("resources/bon_smrocks.png"))); num_bonuses = 4; game_state = GS_MAINMENU; initLevel(1); } void initGame () //restart game variables { total_fish_saved = 0; total_score = 0; level_score = 0; shoot_time = 0; completed_the_game = false; game_over = false; paused = false; } void initLevel (int level_num) //initialize the level { paused = false; level_completed = false; handicap = 1; longest_combo = 0; torpedo = false; smrocks = 0; name_show = 0; time_rewind = 0; time_paused = 0; items = null; game_starting = true; level_score = 0; go_speedup = 0; st_timer = 0;//doesn't really do anything... shot_bubble = new Bubble(); shot_bubble.bm = null; path_speed = 0.5; bob_y = 290; bob_akey = 0; level = level_num; episode = (level - 1) / 5; sub_level = (level - 1) % 5 + 1; if (sub_level == 1) { //set the trail that the trapped fish take //fish_to_save_at_start = fish_to_save = 80; fish_to_save_at_start = fish_to_save = 1; //test line path_speed = 0.4; //path_speed = 2.99;//test line path_inc_x = 320; path_inc_y = -10; path_start_t = 32; //path_start_t = 1;//test line TxtParser txtParser = new TxtParser(); File pointsFile = new File("resources/level1.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); num_path_points = 53; path = new PathPoint[num_path_points]; int j = 0; //for (int i = 0; i < num_path_points; i++) { // j=i; // setPathPoint(i, levelPathPoints.get(i).x, levelPathPoints.get(i).y); //} setPathPoint(j++, 0, 0); setPathPoint(j++, 52, 6); setPathPoint(j++, 6, 72); setPathPoint(j++, -36, 91); setPathPoint(j++, -86, 90); setPathPoint(j++, -129, 90); setPathPoint(j++, -171, 89); setPathPoint(j++, -205, 89); setPathPoint(j++, -225, 89); setPathPoint(j++, -252, 101); setPathPoint(j++, -281, 123); setPathPoint(j++, -275, 146); setPathPoint(j++, -267, 172); setPathPoint(j++, -249, 187); setPathPoint(j++, -218, 190); setPathPoint(j++, -184, 188); setPathPoint(j++, -159, 175); setPathPoint(j++, -131, 162); setPathPoint(j++, -89, 161); setPathPoint(j++, -52, 170); setPathPoint(j++, -28, 181); setPathPoint(j++, -1, 181); setPathPoint(j++, 33, 168); setPathPoint(j++, 63, 149); setPathPoint(j++, 103, 136); setPathPoint(j++, 141, 132); setPathPoint(j++, 180, 132); setPathPoint(j++, 196, 154); setPathPoint(j++, 233, 180); setPathPoint(j++, 245, 206); setPathPoint(j++, 235, 238); setPathPoint(j++, 196, 259); setPathPoint(j++, 139, 265); setPathPoint(j++, 79, 270); setPathPoint(j++, 39, 272); setPathPoint(j++, 3, 272); setPathPoint(j++, -21, 267); setPathPoint(j++, -55, 267); setPathPoint(j++, -97, 267); setPathPoint(j++, -128, 267); setPathPoint(j++, -176, 269); setPathPoint(j++, -213, 271); setPathPoint(j++, -251, 291); setPathPoint(j++, -257, 326); setPathPoint(j++, -235, 351); setPathPoint(j++, -187, 367); setPathPoint(j++, -133, 367); setPathPoint(j++, -75, 368); setPathPoint(j++, 2, 366); setPathPoint(j++, 58, 363); setPathPoint(j++, 112, 350); setPathPoint(j++, 174, 353); setPathPoint(j++, 190, 356); }//*/ /* if (sub_level == 1)//entire section is test { //set the trail that the trapped fish take fish_to_save_at_start = fish_to_save = 80; path_speed = 0.4; path_inc_x = 320; path_inc_y = -10; path_start_t = 32; //path_start_t = 1;//test line num_path_points = 28; path = new PathPoint[num_path_points]; int j = 0; setPathPoint(j++, 0, 0); setPathPoint(j++, 1, 1); setPathPoint(j++, 10, 20); setPathPoint(j++, 1, 30); setPathPoint(j++, 150, 40); setPathPoint(j++, 1, 150); setPathPoint(j++, 150, 40); setPathPoint(j++, 1, 150); setPathPoint(j++, 150, 40); setPathPoint(j++, 1, 150); setPathPoint(j++, 150, 40); setPathPoint(j++, 1, 150); setPathPoint(j++, 150, 40); setPathPoint(j++, 1, 150); setPathPoint(j++, 150, 40); setPathPoint(j++, 1, 150); setPathPoint(j++, 100, 60); setPathPoint(j++, 1, 170); setPathPoint(j++, 150, 150); setPathPoint(j++, 1, 170); setPathPoint(j++, 150, 150); setPathPoint(j++, 1, 170); setPathPoint(j++, 150, 150); setPathPoint(j++, 1, 170); setPathPoint(j++, 150, 150); setPathPoint(j++, 1, 170); setPathPoint(j++, 150, 150); setPathPoint(j++, 190, 356); }//*/ else if (sub_level == 2) { fish_to_save_at_start = fish_to_save = -1;//test //fish_to_save_at_start = fish_to_save = 180; path_speed = 0.5; path_inc_x = 0; path_inc_y = 59; path_start_t = 14; num_path_points = 78; path = new PathPoint[num_path_points]; int j = 0; setPathPoint(j++, -30, 0); setPathPoint(j++, 20, 0); setPathPoint(j++, 57, 0); setPathPoint(j++, 105, 1); setPathPoint(j++, 145, 0); setPathPoint(j++, 213, -2); setPathPoint(j++, 272, 5); setPathPoint(j++, 295, 27); setPathPoint(j++, 291, 57); setPathPoint(j++, 268, 75); setPathPoint(j++, 235, 82); setPathPoint(j++, 182, 90); setPathPoint(j++, 127, 90); setPathPoint(j++, 74, 86); setPathPoint(j++, 53, 96); setPathPoint(j++, 40, 110); setPathPoint(j++, 33, 132); setPathPoint(j++, 40, 151); setPathPoint(j++, 67, 164); setPathPoint(j++, 119, 157); setPathPoint(j++, 169, 155); setPathPoint(j++, 215, 156); setPathPoint(j++, 243, 166); setPathPoint(j++, 255, 189); setPathPoint(j++, 252, 206); setPathPoint(j++, 233, 219); setPathPoint(j++, 188, 220); setPathPoint(j++, 143, 221); setPathPoint(j++, 103, 221); setPathPoint(j++, 77, 221); setPathPoint(j++, 58, 242); setPathPoint(j++, 55, 264); setPathPoint(j++, 66, 277); setPathPoint(j++, 88, 279); setPathPoint(j++, 116, 284); setPathPoint(j++, 154, 292); setPathPoint(j++, 224, 289); setPathPoint(j++, 277, 286); setPathPoint(j++, 311, 286); setPathPoint(j++, 355, 292); setPathPoint(j++, 394, 291); setPathPoint(j++, 466, 288); setPathPoint(j++, 499, 288); setPathPoint(j++, 538, 288); setPathPoint(j++, 565, 281); setPathPoint(j++, 582, 261); setPathPoint(j++, 589, 237); setPathPoint(j++, 572, 208); setPathPoint(j++, 544, 204); setPathPoint(j++, 513, 203); setPathPoint(j++, 483, 203); setPathPoint(j++, 438, 209); setPathPoint(j++, 410, 202); setPathPoint(j++, 393, 186); setPathPoint(j++, 398, 160); setPathPoint(j++, 418, 147); setPathPoint(j++, 439, 142); setPathPoint(j++, 465, 142); setPathPoint(j++, 490, 143); setPathPoint(j++, 514, 145); setPathPoint(j++, 556, 148); setPathPoint(j++, 585, 139); setPathPoint(j++, 597, 115); setPathPoint(j++, 598, 94); setPathPoint(j++, 586, 77); setPathPoint(j++, 556, 70); setPathPoint(j++, 520, 65); setPathPoint(j++, 484, 65); setPathPoint(j++, 453, 66); setPathPoint(j++, 379, 71); setPathPoint(j++, 357, 58); setPathPoint(j++, 344, 32); setPathPoint(j++, 353, 9); setPathPoint(j++, 387, -2); setPathPoint(j++, 423, -4); setPathPoint(j++, 461, -5); setPathPoint(j++, 487, -2); setPathPoint(j++, 515, 8); } else if (sub_level == 3) { fish_to_save_at_start = fish_to_save = 128; //fish_to_save_at_start = fish_to_save = -1;//test path_speed = 0.65; path_inc_x = 10; path_inc_y = 323; path_start_t = 15; num_path_points = 21; path = new PathPoint[num_path_points]; int j = 0; setPathPoint(j++, -40, 0); setPathPoint(j++, 23, 0); setPathPoint(j++, 139, 0); setPathPoint(j++, 270, 0); setPathPoint(j++, 430, 0); setPathPoint(j++, 505, 1); setPathPoint(j++, 538, -3); setPathPoint(j++, 548, -14); setPathPoint(j++, 545, -28); setPathPoint(j++, 536, -48); setPathPoint(j++, 387, -264); setPathPoint(j++, 365, -284); setPathPoint(j++, 342, -286); setPathPoint(j++, 324, -280); setPathPoint(j++, 296, -256); setPathPoint(j++, 98, -79); setPathPoint(j++, 80, -62); setPathPoint(j++, 83, -42); setPathPoint(j++, 104, -36); setPathPoint(j++, 370, -70); setPathPoint(j++, 390, -60); } else if (sub_level == 4) { //fish_to_save_at_start = fish_to_save = 150; fish_to_save_at_start = fish_to_save = -1;//test path_speed = 0.8; path_inc_x = 67; path_inc_y = 0; path_start_t = 6; num_path_points = 58; path = new PathPoint[num_path_points]; int j = 0; setPathPoint(j++, 0, 0); setPathPoint(j++, 0, 8); setPathPoint(j++, -14, 51); setPathPoint(j++, 2, 62); setPathPoint(j++, 32, 69); setPathPoint(j++, 57, 69); setPathPoint(j++, 95, 69); setPathPoint(j++, 129, 69); setPathPoint(j++, 321, 66); setPathPoint(j++, 409, 67); setPathPoint(j++, 469, 71); setPathPoint(j++, 501, 75); setPathPoint(j++, 512, 93); setPathPoint(j++, 495, 113); setPathPoint(j++, 406, 112); setPathPoint(j++, 340, 105); setPathPoint(j++, 267, 105); setPathPoint(j++, 138, 109); setPathPoint(j++, 18, 106); setPathPoint(j++, -12, 124); setPathPoint(j++, -8, 159); setPathPoint(j++, 30, 168); setPathPoint(j++, 94, 169); setPathPoint(j++, 425, 160); setPathPoint(j++, 461, 157); setPathPoint(j++, 487, 157); setPathPoint(j++, 508, 161); setPathPoint(j++, 510, 189); setPathPoint(j++, 488, 203); setPathPoint(j++, 448, 204); setPathPoint(j++, 56, 213); setPathPoint(j++, 6, 210); setPathPoint(j++, -17, 221); setPathPoint(j++, -28, 236); setPathPoint(j++, -20, 253); setPathPoint(j++, -2, 256); setPathPoint(j++, 452, 246); setPathPoint(j++, 502, 248); setPathPoint(j++, 515, 257); setPathPoint(j++, 522, 280); setPathPoint(j++, 510, 302); setPathPoint(j++, 451, 303); setPathPoint(j++, 341, 300); setPathPoint(j++, 247, 302); setPathPoint(j++, 144, 301); setPathPoint(j++, 66, 299); setPathPoint(j++, 12, 294); setPathPoint(j++, -9, 297); setPathPoint(j++, -35, 315); setPathPoint(j++, -38, 336); setPathPoint(j++, -23, 349); setPathPoint(j++, 27, 351); setPathPoint(j++, 103, 351); setPathPoint(j++, 200, 351); setPathPoint(j++, 314, 351); setPathPoint(j++, 401, 343); setPathPoint(j++, 460, 341); setPathPoint(j++, 488, 357); } else if (sub_level == 5) { //fish_to_save_at_start = fish_to_save = 150; fish_to_save_at_start = fish_to_save = -1;//test path_speed = 0.4; path_inc_x = 0; path_inc_y = 60; path_start_t = 24; num_path_points = 48; path = new PathPoint[num_path_points]; int j = 0; setPathPoint(j++, -30, 0); setPathPoint(j++, 41, 0); setPathPoint(j++, 123, -2); setPathPoint(j++, 193, -2); setPathPoint(j++, 239, 0); setPathPoint(j++, 304, 1); setPathPoint(j++, 355, 1); setPathPoint(j++, 439, 6); setPathPoint(j++, 530, 13); setPathPoint(j++, 545, 26); setPathPoint(j++, 556, 81); setPathPoint(j++, 553, 149); setPathPoint(j++, 559, 220); setPathPoint(j++, 552, 260); setPathPoint(j++, 509, 275); setPathPoint(j++, 417, 293); setPathPoint(j++, 258, 288); setPathPoint(j++, 161, 286); setPathPoint(j++, 83, 267); setPathPoint(j++, 60, 235); setPathPoint(j++, 44, 192); setPathPoint(j++, 50, 143); setPathPoint(j++, 60, 83); setPathPoint(j++, 92, 57); setPathPoint(j++, 138, 59); setPathPoint(j++, 223, 59); setPathPoint(j++, 316, 54); setPathPoint(j++, 403, 61); setPathPoint(j++, 456, 67); setPathPoint(j++, 485, 93); setPathPoint(j++, 494, 132); setPathPoint(j++, 494, 172); setPathPoint(j++, 475, 200); setPathPoint(j++, 446, 220); setPathPoint(j++, 415, 222); setPathPoint(j++, 348, 223); setPathPoint(j++, 269, 223); setPathPoint(j++, 194, 209); setPathPoint(j++, 142, 190); setPathPoint(j++, 123, 144); setPathPoint(j++, 140, 112); setPathPoint(j++, 167, 105); setPathPoint(j++, 192, 104); setPathPoint(j++, 230, 109); setPathPoint(j++, 258, 122); setPathPoint(j++, 279, 135); setPathPoint(j++, 305, 140); setPathPoint(j++, 329, 140); } path_speed += episode * 0.08; path_t0 = 0; path_last_t = 0; for (int k = 0; k < num_path_points; k++) { path_last_t += path[k].dist_to_next; } path_last_t /= 2 * RAD_BUBBLE; bubbles = new Bubble[MAX_BUBBLES]; for (int k = 0; k < bubbles.length; k++) { bubbles[k] = new Bubble(); } first_bub = new Bubble(); first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; Point2D.Double pnt = getPathPoint(0); first_bub.x = pnt.x; first_bub.y = pnt.y; next_bubble = getRandomBubble(true); next_bubble2 = getRandomBubble(true); } public void draw (Graphics2D context) //called by game render { if (game_state == GS_MAINMENU) { bm_bg_menu.render(context); } else if (game_state == GS_LEVEL_COMPLETED) //stats to display when level completed { bm_bg_game.render(context, 0, 0); bm_lev_comp.render(context, 90, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 151, "Fish Saved (reviewed by Fan1):"); drawOutlined(context, 340, 168, "" + total_fish_saved); drawOutlined(context, 140, 151, "Max Combo:"); drawOutlined(context, 140, 168, "" + longest_combo); drawOutlined(context, 240, 205, "Level Score:"); drawOutlined(context, 240, 222, "" + level_score); context.setFont(fnt); context.setColor(Color.WHITE); bm_click_to_continue.render(context, 156, 290); drawParts(context); drawBar(context); } else if (game_state == GS_GAME_OVER) //stats to display when game is over { bm_bg_game.render(context, 0, 0); if (completed_the_game) //over because you completed the game { context.setColor(Color.WHITE); context.setFont(fnt2); bm_congrats.render(context, 50, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 175, "Fish Saved (reviewed by Fan2):"); drawOutlined(context, 340, 192, "" + total_fish_saved); drawOutlined(context, 140, 175, "Final Score:"); drawOutlined(context, 140, 192, "" + total_score); } else //over because you lost { bm_game_over.render(context, 132, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 240, 111, "Fish Saved (reviewed by Fan3):"); drawOutlined(context, 240, 128, "" + total_fish_saved); drawOutlined(context, 240, 155, "Final Score:"); drawOutlined(context, 240, 172, "" + total_score); } drawParts(context); drawBar(context); bm_click_to_continue.render(context, 156, 290); } else if (game_state == GS_PLAY) { bm_bg_game.render(context, 0, 0); drawPath(context); drawParts(context); drawItems(context); bob_x = game.getMouseX(); int y_offset = (int)(5 * Math.sin(shoot_time * Math.PI)); if (torpedo) { bm_torpedo.setX(bob_x - bm_torpedo.getWidth() / 2); bm_torpedo.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_torpedo.render(context); } else if (smrocks > 0) { bm_smrock.setX(bob_x - bm_torpedo.getWidth() / 2); bm_smrock.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_smrock.render(context); } else { if (shoot_time >= 1) { next_bubble.setX(bob_x - next_bubble.getWidth() / 2); next_bubble.setY(bob_y - next_bubble.getHeight() + y_offset); next_bubble.render(context); } else { int x_offset = (int)(shoot_time * 2 * RAD_BUBBLE); next_bubble.setX(bob_x - x_offset / 2); next_bubble.setY((bob_y + (1 - shoot_time) * 4 * RAD_BUBBLE) - next_bubble.getHeight() + y_offset); next_bubble.render(context); } // BUGBUG: change size to 16x16 next_bubble2.render(context, (int)((bob_x - 16 / 2) + 1), (int)(((bob_y - 4) + y_offset) + (1 - shoot_time) * 16)); } bm_bob[(int)bob_akey].render(context, bob_x - 22, bob_y + y_offset); drawBar(context); if (name_show < 1 && !paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Level " + (episode + 1) + "-" + sub_level); } } if (paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Paused"); context.setFont(fnt); context.setColor(Color.BLACK); context.drawString("Press space to continue", 240, 190); } } void drawParts (Graphics2D context) { for (Part part = parts; part != null; part = part.next) { if (part.life < 0.999) { part.draw(context); } } } void drawPath (Graphics2D context) // draw the path of bubbles { //all the sine stuff is what makes the bubbles bounce int x = 0; int y = 0; double t = 0; for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (path_t0 + bubble.t < path_last_t - 1) { if (bubble.fish_inside) { bm_smfish.setX(bubble.x - 8); //bm_smfish.setY(bubble.y - 6 + 22 * Math.sin(bubble.phase * PI_2));//test line bm_smfish.setY(bubble.y - 6 + 2 * Math.sin(bubble.phase * PI_2)); bm_smfish.render(context); } double x_scale = 1 - bubble.trans; x = (int)(bubble.trans * bubble.attach_x + x_scale * bubble.x); if (path_t0 + bubble.t >= path_last_t - 4) // what does this line mean => if bubble is close to evil fish { double y_scale = ((path_t0 + bubble.t) - (path_last_t - 4)) / 4; //y = (int)((bubble.trans * bubble.attach_y + x_scale * bubble.y) + 23 * Math.sin(bubble.phase * PI_2) * (1 - y_scale) + 4 * Math.sin(PI_2 * akey2) * y_scale); //test line y = (int)((bubble.trans * bubble.attach_y + x_scale * bubble.y) + 3 * Math.sin(bubble.phase * PI_2) * (1 - y_scale) + 4 * Math.sin(PI_2 * akey2) * y_scale); } else { //y = (int)(bubble.trans * bubble.attach_y + x_scale * bubble.y + 53 * Math.sin(bubble.phase * PI_2)); //test line y = (int)(bubble.trans * bubble.attach_y + x_scale * bubble.y + 3 * Math.sin(bubble.phase * PI_2)); } bubble.bm.render(context, x - RAD_BUBBLE, y - RAD_BUBBLE); } t = bubble.t; } t += path_t0 + 1 + st_timer * (path_t0 + path_last_t - t); //t += path_t0 + 1 + st_timer * (path_t0 + path_last_t - t);//test //small bubbles for (double t1 = Math.floor(t); t1 < path_last_t; t1 += 0.5) //for (double t1 = t; t1 < path_last_t; t1 += 0.25)//test { Point2D.Double pnt = getPathPoint(t1); y = (int)(pnt.y + 3 * Math.sin(PI_2 * akey1 + t1)); //y = (int)(pnt.y + 43 * Math.sin(PI_2 * akey1 + t1)); //test line bm_part_bub[3].render(context, (int)pnt.x - 2, y - 2); } x = (int)(path[num_path_points - 1].x - 55 + (1 - Math.sin(0.5 * Math.PI + 0.5 * Math.PI * st_timer)) * (480 - x)); y = (int)path[num_path_points - 1].y; //bm_evil_fish.render(context, x, (y + (int)(24 * Math.sin(PI_2 * akey2))) - 40); //test line bm_evil_fish.render(context, x, (y + (int)(4 * Math.sin(PI_2 * akey2))) - 40); } void drawItems (Graphics2D context) { for (Item item = items; item != null; item = item.next) { int x = (int)(item.x + 3 * Math.sin(PI_2 * akey1)); int y = (int)item.y; if (4 * item.time_existed < 1 && item.vel_y > 0) { double t = 4 * item.time_existed; int w = (int)(item.bm.getWidth() * t); int h = (int)(item.bm.getHeight() * t); // BUGBUG: change size item.bm.render(context, x - w / 2, y - h / 2); } else { item.bm.render(context, x, y); } } if (shot_bubble.bm != null) { shot_bubble.bm.render(context, (int)shot_bubble.x, (int)shot_bubble.y); } } void drawBar (Graphics2D context) // draw the bar at the bottom { int w = bm_fisho.getWidth(); int h = (int)(w * ((fish_to_save_at_start - fish_to_save) / fish_to_save_at_start)); // BUGBUG: change size //there is a bug the size of the bar doesn't change bm_fisho.render(context, 276, 342); context.setColor(Color.WHITE); context.setFont(fnt); context.drawString(scoreString(), 63, 354); context.drawString(String.valueOf(st_timer), 230, 354);//test //context.drawString(String.valueOf(first_bub.x), 160, 100);//test context.drawString(String.valueOf(fish_to_save_at_start), 160, 354);//test context.drawString((episode + 1) + " - " + sub_level, 190, 354); } void drawOutlined (Graphics2D context, int x, int y, String text) { //draw the text a bunch of different times offset a little bit to create outline // BUGBUG: center context.setColor(Color.BLACK); context.drawString(text, x - 2, y - 2); context.drawString(text, x - 2, y + 2); context.drawString(text, x + 2, y + 2); context.drawString(text, x + 2, y - 2); context.drawString(text, x - 2, y); context.drawString(text, x, y + 2); context.drawString(text, x + 2, y); context.drawString(text, x, y - 2); context.setColor(new Color(0xECD300)); //yellow context.drawString(text, x, y); } public void update (double elapsedTime) //called by game update { if (paused || game_state != GS_PLAY) { return; } if (!level_completed && !game_over && !existsInPath(next_bubble)) { next_bubble = getRandomBubble(false); } akey0 = (akey0 + elapsedTime) % 1.0; akey1 = (akey1 + 0.7 * elapsedTime) % 1.0; akey2 = (akey2 + 0.5 * elapsedTime) % 1.0; akey3 = (akey3 + 0.3 * elapsedTime) % 1.0; bob_akey = (bob_akey + 2 * elapsedTime) % NUM_BOB_STATES; time_paused = Math.max(0, time_paused - elapsedTime); time_rewind = Math.max(0, time_rewind - elapsedTime); shoot_time = Math.min(1, shoot_time + 3 * elapsedTime); name_show += 0.7 * elapsedTime; score_show += Math.min(4, (int)(5 * elapsedTime * (total_score - score_show))); score_show = Math.min(score_show, total_score); updateParts(elapsedTime); updateItems(elapsedTime); updateBubbles(elapsedTime); } void updateParts (double time) { Part dead = null; for (Part part = parts; part != null; part = part.next) { part.life -= part.speed * time; if (part.life <= 0.001) { if (dead == null) { parts = part.next; } else { dead.next = part.next; } } else if (part.life < 0.999) { part.x += time * part.vx; part.y += time * part.vy; dead = part; } } } void updateItems (double time) //time is elapsed time { Item dead = null; for (Item item = items; item != null; item = item.next) { item.y += time * item.vel_y; //items fall down if (item.y < -21 || item.y > 380 || item.type == ITEM_FREE) { if (dead == null) { items = items.next; } else { dead.next = item.next; } } else { item.time_existed += time; if (item.type == ITEM_TORPEDO || item.type == ITEM_SMROCKS) { if (item.type == ITEM_TORPEDO) { item.vel_y -= 400 * time; } for ( ; Math.abs(item.y - item.py) > 4; item.py -= 4)//create particle bubbles { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-5, 5); addPart(partbub); } for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next)//for all the bubbles { double dx = item.x - bubble.x; double dy = item.y - bubble.y; if (dx * dx + dy * dy < RAD_BUBBLE * RAD_BUBBLE)//if distance to item is less than radius of bubble { if (item.type == ITEM_TORPEDO) { for (Bubble bubble1 = first_bub; bubble1 != null; bubble1 = bubble1.next) { spawnBiggerBurst(item.x, item.y); double ddx = item.x - bubble1.x; double ddy = item.y - bubble1.y; if (ddx * ddx + ddy * ddy < 4096 && path_t0 + bubble1.t > 0)//only pop bubbles within a certain radius and on screen { spawnBurst(bubble1.x, bubble1.y); if (bubble1.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble1.next != null) { bubble1.next.shot = true; bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } else { first_bub = bubble1.next; } } } game.playSound(snd_explosion); shoot_time = 0.5; } else if (item.type == ITEM_SMROCKS) { spawnBurst(bubble.x, bubble.y); if (bubble.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble.x, bubble.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble.next != null) { bubble.next.shot = true; bubble.next.prev = bubble.prev; } if (bubble.prev != null) { bubble.prev.next = bubble.next; } else { first_bub = bubble.next; } game.playSound(snd_pop); } item.type = ITEM_FREE; if (first_bub == null) { if (fish_to_save <= 0) { level_completed = true; } else { first_bub = new Bubble(); first_bub.t = -path_t0 - 1; first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; } } } } } else // if not small rocks or torpedo { for ( ; Math.abs(item.y - item.py) > 4; item.py += 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-5, 5); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-7, 7); addPart(partbub); } if (item.bonus != null && Math.abs(item.x - bob_x) < 25 && Math.abs(item.y - (bob_y + 20)) < 38) { spawnBurst(item.x, item.y);//spawn burst of item game.playSound(snd_pick); PartString partstring = new PartString(this, item.x, item.y, item.bonus.name, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); shoot_time = 0.5; item.bonus.act(); if (dead == null) { items = items.next; } else { dead.next = item.next; } } } dead = item; } } } void updateBubbles (double elapsedTime) { double acc = path_speed * 1.5; // some sort of speed indicator? Bubble bubble = getLastBubble(); if (bubble != null) { if (game_starting) { double t = path_t0 + bubble.t; if (t < path_start_t - 8) //if it's before starting point, speed quickly ins { acc *= 25; } else if (t < path_start_t) //if the beginning bubbles are within distance 8 { acc *= 1 + (24 * (path_start_t - t)) / 8; } else //the game is starting { game_starting = false; } } double t = (path_t0 + bubble.t) / path_last_t;//starts low, approaches 1 if (time_paused <= 0) { if (t < 0.7) { if (t > 0.1) { handicap += 0.1 * (0.7 - t) * elapsedTime; //handicap is increased } else { handicap += 0.06 * elapsedTime;//handicap added } } else if (t > 0.7) { handicap -= 0.15 * (t - 0.7) * elapsedTime; //handicap is reduced } } handicap = Math.max(0.95, Math.min(handicap, 4));//0.9<handicap<4 acc *= handicap;//bigger handicap means faster , handicap is bad if (t < 0.4) { t = 1 + 15 * (0.4 - t); } else if (t > 0.8) { if (t > 0.95) { t = 0.95; } t = 2.5 * (1 - t); if (t < 0.15) { t = 0.15; } } else { t = 0.5 + 0.5 * (1 - (t - 0.4) / 0.4); } acc *= t; } acc = Math.max(0.2, acc);//acc is at least 0.2 if (time_paused > 0) //what to do if it is paused ... affects acc ... affects speed? //can happen concurrently { double factor = 1; if (time_paused > 5) { factor = 1 - (MAX_TIME_PAUSED - time_paused); //factor = (15 - (MAX_TIME_PAUSED - time_paused))/15;//test } else if (time_paused > 1) { factor = 0; } else if (time_paused > 0) { factor = 1 - time_paused; } acc *= factor; } if (time_rewind > 0)//rewind { double factor = 0; if (time_rewind > 3) { factor = 4 - time_rewind; } else if (time_rewind > 1) { factor = 1; } else if (time_rewind > 0) { factor = 1 * time_rewind; } acc = acc * (1 - factor) - 3 * factor; } if (game_over) { acc += go_speedup; go_speedup += 32 * elapsedTime; } else { acc = Math.max(-12, Math.min(acc, 12)); } acc *= elapsedTime; if (bubble != null && (path_t0 + bubble.t > 0 || acc > 0)) { path_t0 += acc; //so this move path_t0 up by acc, this moves the path forward //path_t0 += 20*acc;//test } if (game_over) { if (first_bub == null) { st_timer += elapsedTime; } if (st_timer > 1) { game_state = GS_GAME_OVER; } } if (level_completed) { st_timer += elapsedTime; if (st_timer > 1) { if (game_state != GS_LEVEL_COMPLETED) { game.playSound(snd_lev_comp); } game_state = GS_LEVEL_COMPLETED; } return; } double shot_y = shot_bubble.y;//shot bubble shot_bubble.y -= 620 * elapsedTime; //shot_bubble.y -= 6200 * elapsedTime;//test if (shot_bubble.bm != null) { for (double part_y = shot_bubble.y; part_y < shot_y; part_y += 5) //adds particle bubbles { PartBub partbub = new PartBub(this, shot_bubble.x, part_y, bm_part_bub[0], randDouble(3, 4.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-40, 0); partbub.x += randDouble(-7, 7); addPart(partbub); } } if (shot_bubble.y < -2 * RAD_BUBBLE) //out of screen { shot_bubble.bm = null; } Bubble bubble1 = first_bub; //System.out.println("first bub is: " + first_bub.x + ", " + first_bub.y); while (!game_over && fish_to_save > 0 && first_bub.x > -2 * RAD_BUBBLE) //while (!game_over && fish_to_save > 0 && first_bub.x > -2 * RAD_BUBBLE) //test //while first bub is still on screen, create it until first bub goes off screen by 1 bubble { fansbubblecount++;//test spawnBiggerBurst(228.233145293306, -14.08079092769546); System.out.println("creating a new bubble " + fansbubblecount + " first bub is: " + first_bub.x + ", " + first_bub.y); bubble1 = new Bubble(); bubble1.phase = first_bub.phase - 0.1; bubble1.fish_inside = true; bubble1.shot = false; first_bub.prev = bubble1; bubble1.next = first_bub; bubble1.t = first_bub.t - 1; bubble1.bm = getRandomBubble(true); first_bub = bubble1; //System.out.println("before updatebubble first bub is: " + first_bub.x + ", " + first_bub.y); updateBubble(first_bub); //System.out.println("after updatebubble first bub is: " + first_bub.x + ", " + first_bub.y); //System.out.println(-2*RAD_BUBBLE); } for ( ; bubble1 != null; bubble1 = bubble1.next) //for each bubble { if (path_t0 + bubble1.t >= path_last_t)//lose condition? { if (!game_over)//if not game over, then make game over { game.playSound(snd_bob_loses); } game_over = true; if (bubble1.prev != null) { bubble1.prev.next = null; } if (bubble1 == first_bub) { first_bub = null; return; } } bubble1.phase += (elapsedTime % 1.0); bubble1.trans = Math.max(0, bubble1.trans - 4 * elapsedTime); updateBubble(bubble1); if (shot_bubble.bm != null && shot_bubble.y - 2 * RAD_BUBBLE <= bubble1.y + 8 && shot_y + 2 * RAD_BUBBLE + 10 > bubble1.y + 8 && Math.abs(shot_bubble.x - bubble1.x) < 15)//if shot bubble connects with path bubble { Bubble bubble2 = new Bubble(); bubble2.bm = shot_bubble.bm; bubble2.shot = true; bubble2.trans = 1; bubble2.attach_x = shot_bubble.x; bubble2.attach_y = shot_bubble.y; double f10 = (bubble1.prev != null) ? Math.min(bubble1.prev.x, bubble1.x) : bubble1.x - RAD_BUBBLE; double f11 = (bubble1.prev != null) ? Math.max(bubble1.prev.x, bubble1.x) : bubble1.x; double f12 = (bubble1.prev != null) ? bubble1.prev.x - bubble1.x : (bubble1.next != null) ? bubble1.x - bubble1.next.x : 1; double f15 = (bubble1.prev != null) ? bubble1.prev.y - bubble1.y : (bubble1.next != null) ? bubble1.y - bubble1.next.y : 0; double f16 = Math.sqrt(f12 * f12 + f15 * f15); f15 /= f16; boolean flag2 = true; if (Math.abs(f15) > 0.4) { flag2 = (f15 < 0); } else { flag2 = ! ((bubble1.prev != null && shot_bubble.x > f10 || bubble1.prev == null) && shot_bubble.x < f11); } if (!flag2) { bubble2.next = bubble1; bubble2.prev = bubble1.prev; bubble2.t = bubble1.t - 0.5; if (bubble1.prev != null) { bubble1.prev.next = bubble2; } else { first_bub = bubble2; } bubble1.prev = bubble2; } else { bubble2.prev = bubble1; bubble2.next = bubble1.next; bubble2.t = bubble1.t + 0.5; if (bubble1.next != null) { bubble1.next.prev = bubble2; } bubble1.next = bubble2; } shot_bubble.bm = null; } if (bubble1.next != null) { int i = 1; boolean flag = bubble1.shot; if (bubble1.prev == null || bubble1.prev.bm != bubble1.bm) { for (Bubble bubble3 = bubble1.next; bubble3 != null && bubble3.bm == bubble1.bm; bubble3 = bubble3.next) { if (bubble3.t - (i + bubble1.t) > 0.01) { i = 0; break; } if (bubble3.shot) { flag = true; } i++;//increment number of consecutive bubbles same color } } if (flag && i >= 3) //popping? { game.playSound(snd_plip_plop); level_score += i * 50; total_score += i * 50; //if (!isSomeBonusActing() && (randInt(16) == 4 || i >= 4 && randInt(10) <= i)) //will some bonus be added? if (true)//test { double f13 = (path_t0 + bubble.t) / path_last_t; if(f13 > 0.4) { Item item = new Item(); item.type = 3; item.x = bubble1.x; item.y = item.py = bubble1.y; item.vel_y = 70; item.bonus = getRandomBonus(); item.bm = item.bonus.icon; if(items == null)//? if don't have an item, add it to the item queue { items = item; } else { item.next = items.next; items.next = item; } } } boolean flag1 = false; int j = 1; double curr_x = 0; double curr_y = 0; for (int k = i; k > 0; k--) { curr_x += bubble1.x; curr_y += bubble1.y; j += bubble1.combo; if (bubble1.fish_inside) { total_fish_saved++; fish_to_save--; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } spawnBurst(bubble1.x, bubble1.y); if (bubble1.next != null) { bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } if (bubble1 == first_bub) { first_bub = bubble1.next; } if (bubble1.next != null) { bubble1 = bubble1.next; } else { flag1 = true; bubble1 = bubble1.prev; } } curr_x /= i; curr_y /= i; if (bubble1 != null && adjIsGoingToBurst(bubble1)) { bubble1.combo = j; } if (j > 1) { PartString partstring = new PartString(this, curr_x, curr_y, "Combo " + j + "x", 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } if (longest_combo < j) { longest_combo = j; } if (j > 0) { j--; } if (j > 7) { j = 7; } game.playSound(snd_combo[j]); Bubble bubble6 = bubble1; if (bubble6 != null && bubble6.prev != null && bubble6.bm == bubble6.prev.bm && !flag1) { bubble6.shot = true; } } if (bubble1 == null) { if (fish_to_save <= 0) { level_completed = true; System.out.println("fish to save < 0 level completed"); } if (level_completed) { first_bub = null; return; } else { first_bub = bubble1 = new Bubble(); bubble1.bm = getRandomBubble(false); bubble1.t = -path_t0; updateBubble(bubble1); return; } } if (bubble1.next == null) { return; } double f14 = Math.abs(bubble1.next.t - bubble1.t); if (f14 < 0.99) { for (Bubble bubble4 = bubble1.next; bubble4 != null; bubble4 = bubble4.next) { double f18 = 6 * (1 - f14) * elapsedTime; if (f18 > f14) f18 = f14; bubble4.t += f18; } } if (f14 > 1.01) { for(Bubble bubble5 = bubble1.next; bubble5 != null; bubble5 = bubble5.next) { double f19 = 2 * f14 * elapsedTime; if (f19 > 0.15) { f19 = 0.15; } if (f19 > f14) { f19 = f14; } bubble5.t -= f19; } } } if (bubble1.combo > 0 && !adjIsGoingToBurst(bubble1))//reset combo { bubble1.combo = 0; } } } void updateBubble (Bubble bubble) //updates bubble position { Point2D.Double tp = getPathPoint(path_t0 + bubble.t); bubble.x = tp.x; bubble.y = tp.y; } public void handleInput () // handles the user inputs { if (game.keyPressed(KeyEvent.VK_SPACE)) { if (game_state == GS_PLAY) { game.playSound(snd_pick); paused = !paused; } else { paused = false; } } if (game.click()) { if (game_state == GS_LEVEL_COMPLETED) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; if (level / 5 + 1 >= 4) { completed_the_game = true; game_state = GS_GAME_OVER; } initLevel(level + 1); } else if (game_state == GS_GAME_OVER) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_MAINMENU) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_PLAY && !paused) { if (smrocks > 0) { game.playSound(snd_shoot_bubble); smrocks--; Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -360; item.type = ITEM_SMROCKS; item.bonus = null; item.bm = bm_smrock; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; PartString partstring = new PartString(this, item.x, item.y, "" + smrocks, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } else if (torpedo) { torpedo = false; game.playSound(snd_shoot_bubble); Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -120; item.type = ITEM_TORPEDO; item.bonus = null; item.bm = bm_torpedo; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; } else if (shot_bubble.bm != null) { return; } else if (shoot_time < 0.8) { return; } else { game.playSound(snd_shoot_bubble); shot_bubble.bm = next_bubble; next_bubble = next_bubble2; next_bubble2 = getRandomBubble(false); shot_bubble.x = game.getMouseX(); shot_bubble.y = bob_y - 10; shoot_time = 0; } } } if (game.rightClick()) { game.playSound(snd_swap); Sprite next = next_bubble; next_bubble = next_bubble2; next_bubble2 = next; shoot_time = 0.5; } } void addPart (Part part) { if (parts == null) { parts = part; } else { part.next = parts; parts = part; } } Point2D.Double getPathPoint (double idx) { if (idx < 0) { return new Point2D.Double(-30, -400); } double idx_dist = idx * 2 * RAD_BUBBLE; double curr_dist = 0; for (int i = 0; i < num_path_points; i++) { double next_dist = curr_dist + path[i].dist_to_next; if (idx_dist < next_dist) { double curr_idx = (idx_dist - curr_dist) / path[i].dist_to_next; return new Point2D.Double(path[i].x + (path[i + 1].x - path[i].x) * curr_idx, path[i].y + (path[i + 1].y - path[i].y) * curr_idx); } curr_dist = next_dist; } // return new Point2D.Double(path[num_path_points - 1].x, path[num_path_points - 1].y); } void setPathPoint (int idx, double x, double y) { path[idx] = new PathPoint(); path[idx].x = (x + path_inc_x) * 0.71; path[idx].y = (y + path_inc_y - 10) * 0.71; if (idx > 0) { double dx = path[idx - 1].x - path[idx].x; double dy = path[idx - 1].y - path[idx].y; path[idx - 1].dist_to_next = Math.sqrt(dx * dx + dy * dy); } num_path_points = idx + 1; } boolean existsInPath (Sprite bub) { for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (bubble.bm == bub) { return true; } } return false; } Bubble getLastBubble () { if (first_bub == null) return null; Bubble bubble; for (bubble = first_bub; bubble.next != null; bubble = bubble.next) ; return bubble; } boolean adjIsGoingToBurst (Bubble bubble) { Sprite s = bubble.bm; int i = 1; for (Bubble b = bubble.prev; b != null && b.bm == s; b = b.prev) i++; for (Bubble b = bubble.next; b != null && b.bm == s; b = b.next) i++; return i >= 3; } void spawnBiggerBurst (double x, double y) { for (int i = 0; i < 30; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(140, 310); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 3.8)); partbub.life += randDouble(0, 0.4); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle); partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } void spawnBurst (double x, double y) { y += 5; for (int i = 0; i < 26; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(50, 100); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 4.2)); partbub.life += randDouble(0, 0.2); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle) - magnitude; partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } Sprite getRandomBubble (boolean totally_random) { int max = 3 + (episode + 1) / 2; if (totally_random) { return bm_bubbles[randInt(max)]; } for (int j = 0; j < 300; j++) { //get a random bubble that exists in path Sprite bub = bm_bubbles[randInt(max)]; if (existsInPath(bub)) { return bub; } } System.out.println("stalled."); return bm_bubbles[randInt(max)]; } Bonus getRandomBonus () { int i = randInt(num_bonuses); Bonus bonus = bonuses; for (bonus = bonuses; i != 0; bonus = bonus.next, i--) ; return bonus; } int randInt (int max) { return (int)(Math.random() * max); } double randDouble (double min, double max) { return min + Math.random() * (max - min); } String scoreString () { StringBuffer stringbuffer = new StringBuffer(score_show); for (int i = stringbuffer.length() - 1 - 2; i > 0; i -= 3) { stringbuffer.insert(i, "0"); } return stringbuffer.toString(); } }
Java
package game; import java.awt.*; import com.golden.gamedev.Game; import com.golden.gamedev.GameLoader; public class BubblefishBob extends Game { private static final long serialVersionUID = 1L; private ProgBob progbob = new ProgBob(); public BubblefishBob () { distribute = true; } @Override public void initResources () { progbob.init(this); } @Override public void render (Graphics2D context) { progbob.draw(context); } @Override public void update (long elapsedTime) { progbob.handleInput(); progbob.update(elapsedTime / 1000.0); } public static void main (String[] args) { GameLoader loader = new GameLoader(); loader.setup(new BubblefishBob(), new Dimension(480, 360), false); loader.start(); } }
Java
package game; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import java.io.File; import java.util.ArrayList; import com.golden.gamedev.Game; import com.golden.gamedev.object.Sprite; /** * this progbob is a backup from before i started messing with level creation * @author Shun * */ public class ProgBob1 { final static int RAD_BUBBLE = 13; final static int W_SMFISH = 8; final static int H_SMFISH = 6; final static int GS_MAINMENU = 0; final static int GS_PLAY = 1; final static int GS_LEVEL_COMPLETED = 2; final static int GS_GAME_OVER = 3; final static int ITEM_FREE = 0; final static int ITEM_BUBBLE = 1; final static int ITEM_TORPEDO = 2; final static int ITEM_BONUS = 3; final static int ITEM_SMROCKS = 4; final static int NUM_BOB_STATES = 11; final static int MAX_BUBBLES = 128; final static double MAX_TIME_PAUSED = 6; final static double MAX_TIME_REWIND = 4; final static double PI_2 = 2 * Math.PI; Font fnt; Font fnt2; Font fnt3; Font fnts[]; Sprite bm_bob[]; Sprite bm_bubbles[]; Sprite bm_evil_fish; Sprite bm_smfish; Sprite bm_torpedo; Sprite bm_smrock; Sprite bm_fisho; Sprite bm_click_to_continue; Sprite bm_congrats; Sprite bm_bg_menu; Sprite bm_bg_game; Sprite bm_lev_comp; Sprite bm_loading; Sprite bm_game_over; Sprite bm_part_bub[]; String snd_level_start; String snd_explosion; String snd_shoot_bubble; String snd_plip_plop; String snd_pop; String snd_bob_loses; String snd_pick; String snd_swap; String snd_lev_comp; String snd_combo[]; boolean torpedo; int smrocks; double name_show; int episode; int sub_level; int total_fish_saved; int longest_combo; double handicap; int game_state; boolean game_starting; boolean completed_the_game; double time_rewind; double time_paused; int num_bonuses; AbstractBonus bonuses; Part parts; Item items; int num_path_points; PathPoint path[]; double path_t0; double path_speed; int fish_to_save; int fish_to_save_at_start; double path_last_t; double path_start_t; Bubble bubbles[]; Bubble first_bub; Bubble shot_bubble; Sprite next_bubble; Sprite next_bubble2; int bob_y; int bob_x; double bob_akey; double akey0; double akey1; double akey2; double akey3; double shoot_time; boolean game_over; double go_speedup; int level; boolean level_completed; double st_timer; int level_score; int total_score; int score_show; boolean paused; int path_inc_x; int path_inc_y; Game game; TxtParser txtParser = new TxtParser(); boolean isSomeBonusActing () { return time_rewind > 0 || time_paused > 0 || items != null || smrocks > 0 || torpedo; } public void init (Game game) { this.game = game; fnt = Font.decode("Arial-BOLD-16"); fnt2 = Font.decode("Arial-BOLD-20"); fnt3 = Font.decode("Arial-PLAIN-14"); fnts = new Font[11]; for (int k = 0; k < 11; k++) { fnts[k] = Font.decode("Arial-PLAIN-" + (k + 2)); } Part part = new Part(this, 10, 10, null, 0); for (int k = 0; k < 100; k++) { part.next = new Part(this, 10, 10, null, 0); part = part.next; } for (int k = 0; k < 100; k++) { part.next = new PartBub(this, 10, 10, null, 0); part = part.next; } bm_loading = new Sprite(game.getImage("resources/loading.jpg")); bm_click_to_continue = new Sprite(game.getImage("resources/click_to_continue.png")); bm_congrats = new Sprite(game.getImage("resources/congrats.png")); bm_bob = new Sprite[NUM_BOB_STATES]; bm_bob[0] = new Sprite(game.getImage("resources/bob_0000.png")); bm_bob[1] = new Sprite(game.getImage("resources/bob_0002.png")); bm_bob[2] = new Sprite(game.getImage("resources/bob_0004.png")); bm_bob[3] = new Sprite(game.getImage("resources/bob_0006.png")); bm_bob[4] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[5] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[6] = new Sprite(game.getImage("resources/bob_0010.png")); bm_bob[7] = new Sprite(game.getImage("resources/bob_0012.png")); bm_bob[8] = new Sprite(game.getImage("resources/bob_0014.png")); bm_bob[9] = new Sprite(game.getImage("resources/bob_0016.png")); bm_bob[10] = new Sprite(game.getImage("resources/bob_0018.png")); bm_evil_fish = new Sprite(game.getImage("resources/evil_fish.png")); bm_smfish = new Sprite(game.getImage("resources/smfish.png")); snd_shoot_bubble = "resources/release_bubble.au"; snd_combo = new String[8]; snd_combo[0] = "resources/combo_01.au"; snd_combo[1] = "resources/combo_02.au"; snd_combo[2] = "resources/combo_03.au"; snd_combo[3] = "resources/combo_04.au"; snd_combo[4] = "resources/combo_05.au"; snd_combo[5] = "resources/combo_06.au"; snd_combo[6] = "resources/combo_07.au"; snd_combo[7] = "resources/combo_08.au"; snd_plip_plop ="resources/pop_01.au"; snd_pop = "resources/pop_01.au"; snd_bob_loses = "resources/bob_loses.au"; snd_pick = "resources/pickup.au"; snd_swap = "resources/gulp.au"; snd_lev_comp = "resources/lev_comp_song.au"; snd_level_start = "resources/level_start.au"; snd_explosion = "resources/explosion.au"; bm_bubbles = new Sprite[7]; bm_bubbles[0] = new Sprite(game.getImage("resources/blue.png")); bm_bubbles[1] = new Sprite(game.getImage("resources/red.png")); bm_bubbles[2] = new Sprite(game.getImage("resources/green.png")); bm_bubbles[3] = new Sprite(game.getImage("resources/orange.png")); bm_bubbles[4] = new Sprite(game.getImage("resources/purple.png")); bm_bubbles[5] = new Sprite(game.getImage("resources/cyan.png")); bm_bubbles[6] = new Sprite(game.getImage("resources/white.png")); bm_bg_game = new Sprite(game.getImage("resources/seagrass.jpg")); bm_bg_menu = new Sprite(game.getImage("resources/bg_menu.jpg")); bm_lev_comp = new Sprite(game.getImage("resources/lev_comp.png")); bm_game_over = new Sprite(game.getImage("resources/game_over.png")); bm_part_bub = new Sprite[4]; bm_part_bub[0] = new Sprite(game.getImage("resources/part_bub_01.png")); bm_part_bub[1] = new Sprite(game.getImage("resources/part_bub_02.png")); bm_part_bub[2] = new Sprite(game.getImage("resources/part_bub_03.png")); bm_part_bub[3] = new Sprite(game.getImage("resources/part_bub_04.png")); bm_torpedo = new Sprite(game.getImage("resources/torpedo.png")); bm_smrock = new Sprite(game.getImage("resources/smrock.png")); bm_fisho = new Sprite(game.getImage("resources/fisho_full.png")); bonuses = new BonusPause(this, "Pause", new Sprite(game.getImage("resources/bonus_pause.png"))); bonuses.next = new BonusRewind(this, "Rewind", new Sprite(game.getImage("resources/bonus_rewind.png"))); bonuses.next.next = new BonusTorpedo(this, "Torpedo", new Sprite(game.getImage("resources/bon_torpedo.png"))); bonuses.next.next.next = new BonusSmRocks(this, "Small Rocks", new Sprite(game.getImage("resources/bon_smrocks.png"))); num_bonuses = 4; game_state = GS_MAINMENU; initLevel(1); } void initGame () { total_fish_saved = 0; total_score = 0; level_score = 0; shoot_time = 0; completed_the_game = false; game_over = false; paused = false; } void initLevel (int level_num) { paused = false; level_completed = false; handicap = 1; longest_combo = 0; torpedo = false; smrocks = 0; name_show = 0; time_rewind = 0; time_paused = 0; items = null; game_starting = true; level_score = 0; go_speedup = 0; st_timer = 0; shot_bubble = new Bubble(); shot_bubble.bm = null; path_speed = 0.5; bob_y = 290; bob_akey = 0; level = level_num; episode = (level - 1) / 5; sub_level = (level - 1) % 5 + 1; if (sub_level == 1) { fish_to_save_at_start = fish_to_save = -1; //fish_to_save_at_start = fish_to_save = 80; path_speed = 0.4; path_inc_x = 320; path_inc_y = -10; path_start_t = 32; num_path_points = 53; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level1.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } else if (sub_level == 2) { fish_to_save_at_start = fish_to_save = -1; //fish_to_save_at_start = fish_to_save = 180; path_speed = 0.5; path_inc_x = 0; path_inc_y = 59; path_start_t = 14; num_path_points = 78; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level2.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } else if (sub_level == 3) { fish_to_save_at_start = fish_to_save = -1; //fish_to_save_at_start = fish_to_save = 128; path_speed = 0.65; path_inc_x = 10; path_inc_y = 323; path_start_t = 15; num_path_points = 21; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level3.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } else if (sub_level == 4) { fish_to_save_at_start = fish_to_save = -1; //fish_to_save_at_start = fish_to_save = 150; path_speed = 0.8; path_inc_x = 67; path_inc_y = 0; path_start_t = 6; num_path_points = 58; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level4.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } else if (sub_level == 5) { fish_to_save_at_start = fish_to_save = 150; path_speed = 0.4; path_inc_x = 0; path_inc_y = 60; path_start_t = 24; num_path_points = 48; path = new PathPoint[num_path_points]; int j = 0; File pointsFile = new File("resources/level5.txt"); ArrayList<Point2D.Double> levelPathPoints = txtParser.parseInput(pointsFile); for (int ii = 0; ii < levelPathPoints.size(); ii++) { setPathPoint(j++,(int) levelPathPoints.get(ii).x,(int) levelPathPoints.get(ii).y); //System.out.println("j: "+j+", x: "+levelPathPoints.get(ii).x+", y: "+levelPathPoints.get(ii).y+", n: "+num_path_points); } } path_speed += episode * 0.08; path_t0 = 0; path_last_t = 0; for (int k = 0; k < num_path_points; k++) { path_last_t += path[k].dist_to_next; } path_last_t /= 2 * RAD_BUBBLE; bubbles = new Bubble[MAX_BUBBLES]; for (int k = 0; k < bubbles.length; k++) { bubbles[k] = new Bubble(); } first_bub = new Bubble(); first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; Point2D.Double pnt = getPathPoint(0); first_bub.x = pnt.x; first_bub.y = pnt.y; next_bubble = getRandomBubble(true); next_bubble2 = getRandomBubble(true); } public void draw (Graphics2D context) { if (game_state == GS_MAINMENU) { bm_bg_menu.render(context); } else if (game_state == GS_LEVEL_COMPLETED) { bm_bg_game.render(context, 0, 0); bm_lev_comp.render(context, 90, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 151, "Fish Saved:"); drawOutlined(context, 340, 168, "" + total_fish_saved); drawOutlined(context, 140, 151, "Max Combo:"); drawOutlined(context, 140, 168, "" + longest_combo); drawOutlined(context, 240, 205, "Level Score:"); drawOutlined(context, 240, 222, "" + level_score); context.setFont(fnt); context.setColor(Color.WHITE); bm_click_to_continue.render(context, 156, 290); drawParts(context); drawBar(context); } else if (game_state == GS_GAME_OVER) { bm_bg_game.render(context, 0, 0); if (completed_the_game) { context.setColor(Color.WHITE); context.setFont(fnt2); bm_congrats.render(context, 50, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 175, "Fish Saved:"); drawOutlined(context, 340, 192, "" + total_fish_saved); drawOutlined(context, 140, 175, "Final Score:"); drawOutlined(context, 140, 192, "" + total_score); } else { bm_game_over.render(context, 132, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 240, 111, "Fish Saved:"); drawOutlined(context, 240, 128, "" + total_fish_saved); drawOutlined(context, 240, 155, "Final Score:"); drawOutlined(context, 240, 172, "" + total_score); } drawParts(context); drawBar(context); bm_click_to_continue.render(context, 156, 290); } else if (game_state == GS_PLAY) { bm_bg_game.render(context, 0, 0); drawPath(context); drawParts(context); drawItems(context); bob_x = game.getMouseX(); int y_offset = (int)(5 * Math.sin(shoot_time * Math.PI)); if (torpedo) { bm_torpedo.setX(bob_x - bm_torpedo.getWidth() / 2); bm_torpedo.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_torpedo.render(context); } else if (smrocks > 0) { bm_smrock.setX(bob_x - bm_torpedo.getWidth() / 2); bm_smrock.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); bm_smrock.render(context); } else { if (shoot_time >= 1) { next_bubble.setX(bob_x - next_bubble.getWidth() / 2); next_bubble.setY(bob_y - next_bubble.getHeight() + y_offset); next_bubble.render(context); } else { int x_offset = (int)(shoot_time * 2 * RAD_BUBBLE); next_bubble.setX(bob_x - x_offset / 2); next_bubble.setY((bob_y + (1 - shoot_time) * 4 * RAD_BUBBLE) - next_bubble.getHeight() + y_offset); next_bubble.render(context); } // BUGBUG: change size to 16x16 next_bubble2.render(context, (int)((bob_x - 16 / 2) + 1), (int)(((bob_y - 4) + y_offset) + (1 - shoot_time) * 16)); } bm_bob[(int)bob_akey].render(context, bob_x - 22, bob_y + y_offset); drawBar(context); if (name_show < 1 && !paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Level " + (episode + 1) + "-" + sub_level); } } if (paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Paused"); context.setFont(fnt); context.setColor(Color.BLACK); context.drawString("Press space to continue", 240, 190); } } void drawParts (Graphics2D context) { for (Part part = parts; part != null; part = part.next) { if (part.life < 0.999) { part.draw(context); } } } void drawPath (Graphics2D context) { int x = 0; int y = 0; double t = 0; for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (path_t0 + bubble.t < path_last_t - 1) { if (bubble.fish_inside) { bm_smfish.setX(bubble.x - 8); bm_smfish.setY(bubble.y - 6 + 2 * Math.sin(bubble.phase * PI_2)); bm_smfish.render(context); } double x_scale = 1 - bubble.trans; x = (int)(bubble.trans * bubble.attach_x + x_scale * bubble.x); if (path_t0 + bubble.t >= path_last_t - 4) { double y_scale = ((path_t0 + bubble.t) - (path_last_t - 4)) / 4; y = (int)((bubble.trans * bubble.attach_y + x_scale * bubble.y) + 3 * Math.sin(bubble.phase * PI_2) * (1 - y_scale) + 4 * Math.sin(PI_2 * akey2) * y_scale); } else { y = (int)(bubble.trans * bubble.attach_y + x_scale * bubble.y + 3 * Math.sin(bubble.phase * PI_2)); } bubble.bm.render(context, x - RAD_BUBBLE, y - RAD_BUBBLE); } t = bubble.t; } t += path_t0 + 1 + st_timer * (path_t0 + path_last_t - t); for (double t1 = Math.floor(t); t1 < path_last_t; t1 += 0.5) { Point2D.Double pnt = getPathPoint(t1); y = (int)(pnt.y + 3 * Math.sin(PI_2 * akey1 + t1)); bm_part_bub[3].render(context, (int)pnt.x - 2, y - 2); } x = (int)(path[num_path_points - 1].x - 55 + (1 - Math.sin(0.5 * Math.PI + 0.5 * Math.PI * st_timer)) * (480 - x)); y = (int)path[num_path_points - 1].y; bm_evil_fish.render(context, x, (y + (int)(4 * Math.sin(PI_2 * akey2))) - 40); } void drawItems (Graphics2D context) { for (Item item = items; item != null; item = item.next) { int x = (int)(item.x + 3 * Math.sin(PI_2 * akey1)); int y = (int)item.y; if (4 * item.time_existed < 1 && item.vel_y > 0) { double t = 4 * item.time_existed; int w = (int)(item.bm.getWidth() * t); int h = (int)(item.bm.getHeight() * t); // BUGBUG: change size item.bm.render(context, x - w / 2, y - h / 2); } else { item.bm.render(context, x, y); } } if (shot_bubble.bm != null) { shot_bubble.bm.render(context, (int)shot_bubble.x, (int)shot_bubble.y); } } void drawBar (Graphics2D context) { int w = bm_fisho.getWidth(); int h = (int)(w * ((fish_to_save_at_start - fish_to_save) / fish_to_save_at_start)); // BUGBUG: change size bm_fisho.render(context, 276, 342); context.setColor(Color.WHITE); context.setFont(fnt); context.drawString(scoreString(), 63, 354); context.drawString((episode + 1) + " - " + sub_level, 190, 354); } void drawOutlined (Graphics2D context, int x, int y, String text) { // BUGBUG: center context.setColor(Color.BLACK); context.drawString(text, x - 2, y - 2); context.drawString(text, x - 2, y + 2); context.drawString(text, x + 2, y + 2); context.drawString(text, x + 2, y - 2); context.drawString(text, x - 2, y); context.drawString(text, x, y + 2); context.drawString(text, x + 2, y); context.drawString(text, x, y - 2); context.setColor(new Color(0xECD300)); context.drawString(text, x, y); } public void update (double elapsedTime) { if (paused || game_state != GS_PLAY) { return; } if (!level_completed && !game_over && !existsInPath(next_bubble)) { next_bubble = getRandomBubble(false); } akey0 = (akey0 + elapsedTime) % 1.0; akey1 = (akey1 + 0.7 * elapsedTime) % 1.0; akey2 = (akey2 + 0.5 * elapsedTime) % 1.0; akey3 = (akey3 + 0.3 * elapsedTime) % 1.0; bob_akey = (bob_akey + 2 * elapsedTime) % NUM_BOB_STATES; time_paused = Math.max(0, time_paused - elapsedTime); time_rewind = Math.max(0, time_rewind - elapsedTime); shoot_time = Math.min(1, shoot_time + 3 * elapsedTime); name_show += 0.7 * elapsedTime; score_show += Math.min(4, (int)(5 * elapsedTime * (total_score - score_show))); score_show = Math.min(score_show, total_score); updateParts(elapsedTime); updateItems(elapsedTime); updateBubbles(elapsedTime); } void updateParts (double time) { Part dead = null; for (Part part = parts; part != null; part = part.next) { part.life -= part.speed * time; if (part.life <= 0.001) { if (dead == null) { parts = part.next; } else { dead.next = part.next; } } else if (part.life < 0.999) { part.x += time * part.vx; part.y += time * part.vy; dead = part; } } } void updateItems (double time) { Item dead = null; for (Item item = items; item != null; item = item.next) { item.y += time * item.vel_y; if (item.y < -21 || item.y > 380 || item.type == ITEM_FREE) { if (dead == null) { items = items.next; } else { dead.next = item.next; } } else { item.time_existed += time; if (item.type == ITEM_TORPEDO || item.type == ITEM_SMROCKS) { if (item.type == ITEM_TORPEDO) { item.vel_y -= 400 * time; } for ( ; Math.abs(item.y - item.py) > 4; item.py -= 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-5, 5); addPart(partbub); } for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { double dx = item.x - bubble.x; double dy = item.y - bubble.y; if (dx * dx + dy * dy < RAD_BUBBLE * RAD_BUBBLE) { if (item.type == ITEM_TORPEDO) { for (Bubble bubble1 = first_bub; bubble1 != null; bubble1 = bubble1.next) { spawnBiggerBurst(item.x, item.y); double ddx = item.x - bubble1.x; double ddy = item.y - bubble1.y; if (ddx * ddx + ddy * ddy < 4096 && path_t0 + bubble1.t > 0) { spawnBurst(bubble1.x, bubble1.y); if (bubble1.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble1.next != null) { bubble1.next.shot = true; bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } else { first_bub = bubble1.next; } } } game.playSound(snd_explosion); shoot_time = 0.5; } else if (item.type == ITEM_SMROCKS) { spawnBurst(bubble.x, bubble.y); if (bubble.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble.x, bubble.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble.next != null) { bubble.next.shot = true; bubble.next.prev = bubble.prev; } if (bubble.prev != null) { bubble.prev.next = bubble.next; } else { first_bub = bubble.next; } game.playSound(snd_pop); } item.type = ITEM_FREE; if (first_bub == null) { if (fish_to_save <= 0) { level_completed = true; } else { first_bub = new Bubble(); first_bub.t = -path_t0 - 1; first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; } } } } } else { for ( ; Math.abs(item.y - item.py) > 4; item.py += 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-5, 5); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-7, 7); addPart(partbub); } if (item.bonus != null && Math.abs(item.x - bob_x) < 25 && Math.abs(item.y - (bob_y + 20)) < 38) { spawnBurst(item.x, item.y); game.playSound(snd_pick); PartString partstring = new PartString(this, item.x, item.y, item.bonus.name, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); shoot_time = 0.5; item.bonus.act(); if (dead == null) { items = items.next; } else { dead.next = item.next; } } } dead = item; } } } void updateBubbles (double elapsedTime) { double acc = path_speed * 1.5; Bubble bubble = getLastBubble(); if (bubble != null) { if (game_starting) { double t = path_t0 + bubble.t; if (t < path_start_t - 8) { acc *= 25; } else if (t < path_start_t) { acc *= 1 + (24 * (path_start_t - t)) / 8; } else { game_starting = false; } } double t = (path_t0 + bubble.t) / path_last_t; if (time_paused <= 0) { if (t < 0.7) { if (t > 0.1) { handicap += 0.1 * (0.7 - t) * elapsedTime; } else { handicap += 0.06 * elapsedTime; } } else if (t > 0.7) { handicap -= 0.15 * (t - 0.7) * elapsedTime; } } handicap = Math.max(0.95, Math.min(handicap, 4)); acc *= handicap; if (t < 0.4) { t = 1 + 15 * (0.4 - t); } else if (t > 0.8) { if (t > 0.95) { t = 0.95; } t = 2.5 * (1 - t); if (t < 0.15) { t = 0.15; } } else { t = 0.5 + 0.5 * (1 - (t - 0.4) / 0.4); } acc *= t; } acc = Math.max(0.2, acc); if (time_paused > 0) { double factor = 1; if (time_paused > 5) { factor = 1 - (MAX_TIME_PAUSED - time_paused); } else if (time_paused > 1) { factor = 0; } else if (time_paused > 0) { factor = 1 - time_paused; } acc *= factor; } if (time_rewind > 0) { double factor = 0; if (time_rewind > 3) { factor = 4 - time_rewind; } else if (time_rewind > 1) { factor = 1; } else if (time_rewind > 0) { factor = 1 * time_rewind; } acc = acc * (1 - factor) - 3 * factor; } if (game_over) { acc += go_speedup; go_speedup += 32 * elapsedTime; } else { acc = Math.max(-12, Math.min(acc, 12)); } acc *= elapsedTime; if (bubble != null && (path_t0 + bubble.t > 0 || acc > 0)) { path_t0 += acc; } if (game_over) { if (first_bub == null) { st_timer += elapsedTime; } if (st_timer > 1) { game_state = GS_GAME_OVER; } } if (level_completed) { st_timer += elapsedTime; if (st_timer > 1) { if (game_state != GS_LEVEL_COMPLETED) { game.playSound(snd_lev_comp); } game_state = GS_LEVEL_COMPLETED; } return; } double shot_y = shot_bubble.y; shot_bubble.y -= 620 * elapsedTime; if (shot_bubble.bm != null) { for (double part_y = shot_bubble.y; part_y < shot_y; part_y += 5) { PartBub partbub = new PartBub(this, shot_bubble.x, part_y, bm_part_bub[0], randDouble(3, 4.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-40, 0); partbub.x += randDouble(-7, 7); addPart(partbub); } } if (shot_bubble.y < -2 * RAD_BUBBLE) { shot_bubble.bm = null; } Bubble bubble1 = first_bub; while (!game_over && fish_to_save > 0 && first_bub.x > -2 * RAD_BUBBLE) { bubble1 = new Bubble(); bubble1.phase = first_bub.phase - 0.1; bubble1.fish_inside = true; bubble1.shot = false; first_bub.prev = bubble1; bubble1.next = first_bub; bubble1.t = first_bub.t - 1; bubble1.bm = getRandomBubble(true); first_bub = bubble1; updateBubble(first_bub); } for ( ; bubble1 != null; bubble1 = bubble1.next) { if (path_t0 + bubble1.t >= path_last_t) { if (!game_over) { game.playSound(snd_bob_loses); } game_over = true; if (bubble1.prev != null) { bubble1.prev.next = null; } if (bubble1 == first_bub) { first_bub = null; return; } } bubble1.phase += (elapsedTime % 1.0); bubble1.trans = Math.max(0, bubble1.trans - 4 * elapsedTime); updateBubble(bubble1); if (shot_bubble.bm != null && shot_bubble.y - 2 * RAD_BUBBLE <= bubble1.y + 8 && shot_y + 2 * RAD_BUBBLE + 10 > bubble1.y + 8 && Math.abs(shot_bubble.x - bubble1.x) < 15) { Bubble bubble2 = new Bubble(); bubble2.bm = shot_bubble.bm; bubble2.shot = true; bubble2.trans = 1; bubble2.attach_x = shot_bubble.x; bubble2.attach_y = shot_bubble.y; double f10 = (bubble1.prev != null) ? Math.min(bubble1.prev.x, bubble1.x) : bubble1.x - RAD_BUBBLE; double f11 = (bubble1.prev != null) ? Math.max(bubble1.prev.x, bubble1.x) : bubble1.x; double f12 = (bubble1.prev != null) ? bubble1.prev.x - bubble1.x : (bubble1.next != null) ? bubble1.x - bubble1.next.x : 1; double f15 = (bubble1.prev != null) ? bubble1.prev.y - bubble1.y : (bubble1.next != null) ? bubble1.y - bubble1.next.y : 0; double f16 = Math.sqrt(f12 * f12 + f15 * f15); f15 /= f16; boolean flag2 = true; if (Math.abs(f15) > 0.4) { flag2 = (f15 < 0); } else { flag2 = ! ((bubble1.prev != null && shot_bubble.x > f10 || bubble1.prev == null) && shot_bubble.x < f11); } if (!flag2) { bubble2.next = bubble1; bubble2.prev = bubble1.prev; bubble2.t = bubble1.t - 0.5; if (bubble1.prev != null) { bubble1.prev.next = bubble2; } else { first_bub = bubble2; } bubble1.prev = bubble2; } else { bubble2.prev = bubble1; bubble2.next = bubble1.next; bubble2.t = bubble1.t + 0.5; if (bubble1.next != null) { bubble1.next.prev = bubble2; } bubble1.next = bubble2; } shot_bubble.bm = null; } if (bubble1.next != null) { int i = 1; boolean flag = bubble1.shot; if (bubble1.prev == null || bubble1.prev.bm != bubble1.bm) { for (Bubble bubble3 = bubble1.next; bubble3 != null && bubble3.bm == bubble1.bm; bubble3 = bubble3.next) { if (bubble3.t - (i + bubble1.t) > 0.01) { i = 0; break; } if (bubble3.shot) { flag = true; } i++; } } if (flag && i >= 3) { game.playSound(snd_plip_plop); level_score += i * 50; total_score += i * 50; if (!isSomeBonusActing() && (randInt(16) == 4 || i >= 4 && randInt(10) <= i)) { double f13 = (path_t0 + bubble.t) / path_last_t; if(f13 > 0.4) { Item item = new Item(); item.type = 3; item.x = bubble1.x; item.y = item.py = bubble1.y; item.vel_y = 70; item.bonus = getRandomBonus(); item.bm = item.bonus.icon; if(items == null) { items = item; } else { item.next = items.next; items.next = item; } } } boolean flag1 = false; int j = 1; double curr_x = 0; double curr_y = 0; for (int k = i; k > 0; k--) { curr_x += bubble1.x; curr_y += bubble1.y; j += bubble1.combo; if (bubble1.fish_inside) { total_fish_saved++; fish_to_save--; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } spawnBurst(bubble1.x, bubble1.y); if (bubble1.next != null) { bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } if (bubble1 == first_bub) { first_bub = bubble1.next; } if (bubble1.next != null) { bubble1 = bubble1.next; } else { flag1 = true; bubble1 = bubble1.prev; } } curr_x /= i; curr_y /= i; if (bubble1 != null && adjIsGoingToBurst(bubble1)) { bubble1.combo = j; } if (j > 1) { PartString partstring = new PartString(this, curr_x, curr_y, "Combo " + j + "x", 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } if (longest_combo < j) { longest_combo = j; } if (j > 0) { j--; } if (j > 7) { j = 7; } game.playSound(snd_combo[j]); Bubble bubble6 = bubble1; if (bubble6 != null && bubble6.prev != null && bubble6.bm == bubble6.prev.bm && !flag1) { bubble6.shot = true; } } if (bubble1 == null) { if (fish_to_save <= 0) { level_completed = true; } if (level_completed) { first_bub = null; return; } else { first_bub = bubble1 = new Bubble(); bubble1.bm = getRandomBubble(false); bubble1.t = -path_t0; updateBubble(bubble1); return; } } if (bubble1.next == null) { return; } double f14 = Math.abs(bubble1.next.t - bubble1.t); if (f14 < 0.99) { for (Bubble bubble4 = bubble1.next; bubble4 != null; bubble4 = bubble4.next) { double f18 = 6 * (1 - f14) * elapsedTime; if (f18 > f14) f18 = f14; bubble4.t += f18; } } if (f14 > 1.01) { for(Bubble bubble5 = bubble1.next; bubble5 != null; bubble5 = bubble5.next) { double f19 = 2 * f14 * elapsedTime; if (f19 > 0.15) { f19 = 0.15; } if (f19 > f14) { f19 = f14; } bubble5.t -= f19; } } } if (bubble1.combo > 0 && !adjIsGoingToBurst(bubble1)) { bubble1.combo = 0; } } } void updateBubble (Bubble bubble) { Point2D.Double tp = getPathPoint(path_t0 + bubble.t); bubble.x = tp.x; bubble.y = tp.y; } public void handleInput () { if (game.keyPressed(KeyEvent.VK_SPACE)) { if (game_state == GS_PLAY) { game.playSound(snd_pick); paused = !paused; } else { paused = false; } } if (game.click()) { if (game_state == GS_LEVEL_COMPLETED) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; if (level / 5 + 1 >= 4) { completed_the_game = true; game_state = GS_GAME_OVER; } initLevel(level + 1); } else if (game_state == GS_GAME_OVER) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_MAINMENU) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_PLAY && !paused) { if (smrocks > 0) { game.playSound(snd_shoot_bubble); smrocks--; Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -360; item.type = ITEM_SMROCKS; item.bonus = null; item.bm = bm_smrock; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; PartString partstring = new PartString(this, item.x, item.y, "" + smrocks, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } else if (torpedo) { torpedo = false; game.playSound(snd_shoot_bubble); Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -120; item.type = ITEM_TORPEDO; item.bonus = null; item.bm = bm_torpedo; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; } else if (shot_bubble.bm != null) { return; } else if (shoot_time < 0.8) { return; } else { game.playSound(snd_shoot_bubble); shot_bubble.bm = next_bubble; next_bubble = next_bubble2; next_bubble2 = getRandomBubble(false); shot_bubble.x = game.getMouseX(); shot_bubble.y = bob_y - 10; shoot_time = 0; } } } if (game.rightClick()) { game.playSound(snd_swap); Sprite next = next_bubble; next_bubble = next_bubble2; next_bubble2 = next; shoot_time = 0.5; } } void addPart (Part part) { if (parts == null) { parts = part; } else { part.next = parts; parts = part; } } Point2D.Double getPathPoint (double idx) { if (idx < 0) { return new Point2D.Double(-30, -400); } double idx_dist = idx * 2 * RAD_BUBBLE; double curr_dist = 0; for (int i = 0; i < num_path_points; i++) { double next_dist = curr_dist + path[i].dist_to_next; if (idx_dist < next_dist) { double curr_idx = (idx_dist - curr_dist) / path[i].dist_to_next; return new Point2D.Double(path[i].x + (path[i + 1].x - path[i].x) * curr_idx, path[i].y + (path[i + 1].y - path[i].y) * curr_idx); } curr_dist = next_dist; } return new Point2D.Double(path[num_path_points - 1].x, path[num_path_points - 1].y); } void setPathPoint (int idx, double x, double y) { path[idx] = new PathPoint(); path[idx].x = (x + path_inc_x) * 0.71; path[idx].y = (y + path_inc_y - 10) * 0.71; if (idx > 0) { double dx = path[idx - 1].x - path[idx].x; double dy = path[idx - 1].y - path[idx].y; path[idx - 1].dist_to_next = Math.sqrt(dx * dx + dy * dy); } num_path_points = idx + 1; } boolean existsInPath (Sprite bub) { for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (bubble.bm == bub) { return true; } } return false; } Bubble getLastBubble () { if (first_bub == null) return null; Bubble bubble; for (bubble = first_bub; bubble.next != null; bubble = bubble.next) ; return bubble; } boolean adjIsGoingToBurst (Bubble bubble) { Sprite s = bubble.bm; int i = 1; for (Bubble b = bubble.prev; b != null && b.bm == s; b = b.prev) i++; for (Bubble b = bubble.next; b != null && b.bm == s; b = b.next) i++; return i >= 3; } void spawnBiggerBurst (double x, double y) { for (int i = 0; i < 30; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(140, 310); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 3.8)); partbub.life += randDouble(0, 0.4); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle); partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } void spawnBurst (double x, double y) { y += 5; for (int i = 0; i < 26; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(50, 100); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 4.2)); partbub.life += randDouble(0, 0.2); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle) - magnitude; partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } Sprite getRandomBubble (boolean totally_random) { int max = 3 + (episode + 1) / 2; if (totally_random) { return bm_bubbles[randInt(max)]; } for (int j = 0; j < 300; j++) { Sprite bub = bm_bubbles[randInt(max)]; if (existsInPath(bub)) { return bub; } } System.out.println("stalled."); return bm_bubbles[randInt(max)]; } AbstractBonus getRandomBonus () { int i = randInt(num_bonuses); AbstractBonus bonus = bonuses; for (bonus = bonuses; i != 0; bonus = bonus.next, i--) ; return bonus; } int randInt (int max) { return (int)(Math.random() * max); } double randDouble (double min, double max) { return min + Math.random() * (max - min); } String scoreString () { StringBuffer stringbuffer = new StringBuffer(score_show); for (int i = stringbuffer.length() - 1 - 2; i > 0; i -= 3) { stringbuffer.insert(i, "0"); } return stringbuffer.toString(); } }
Java
package game; import ResourceManager; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.geom.Point2D; import com.golden.gamedev.Game; import com.golden.gamedev.object.Sprite; /** * refactored version of prog bob i refactored the level creation * so that it reads from a resource file and doesn't use if statements * @author Shun * */ public class ProgBob { final static int RAD_BUBBLE = 13; final static int W_SMFISH = 8; final static int H_SMFISH = 6; final static int GS_MAINMENU = 0; final static int GS_PLAY = 1; final static int GS_LEVEL_COMPLETED = 2; final static int GS_GAME_OVER = 3; final static int ITEM_FREE = 0; final static int ITEM_BUBBLE = 1; final static int ITEM_TORPEDO = 2; final static int ITEM_BONUS = 3; final static int ITEM_SMROCKS = 4; final static int NUM_BOB_STATES = 11; final static int MAX_BUBBLES = 128; final static double MAX_TIME_PAUSED = 6; final static double MAX_TIME_REWIND = 4; final static double PI_2 = 2 * Math.PI; Font fnt; Font fnt2; Font fnt3; Font fnts[]; Sprite bm_bob[]; Sprite bm_bubbles[]; Sprite bm_evil_fish; Sprite bm_smfish; Sprite bm_torpedo; Sprite bm_smrock; Sprite bm_fisho; Sprite bm_click_to_continue; Sprite bm_congrats; Sprite bm_bg_menu; Sprite bm_bg_game; Sprite bm_lev_comp; Sprite bm_loading; Sprite bm_game_over; Sprite bm_part_bub[]; String snd_level_start; String snd_explosion; String snd_shoot_bubble; String snd_plip_plop; String snd_pop; String snd_bob_loses; String snd_pick; String snd_swap; String snd_lev_comp; String snd_combo[]; boolean torpedoBoolean; int smrocks; double name_show; int episode; int sub_level; int total_fish_saved; int longest_combo; double handicap; int game_state; boolean game_starting; boolean completed_the_game; // double time_rewind; // double time_paused; int num_bonuses; AbstractBonus bonuses; AbstractBonus[] allBonus; Part parts; Item items; int num_path_points; PathPoint path[]; double path_t0; double path_speed; int fish_to_save; int fish_to_save_at_start; double path_last_t; double path_start_t; Bubble bubbles[]; Bubble first_bub; Bubble shot_bubble; Sprite next_bubble; Sprite next_bubble2; int bob_y; int bob_x; double bob_akey; double akey0; double akey1; double akey2; double akey3; double shoot_time; boolean game_over; double go_speedup; int level; boolean level_completed; double st_timer; int level_score; int total_score; int score_show; boolean paused; int path_inc_x; int path_inc_y; Game game; private ResourceManager bonusTypeResource = new ResourceManager("BonusTypesResource"); BonusFactory factory = new BonusFactory(); boolean isSomeBonusActing () { //return time_rewind > 0 || time_paused > 0 || items != null || smrocks > 0 || torpedoBoolean; } public void init (Game game) { this.game = game; fnt = Font.decode("Arial-BOLD-16"); fnt2 = Font.decode("Arial-BOLD-20"); fnt3 = Font.decode("Arial-PLAIN-14"); fnts = new Font[11]; for (int k = 0; k < 11; k++) { fnts[k] = Font.decode("Arial-PLAIN-" + (k + 2)); } Part part = new Part(this, 10, 10, null, 0); for (int k = 0; k < 100; k++) { part.next = new Part(this, 10, 10, null, 0); part = part.next; } for (int k = 0; k < 100; k++) { part.next = new PartBub(this, 10, 10, null, 0); part = part.next; } bm_loading = new Sprite(game.getImage("resources/loading.jpg")); bm_click_to_continue = new Sprite(game.getImage("resources/click_to_continue.png")); bm_congrats = new Sprite(game.getImage("resources/congrats.png")); bm_bob = new Sprite[NUM_BOB_STATES]; bm_bob[0] = new Sprite(game.getImage("resources/bob_0000.png")); bm_bob[1] = new Sprite(game.getImage("resources/bob_0002.png")); bm_bob[2] = new Sprite(game.getImage("resources/bob_0004.png")); bm_bob[3] = new Sprite(game.getImage("resources/bob_0006.png")); bm_bob[4] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[5] = new Sprite(game.getImage("resources/bob_0008.png")); bm_bob[6] = new Sprite(game.getImage("resources/bob_0010.png")); bm_bob[7] = new Sprite(game.getImage("resources/bob_0012.png")); bm_bob[8] = new Sprite(game.getImage("resources/bob_0014.png")); bm_bob[9] = new Sprite(game.getImage("resources/bob_0016.png")); bm_bob[10] = new Sprite(game.getImage("resources/bob_0018.png")); bm_evil_fish = new Sprite(game.getImage("resources/evil_fish.png")); bm_smfish = new Sprite(game.getImage("resources/smfish.png")); snd_shoot_bubble = "resources/release_bubble.au"; snd_combo = new String[8]; snd_combo[0] = "resources/combo_01.au"; snd_combo[1] = "resources/combo_02.au"; snd_combo[2] = "resources/combo_03.au"; snd_combo[3] = "resources/combo_04.au"; snd_combo[4] = "resources/combo_05.au"; snd_combo[5] = "resources/combo_06.au"; snd_combo[6] = "resources/combo_07.au"; snd_combo[7] = "resources/combo_08.au"; snd_plip_plop ="resources/pop_01.au"; snd_pop = "resources/pop_01.au"; snd_bob_loses = "resources/bob_loses.au"; snd_pick = "resources/pickup.au"; snd_swap = "resources/gulp.au"; snd_lev_comp = "resources/lev_comp_song.au"; snd_level_start = "resources/level_start.au"; snd_explosion = "resources/explosion.au"; bm_bubbles = new Sprite[7]; bm_bubbles[0] = new Sprite(game.getImage("resources/blue.png")); bm_bubbles[1] = new Sprite(game.getImage("resources/red.png")); bm_bubbles[2] = new Sprite(game.getImage("resources/green.png")); bm_bubbles[3] = new Sprite(game.getImage("resources/orange.png")); bm_bubbles[4] = new Sprite(game.getImage("resources/purple.png")); bm_bubbles[5] = new Sprite(game.getImage("resources/cyan.png")); bm_bubbles[6] = new Sprite(game.getImage("resources/white.png")); bm_bg_game = new Sprite(game.getImage("resources/seagrass.jpg")); bm_bg_menu = new Sprite(game.getImage("resources/bg_menu.jpg")); bm_lev_comp = new Sprite(game.getImage("resources/lev_comp.png")); bm_game_over = new Sprite(game.getImage("resources/game_over.png")); bm_part_bub = new Sprite[4]; bm_part_bub[0] = new Sprite(game.getImage("resources/part_bub_01.png")); bm_part_bub[1] = new Sprite(game.getImage("resources/part_bub_02.png")); bm_part_bub[2] = new Sprite(game.getImage("resources/part_bub_03.png")); bm_part_bub[3] = new Sprite(game.getImage("resources/part_bub_04.png")); // bm_torpedo = new Sprite(game.getImage("resources/torpedo.png")); // bm_smrock = new Sprite(game.getImage("resources/smrock.png")); bm_fisho = new Sprite(game.getImage("resources/fisho_full.png")); //This creates an arrayList of bonuses from a read-in properties file String[] stringBonuses = bonusTypeResource.getStringArray("bonusList"); allBonus = new AbstractBonus[stringBonuses.length]; for(int i = 0; i < stringBonuses.length; i++){ allBonus[i] =(factory.getBonusInstance(stringBonuses[i])); } // bonuses = new BonusPause(this, "Pause", new Sprite(game.getImage("resources/bonus_pause.png"))); // bonuses.next = new BonusRewind(this, "Rewind", new Sprite(game.getImage("resources/bonus_rewind.png"))); // bonuses.next.next = new BonusTorpedo(this, "Torpedo", new Sprite(game.getImage("resources/bon_torpedo.png"))); // bonuses.next.next.next = new BonusSmRocks(this, "Small Rocks", new Sprite(game.getImage("resources/bon_smrocks.png"))); num_bonuses = 4; game_state = GS_MAINMENU; initLevel(1); } void initGame () { total_fish_saved = 0; total_score = 0; level_score = 0; shoot_time = 0; completed_the_game = false; game_over = false; paused = false; } void initLevel (int level_num) { for(AbstractBonus bonus : allBonus){ bonus.turnOff(); } paused = false; level_completed = false; handicap = 1; longest_combo = 0; // torpedoBoolean = false; smrocks = 0; name_show = 0; // time_rewind = 0; // time_paused = 0; items = null; game_starting = true; level_score = 0; go_speedup = 0; st_timer = 0; shot_bubble = new Bubble(); shot_bubble.bm = null; path_speed = 0.5; bob_y = 290; bob_akey = 0; level = level_num; episode = (level - 1) / 5; sub_level = (level - 1) % 5 + 1; //refactored level no more if statements Level level = new Level(sub_level); fish_to_save_at_start = fish_to_save = level.getFishLeftToSave(); path_speed = level.getBubblePathSpeed(); path_start_t = level.getBubblePathStartPos(); num_path_points = level.getNumberOfBubblePathPoints(); path = level.getBubblePath(); path_speed += episode * 0.08; path_t0 = 0; path_last_t = 0; for (int k = 0; k < num_path_points; k++) { path_last_t += path[k].dist_to_next; } path_last_t /= 2 * RAD_BUBBLE; bubbles = new Bubble[MAX_BUBBLES]; for (int k = 0; k < bubbles.length; k++) { bubbles[k] = new Bubble(); } first_bub = new Bubble(); first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; Point2D.Double pnt = getPathPoint(0); first_bub.x = pnt.x; first_bub.y = pnt.y; next_bubble = getRandomBubble(true); next_bubble2 = getRandomBubble(true); } public void draw (Graphics2D context) { if (game_state == GS_MAINMENU) { bm_bg_menu.render(context); } else if (game_state == GS_LEVEL_COMPLETED) { bm_bg_game.render(context, 0, 0); bm_lev_comp.render(context, 90, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 151, "Fish Saved:"); drawOutlined(context, 340, 168, "" + total_fish_saved); drawOutlined(context, 140, 151, "Max Combo:"); drawOutlined(context, 140, 168, "" + longest_combo); drawOutlined(context, 240, 205, "Level Score:"); drawOutlined(context, 240, 222, "" + level_score); context.setFont(fnt); context.setColor(Color.WHITE); bm_click_to_continue.render(context, 156, 290); drawParts(context); drawBar(context); } else if (game_state == GS_GAME_OVER) { bm_bg_game.render(context, 0, 0); if (completed_the_game) { context.setColor(Color.WHITE); context.setFont(fnt2); bm_congrats.render(context, 50, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 340, 175, "Fish Saved:"); drawOutlined(context, 340, 192, "" + total_fish_saved); drawOutlined(context, 140, 175, "Final Score:"); drawOutlined(context, 140, 192, "" + total_score); } else { bm_game_over.render(context, 132, 30); context.setColor(Color.WHITE); context.setFont(fnt); drawOutlined(context, 240, 111, "Fish Saved:"); drawOutlined(context, 240, 128, "" + total_fish_saved); drawOutlined(context, 240, 155, "Final Score:"); drawOutlined(context, 240, 172, "" + total_score); } drawParts(context); drawBar(context); bm_click_to_continue.render(context, 156, 290); } else if (game_state == GS_PLAY) { bm_bg_game.render(context, 0, 0); drawPath(context); drawParts(context); drawItems(context); bob_x = game.getMouseX(); int y_offset = (int)(5 * Math.sin(shoot_time * Math.PI)); for(AbstractBonus bonus: allBonus){ if(bonus.isOn()){ bonus.setBonusPosition(bob_x, bob_y, y_offset); } } // if (torpedoBoolean) // { // bm_torpedo.setX(bob_x - bm_torpedo.getWidth() / 2); // bm_torpedo.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); // bm_torpedo.render(context); // } // else if (smrocks > 0) // { // bm_smrock.setX(bob_x - bm_torpedo.getWidth() / 2); // bm_smrock.setY(bob_y - bm_torpedo.getHeight() / 2 + y_offset); // bm_smrock.render(context); // } else { if (shoot_time >= 1) { next_bubble.setX(bob_x - next_bubble.getWidth() / 2); next_bubble.setY(bob_y - next_bubble.getHeight() + y_offset); next_bubble.render(context); } else { int x_offset = (int)(shoot_time * 2 * RAD_BUBBLE); next_bubble.setX(bob_x - x_offset / 2); next_bubble.setY((bob_y + (1 - shoot_time) * 4 * RAD_BUBBLE) - next_bubble.getHeight() + y_offset); next_bubble.render(context); } // BUGBUG: change size to 16x16 next_bubble2.render(context, (int)((bob_x - 16 / 2) + 1), (int)(((bob_y - 4) + y_offset) + (1 - shoot_time) * 16)); } bm_bob[(int)bob_akey].render(context, bob_x - 22, bob_y + y_offset); drawBar(context); if (name_show < 1 && !paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Level " + (episode + 1) + "-" + sub_level); } } if (paused) { context.setFont(fnt2); context.setColor(Color.BLACK); drawOutlined(context, 240, 170, "Paused"); context.setFont(fnt); context.setColor(Color.BLACK); context.drawString("Press space to continue", 240, 190); } } void drawParts (Graphics2D context) { for (Part part = parts; part != null; part = part.next) { if (part.life < 0.999) { part.draw(context); } } } void drawPath (Graphics2D context) { int x = 0; int y = 0; double t = 0; for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (path_t0 + bubble.t < path_last_t - 1) { if (bubble.fish_inside) { bm_smfish.setX(bubble.x - 8); bm_smfish.setY(bubble.y - 6 + 2 * Math.sin(bubble.phase * PI_2)); bm_smfish.render(context); } double x_scale = 1 - bubble.trans; x = (int)(bubble.trans * bubble.attach_x + x_scale * bubble.x); if (path_t0 + bubble.t >= path_last_t - 4) { double y_scale = ((path_t0 + bubble.t) - (path_last_t - 4)) / 4; y = (int)((bubble.trans * bubble.attach_y + x_scale * bubble.y) + 3 * Math.sin(bubble.phase * PI_2) * (1 - y_scale) + 4 * Math.sin(PI_2 * akey2) * y_scale); } else { y = (int)(bubble.trans * bubble.attach_y + x_scale * bubble.y + 3 * Math.sin(bubble.phase * PI_2)); } bubble.bm.render(context, x - RAD_BUBBLE, y - RAD_BUBBLE); } t = bubble.t; } t += path_t0 + 1 + st_timer * (path_t0 + path_last_t - t); for (double t1 = Math.floor(t); t1 < path_last_t; t1 += 0.5) { Point2D.Double pnt = getPathPoint(t1); y = (int)(pnt.y + 3 * Math.sin(PI_2 * akey1 + t1)); bm_part_bub[3].render(context, (int)pnt.x - 2, y - 2); } x = (int)(path[num_path_points - 1].x - 55 + (1 - Math.sin(0.5 * Math.PI + 0.5 * Math.PI * st_timer)) * (480 - x)); y = (int)path[num_path_points - 1].y; bm_evil_fish.render(context, x, (y + (int)(4 * Math.sin(PI_2 * akey2))) - 40); } void drawItems (Graphics2D context) { for (Item item = items; item != null; item = item.next) { int x = (int)(item.x + 3 * Math.sin(PI_2 * akey1)); int y = (int)item.y; if (4 * item.time_existed < 1 && item.vel_y > 0) { double t = 4 * item.time_existed; int w = (int)(item.bm.getWidth() * t); int h = (int)(item.bm.getHeight() * t); // BUGBUG: change size item.bm.render(context, x - w / 2, y - h / 2); } else { item.bm.render(context, x, y); } } if (shot_bubble.bm != null) { shot_bubble.bm.render(context, (int)shot_bubble.x, (int)shot_bubble.y); } } void drawBar (Graphics2D context) { int w = bm_fisho.getWidth(); int h = (int)(w * ((fish_to_save_at_start - fish_to_save) / fish_to_save_at_start)); // BUGBUG: change size bm_fisho.render(context, 276, 342); context.setColor(Color.WHITE); context.setFont(fnt); context.drawString(scoreString(), 63, 354); context.drawString((episode + 1) + " - " + sub_level, 190, 354); } void drawOutlined (Graphics2D context, int x, int y, String text) { // BUGBUG: center context.setColor(Color.BLACK); context.drawString(text, x - 2, y - 2); context.drawString(text, x - 2, y + 2); context.drawString(text, x + 2, y + 2); context.drawString(text, x + 2, y - 2); context.drawString(text, x - 2, y); context.drawString(text, x, y + 2); context.drawString(text, x + 2, y); context.drawString(text, x, y - 2); context.setColor(new Color(0xECD300)); context.drawString(text, x, y); } public void update (double elapsedTime) { if (paused || game_state != GS_PLAY) { return; } if (!level_completed && !game_over && !existsInPath(next_bubble)) { next_bubble = getRandomBubble(false); } akey0 = (akey0 + elapsedTime) % 1.0; akey1 = (akey1 + 0.7 * elapsedTime) % 1.0; akey2 = (akey2 + 0.5 * elapsedTime) % 1.0; akey3 = (akey3 + 0.3 * elapsedTime) % 1.0; bob_akey = (bob_akey + 2 * elapsedTime) % NUM_BOB_STATES; //time_paused = Math.max(0, time_paused - elapsedTime); time_rewind = Math.max(0, time_rewind - elapsedTime); shoot_time = Math.min(1, shoot_time + 3 * elapsedTime); name_show += 0.7 * elapsedTime; score_show += Math.min(4, (int)(5 * elapsedTime * (total_score - score_show))); score_show = Math.min(score_show, total_score); updateParts(elapsedTime); updateItems(elapsedTime); updateBubbles(elapsedTime); } void updateParts (double time) { Part dead = null; for (Part part = parts; part != null; part = part.next) { part.life -= part.speed * time; if (part.life <= 0.001) { if (dead == null) { parts = part.next; } else { dead.next = part.next; } } else if (part.life < 0.999) { part.x += time * part.vx; part.y += time * part.vy; dead = part; } } } void updateItems (double time) { Item dead = null; for (Item item = items; item != null; item = item.next) { item.y += time * item.vel_y; if (item.y < -21 || item.y > 380 || item.type == ITEM_FREE) { if (dead == null) { items = items.next; } else { dead.next = item.next; } } else { item.time_existed += time; if (item.type == ITEM_TORPEDO || item.type == ITEM_SMROCKS) { if (item.type == ITEM_TORPEDO) { item.vel_y -= 400 * time; } for ( ; Math.abs(item.y - item.py) > 4; item.py -= 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-5, 5); addPart(partbub); } for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { double dx = item.x - bubble.x; double dy = item.y - bubble.y; if (dx * dx + dy * dy < RAD_BUBBLE * RAD_BUBBLE) { if (item.type == ITEM_TORPEDO) { for (Bubble bubble1 = first_bub; bubble1 != null; bubble1 = bubble1.next) { spawnBiggerBurst(item.x, item.y); double ddx = item.x - bubble1.x; double ddy = item.y - bubble1.y; if (ddx * ddx + ddy * ddy < 4096 && path_t0 + bubble1.t > 0) { spawnBurst(bubble1.x, bubble1.y); if (bubble1.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble1.next != null) { bubble1.next.shot = true; bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } else { first_bub = bubble1.next; } } } game.playSound(snd_explosion); shoot_time = 0.5; } else if (item.type == ITEM_SMROCKS) { spawnBurst(bubble.x, bubble.y); if (bubble.fish_inside) { fish_to_save--; total_fish_saved++; Part part = new Part(this, bubble.x, bubble.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } if (bubble.next != null) { bubble.next.shot = true; bubble.next.prev = bubble.prev; } if (bubble.prev != null) { bubble.prev.next = bubble.next; } else { first_bub = bubble.next; } game.playSound(snd_pop); } item.type = ITEM_FREE; if (first_bub == null) { if (fish_to_save <= 0) { level_completed = true; } else { first_bub = new Bubble(); first_bub.t = -path_t0 - 1; first_bub.bm = getRandomBubble(true); first_bub.fish_inside = true; } } } } } else { for ( ; Math.abs(item.y - item.py) > 4; item.py += 4) { PartBub partbub = new PartBub(this, item.x, item.py, bm_part_bub[0], randDouble(1, 2.2)); partbub.vx = randDouble(-5, 5); partbub.vy = randDouble(-50, -10); partbub.x += randDouble(-7, 7); addPart(partbub); } if (item.bonus != null && Math.abs(item.x - bob_x) < 25 && Math.abs(item.y - (bob_y + 20)) < 38) { spawnBurst(item.x, item.y); game.playSound(snd_pick); PartString partstring = new PartString(this, item.x, item.y, item.bonus.name, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); shoot_time = 0.5; item.bonus.toogleBonus(); if (dead == null) { items = items.next; } else { dead.next = item.next; } } } dead = item; } } } void updateBubbles (double elapsedTime) { double acc = path_speed * 1.5; Bubble bubble = getLastBubble(); if (bubble != null) { if (game_starting) { double t = path_t0 + bubble.t; if (t < path_start_t - 8) { acc *= 25; } else if (t < path_start_t) { acc *= 1 + (24 * (path_start_t - t)) / 8; } else { game_starting = false; } } double t = (path_t0 + bubble.t) / path_last_t; if (time_paused <= 0) { if (t < 0.7) { if (t > 0.1) { handicap += 0.1 * (0.7 - t) * elapsedTime; } else { handicap += 0.06 * elapsedTime; } } else if (t > 0.7) { handicap -= 0.15 * (t - 0.7) * elapsedTime; } } handicap = Math.max(0.95, Math.min(handicap, 4)); acc *= handicap; if (t < 0.4) { t = 1 + 15 * (0.4 - t); } else if (t > 0.8) { if (t > 0.95) { t = 0.95; } t = 2.5 * (1 - t); if (t < 0.15) { t = 0.15; } } else { t = 0.5 + 0.5 * (1 - (t - 0.4) / 0.4); } acc *= t; } acc = Math.max(0.2, acc); if (time_paused > 0) { double factor = 1; if (time_paused > 5) { factor = 1 - (MAX_TIME_PAUSED - time_paused); } else if (time_paused > 1) { factor = 0; } else if (time_paused > 0) { factor = 1 - time_paused; } acc *= factor; } if (time_rewind > 0) { double factor = 0; if (time_rewind > 3) { factor = 4 - time_rewind; } else if (time_rewind > 1) { factor = 1; } else if (time_rewind > 0) { factor = 1 * time_rewind; } acc = acc * (1 - factor) - 3 * factor; } if (game_over) { acc += go_speedup; go_speedup += 32 * elapsedTime; } else { acc = Math.max(-12, Math.min(acc, 12)); } acc *= elapsedTime; if (bubble != null && (path_t0 + bubble.t > 0 || acc > 0)) { path_t0 += acc; } if (game_over) { if (first_bub == null) { st_timer += elapsedTime; } if (st_timer > 1) { game_state = GS_GAME_OVER; } } if (level_completed) { st_timer += elapsedTime; if (st_timer > 1) { if (game_state != GS_LEVEL_COMPLETED) { game.playSound(snd_lev_comp); } game_state = GS_LEVEL_COMPLETED; } return; } double shot_y = shot_bubble.y; shot_bubble.y -= 620 * elapsedTime; if (shot_bubble.bm != null) { for (double part_y = shot_bubble.y; part_y < shot_y; part_y += 5) { PartBub partbub = new PartBub(this, shot_bubble.x, part_y, bm_part_bub[0], randDouble(3, 4.2)); partbub.vx = randDouble(-10, 10); partbub.vy = randDouble(-40, 0); partbub.x += randDouble(-7, 7); addPart(partbub); } } if (shot_bubble.y < -2 * RAD_BUBBLE) { shot_bubble.bm = null; } Bubble bubble1 = first_bub; while (!game_over && fish_to_save > 0 && first_bub.x > -2 * RAD_BUBBLE) { bubble1 = new Bubble(); bubble1.phase = first_bub.phase - 0.1; bubble1.fish_inside = true; bubble1.shot = false; first_bub.prev = bubble1; bubble1.next = first_bub; bubble1.t = first_bub.t - 1; bubble1.bm = getRandomBubble(true); first_bub = bubble1; updateBubble(first_bub); } for ( ; bubble1 != null; bubble1 = bubble1.next) { if (path_t0 + bubble1.t >= path_last_t) { if (!game_over) { game.playSound(snd_bob_loses); } game_over = true; if (bubble1.prev != null) { bubble1.prev.next = null; } if (bubble1 == first_bub) { first_bub = null; return; } } bubble1.phase += (elapsedTime % 1.0); bubble1.trans = Math.max(0, bubble1.trans - 4 * elapsedTime); updateBubble(bubble1); if (shot_bubble.bm != null && shot_bubble.y - 2 * RAD_BUBBLE <= bubble1.y + 8 && shot_y + 2 * RAD_BUBBLE + 10 > bubble1.y + 8 && Math.abs(shot_bubble.x - bubble1.x) < 15) { Bubble bubble2 = new Bubble(); bubble2.bm = shot_bubble.bm; bubble2.shot = true; bubble2.trans = 1; bubble2.attach_x = shot_bubble.x; bubble2.attach_y = shot_bubble.y; double f10 = (bubble1.prev != null) ? Math.min(bubble1.prev.x, bubble1.x) : bubble1.x - RAD_BUBBLE; double f11 = (bubble1.prev != null) ? Math.max(bubble1.prev.x, bubble1.x) : bubble1.x; double f12 = (bubble1.prev != null) ? bubble1.prev.x - bubble1.x : (bubble1.next != null) ? bubble1.x - bubble1.next.x : 1; double f15 = (bubble1.prev != null) ? bubble1.prev.y - bubble1.y : (bubble1.next != null) ? bubble1.y - bubble1.next.y : 0; double f16 = Math.sqrt(f12 * f12 + f15 * f15); f15 /= f16; boolean flag2 = true; if (Math.abs(f15) > 0.4) { flag2 = (f15 < 0); } else { flag2 = ! ((bubble1.prev != null && shot_bubble.x > f10 || bubble1.prev == null) && shot_bubble.x < f11); } if (!flag2) { bubble2.next = bubble1; bubble2.prev = bubble1.prev; bubble2.t = bubble1.t - 0.5; if (bubble1.prev != null) { bubble1.prev.next = bubble2; } else { first_bub = bubble2; } bubble1.prev = bubble2; } else { bubble2.prev = bubble1; bubble2.next = bubble1.next; bubble2.t = bubble1.t + 0.5; if (bubble1.next != null) { bubble1.next.prev = bubble2; } bubble1.next = bubble2; } shot_bubble.bm = null; } if (bubble1.next != null) { int i = 1; boolean flag = bubble1.shot; if (bubble1.prev == null || bubble1.prev.bm != bubble1.bm) { for (Bubble bubble3 = bubble1.next; bubble3 != null && bubble3.bm == bubble1.bm; bubble3 = bubble3.next) { if (bubble3.t - (i + bubble1.t) > 0.01) { i = 0; break; } if (bubble3.shot) { flag = true; } i++; } } if (flag && i >= 3) { game.playSound(snd_plip_plop); level_score += i * 50; total_score += i * 50; if (!isSomeBonusActing() && (randInt(16) == 4 || i >= 4 && randInt(10) <= i)) { double f13 = (path_t0 + bubble.t) / path_last_t; if(f13 > 0.4) { Item item = new Item(); item.type = 3; item.x = bubble1.x; item.y = item.py = bubble1.y; item.vel_y = 70; item.bonus = getRandomBonus(); item.bm = item.bonus.icon; if(items == null) { items = item; } else { item.next = items.next; items.next = item; } } } boolean flag1 = false; int j = 1; double curr_x = 0; double curr_y = 0; for (int k = i; k > 0; k--) { curr_x += bubble1.x; curr_y += bubble1.y; j += bubble1.combo; if (bubble1.fish_inside) { total_fish_saved++; fish_to_save--; Part part = new Part(this, bubble1.x, bubble1.y, bm_smfish, 0.4); part.vx = randDouble(-180, -140); part.vy = randDouble(-20, 20); addPart(part); } spawnBurst(bubble1.x, bubble1.y); if (bubble1.next != null) { bubble1.next.prev = bubble1.prev; } if (bubble1.prev != null) { bubble1.prev.next = bubble1.next; } if (bubble1 == first_bub) { first_bub = bubble1.next; } if (bubble1.next != null) { bubble1 = bubble1.next; } else { flag1 = true; bubble1 = bubble1.prev; } } curr_x /= i; curr_y /= i; if (bubble1 != null && adjIsGoingToBurst(bubble1)) { bubble1.combo = j; } if (j > 1) { PartString partstring = new PartString(this, curr_x, curr_y, "Combo " + j + "x", 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } if (longest_combo < j) { longest_combo = j; } if (j > 0) { j--; } if (j > 7) { j = 7; } game.playSound(snd_combo[j]); Bubble bubble6 = bubble1; if (bubble6 != null && bubble6.prev != null && bubble6.bm == bubble6.prev.bm && !flag1) { bubble6.shot = true; } } if (bubble1 == null) { if (fish_to_save <= 0) { level_completed = true; } if (level_completed) { first_bub = null; return; } else { first_bub = bubble1 = new Bubble(); bubble1.bm = getRandomBubble(false); bubble1.t = -path_t0; updateBubble(bubble1); return; } } if (bubble1.next == null) { return; } double f14 = Math.abs(bubble1.next.t - bubble1.t); if (f14 < 0.99) { for (Bubble bubble4 = bubble1.next; bubble4 != null; bubble4 = bubble4.next) { double f18 = 6 * (1 - f14) * elapsedTime; if (f18 > f14) f18 = f14; bubble4.t += f18; } } if (f14 > 1.01) { for(Bubble bubble5 = bubble1.next; bubble5 != null; bubble5 = bubble5.next) { double f19 = 2 * f14 * elapsedTime; if (f19 > 0.15) { f19 = 0.15; } if (f19 > f14) { f19 = f14; } bubble5.t -= f19; } } } if (bubble1.combo > 0 && !adjIsGoingToBurst(bubble1)) { bubble1.combo = 0; } } } void updateBubble (Bubble bubble) { Point2D.Double tp = getPathPoint(path_t0 + bubble.t); bubble.x = tp.x; bubble.y = tp.y; } public void handleInput () { if (game.keyPressed(KeyEvent.VK_SPACE)) { if (game_state == GS_PLAY) { game.playSound(snd_pick); paused = !paused; } else { paused = false; } } if (game.click()) { if (game_state == GS_LEVEL_COMPLETED) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; if (level / 5 + 1 >= 4) { completed_the_game = true; game_state = GS_GAME_OVER; } initLevel(level + 1); } else if (game_state == GS_GAME_OVER) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_MAINMENU) { game.playSound(snd_level_start); game_state = GS_PLAY; game_over = false; initGame(); initLevel(1); } else if (game_state == GS_PLAY && !paused) { if (smrocks > 0) { game.playSound(snd_shoot_bubble); smrocks--; Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -360; item.type = ITEM_SMROCKS; item.bonus = null; item.bm = bm_smrock; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; PartString partstring = new PartString(this, item.x, item.y, "" + smrocks, 0.6); partstring.vx = 0; partstring.vy = -30; addPart(partstring); } else if (torpedo) { torpedoBoolean = false; game.playSound(snd_shoot_bubble); Item item = new Item(); item.x = game.getMouseX(); item.y = item.py = bob_y; item.vel_y = -120; item.type = ITEM_TORPEDO; item.bonus = null; item.bm = bm_torpedo; if (items == null) { items = item; } else { item.next = items.next; items.next = item; } shoot_time = 0.5; } else if (shot_bubble.bm != null) { return; } else if (shoot_time < 0.8) { return; } else { game.playSound(snd_shoot_bubble); shot_bubble.bm = next_bubble; next_bubble = next_bubble2; next_bubble2 = getRandomBubble(false); shot_bubble.x = game.getMouseX(); shot_bubble.y = bob_y - 10; shoot_time = 0; } } } if (game.rightClick()) { game.playSound(snd_swap); Sprite next = next_bubble; next_bubble = next_bubble2; next_bubble2 = next; shoot_time = 0.5; } } void addPart (Part part) { if (parts == null) { parts = part; } else { part.next = parts; parts = part; } } Point2D.Double getPathPoint (double idx) { if (idx < 0) { return new Point2D.Double(-30, -400); } double idx_dist = idx * 2 * RAD_BUBBLE; double curr_dist = 0; for (int i = 0; i < num_path_points; i++) { double next_dist = curr_dist + path[i].dist_to_next; if (idx_dist < next_dist) { double curr_idx = (idx_dist - curr_dist) / path[i].dist_to_next; return new Point2D.Double(path[i].x + (path[i + 1].x - path[i].x) * curr_idx, path[i].y + (path[i + 1].y - path[i].y) * curr_idx); } curr_dist = next_dist; } return new Point2D.Double(path[num_path_points - 1].x, path[num_path_points - 1].y); } boolean existsInPath (Sprite bub) { for (Bubble bubble = first_bub; bubble != null; bubble = bubble.next) { if (bubble.bm == bub) { return true; } } return false; } Bubble getLastBubble () { if (first_bub == null) return null; Bubble bubble; for (bubble = first_bub; bubble.next != null; bubble = bubble.next) ; return bubble; } boolean adjIsGoingToBurst (Bubble bubble) { Sprite s = bubble.bm; int i = 1; for (Bubble b = bubble.prev; b != null && b.bm == s; b = b.prev) i++; for (Bubble b = bubble.next; b != null && b.bm == s; b = b.next) i++; return i >= 3; } void spawnBiggerBurst (double x, double y) { for (int i = 0; i < 30; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(140, 310); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 3.8)); partbub.life += randDouble(0, 0.4); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle); partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } void spawnBurst (double x, double y) { y += 5; for (int i = 0; i < 26; i++) { double angle = randDouble(0, PI_2); double magnitude = randDouble(50, 100); PartBub partbub = new PartBub(this, x, y, bm_part_bub[0], randDouble(3, 4.2)); partbub.life += randDouble(0, 0.2); partbub.vx = magnitude * Math.cos(angle); partbub.vy = magnitude * Math.sin(angle) - magnitude; partbub.x += partbub.vx / 80; partbub.y += partbub.vy / 80; addPart(partbub); } } Sprite getRandomBubble (boolean totally_random) { int max = 3 + (episode + 1) / 2; if (totally_random) { return bm_bubbles[randInt(max)]; } for (int j = 0; j < 300; j++) { Sprite bub = bm_bubbles[randInt(max)]; if (existsInPath(bub)) { return bub; } } System.out.println("stalled."); return bm_bubbles[randInt(max)]; } AbstractBonus getRandomBonus () { int i = randInt(num_bonuses); AbstractBonus bonus = bonuses; for (bonus = bonuses; i != 0; bonus = bonus.next, i--) ; return bonus; } int randInt (int max) { return (int)(Math.random() * max); } double randDouble (double min, double max) { return min + Math.random() * (max - min); } String scoreString () { StringBuffer stringbuffer = new StringBuffer(score_show); for (int i = stringbuffer.length() - 1 - 2; i > 0; i -= 3) { stringbuffer.insert(i, "0"); } return stringbuffer.toString(); } }
Java
package game; import java.lang.Double; import java.awt.geom.Point2D; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; import java.util.Scanner; /** * * @author Shun Fan * parses level from text files */ public class TxtParser{ private File myFile; private double path_speed; private int path_x_offset; private int path_y_offset; private int fishToSaveAtStartOfLevel; private int path_start_t; private int num_path_points; private PathPoint[] path; private String pathPointsString; private ArrayList<Point2D.Double> pathPoints = new ArrayList<Point2D.Double>(); public TxtParser() { } public TxtParser(File sourceFile) { pathPoints = new ArrayList<Point2D.Double>(); myFile = (File) sourceFile; try { Scanner textScanner = new Scanner(myFile).useDelimiter("(\\s*=\\s*)|(;\\s*)"); parseVariables(textScanner); createPathPointsArray(pathPointsString); } catch (FileNotFoundException e) { System.out.println("text parser could not find file"); //e.printStackTrace(); } } private void parseVariables(Scanner textScanner) { textScanner.next(); fishToSaveAtStartOfLevel = Integer.parseInt(textScanner.next()); textScanner.next(); path_speed = Double.parseDouble(textScanner.next()); textScanner.next(); path_x_offset = Integer.parseInt(textScanner.next()); textScanner.next(); path_y_offset = Integer.parseInt(textScanner.next()); textScanner.next(); path_start_t = Integer.parseInt(textScanner.next()); textScanner.next(); num_path_points = Integer.parseInt(textScanner.next()); textScanner.next(); pathPointsString = textScanner.next(); } private void createPathPointsArray(String pathPointsString) { Scanner pointsScanner = new Scanner(pathPointsString).useDelimiter("(\\s*,\\s*)|(\\s+)"); while(pointsScanner.hasNext()) { double parsedXvalue = new Double(pointsScanner.next()); double parsedYvalue = new Double(pointsScanner.next()); Point2D.Double newPoint = new Point2D.Double(parsedXvalue, parsedYvalue); //System.out.println("pointx: " + parsedXvalue + ", pointy: " + parsedYvalue); pathPoints.add(newPoint); } //System.out.println("pathpoints size: " + pathPoints.size()); } public double getBubblePathSpeed() { return path_speed; } public int getFishLeftToSave() { return fishToSaveAtStartOfLevel; } public int getBubblePathStartPos() { return path_start_t; } public int getNumberOfBubblePathPoints() { return num_path_points; } public ArrayList<Point2D.Double> getBubblePathPoints(){ return pathPoints; } public int getPathXOffset() { return path_x_offset; } public int getPathYOffset() { return path_y_offset; } }
Java
package de.fmaul.android.cmis; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import de.fmaul.android.cmis.asynctask.CopyFilesTask; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FileSystemUtils; import de.fmaul.android.cmis.utils.StorageException; import de.fmaul.android.cmis.utils.StorageUtils; public class FileChooserActivity extends ListActivity { private static final int EDIT_ACTION = 0; private final String TAG = "File Chooser"; protected ArrayList<File> mFileList; protected File mRoot; protected File parent; private File file; private ListView listView; private EditText input; private Boolean multipleMode = false; private static final int MENU_NEW_FOLDER = Menu.FIRST + 1; private static final int DIALOG_NEW_FOLDER = 1; private static final int DIALOG_DELETE = 2; private static final int DIALOG_RENAME = 3; private static final int DIALOG_ABOUT = 4; private static final int DIALOG_ORDER = 5; private static final String SDCARD = "sdcard"; private int sort = SORT_ALPHA; private ArrayList<String> sortingValueLabel = new ArrayList<String>(3); private ArrayList<Integer> sorting = new ArrayList<Integer>(3); private static final int SORT_ALPHA = R.string.action_sorting_name; private static final int SORT_SIZE = R.string.action_sorting_size; private static final int SORT_DATE = R.string.action_sorting_date; private ArrayList<File> copiedFiles = new ArrayList<File>(); private ArrayList<File> cutFiles = new ArrayList<File>(); private ArrayList<File> selectionFiles = new ArrayList<File>(); private Button home; private Button up; private Button filter; private Button paste; private Button clear; private Button order; private Button copy; private Button cut; private Button delete; private Button cancel; private Button multiple; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.file_list_main); //Filter Init initSorting(); initSortingLabel(); listView = this.getListView(); listView.setOnCreateContextMenuListener(this); try { file = StorageUtils.getDownloadRoot(this.getApplication()); } catch (StorageException e) { } setTitle(getString(R.string.app_name)); initActionIcon(); if (getLastNonConfigurationInstance() != null ){ file = (File) getLastNonConfigurationInstance(); } parent = new File(file.getParent()); initialize("Download", file); } private AlertDialog createDialog(int title, int message, String defaultValue, DialogInterface.OnClickListener positiveClickListener){ final AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(title); alert.setMessage(message); input = new EditText(this); input.setText(defaultValue); alert.setView(input); alert.setPositiveButton(R.string.validate, positiveClickListener); alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); return alert.create(); } private void initActionIcon() { home = (Button) findViewById(R.id.home); up = (Button) findViewById(R.id.up); filter = (Button) findViewById(R.id.preference); order = (Button) findViewById(R.id.order); paste = (Button) findViewById(R.id.paste); clear = (Button) findViewById(R.id.clear); copy = (Button) findViewById(R.id.copy); cut = (Button) findViewById(R.id.cut); delete = (Button) findViewById(R.id.delete); cancel = (Button) findViewById(R.id.cancel); multiple = (Button) findViewById(R.id.multiple); multiple.setVisibility(View.GONE); filter.setVisibility(View.GONE); paste.setVisibility(View.GONE); clear.setVisibility(View.GONE); copy.setVisibility(View.GONE); cut.setVisibility(View.GONE); delete.setVisibility(View.GONE); cancel.setVisibility(View.GONE); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); Intent intent = new Intent(FileChooserActivity.this, HomeActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); order.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(DIALOG_ORDER); } }); up.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { goUp(false); } }); paste.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { for (File fileToMove : cutFiles) { FileSystemUtils.rename(mRoot, fileToMove); } new CopyFilesTask(FileChooserActivity.this, copiedFiles, cutFiles, mRoot).execute(); } }); clear.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { copiedFiles.clear(); cutFiles.clear(); paste.setVisibility(View.GONE); clear.setVisibility(View.GONE); ActionUtils.displayMessage(FileChooserActivity.this, R.string.action_clear_success); } }); copy.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { copy.setVisibility(View.GONE); cut.setVisibility(View.GONE); paste.setVisibility(View.GONE); clear.setVisibility(View.GONE); delete.setVisibility(View.GONE); multipleMode = false; copiedFiles.addAll(selectionFiles); selectionFiles.clear(); } }); cut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { copy.setVisibility(View.GONE); cut.setVisibility(View.GONE); paste.setVisibility(View.GONE); clear.setVisibility(View.GONE); delete.setVisibility(View.GONE); multipleMode = false; cutFiles.addAll(selectionFiles); selectionFiles.clear(); } }); delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { copy.setVisibility(View.GONE); cut.setVisibility(View.GONE); paste.setVisibility(View.GONE); clear.setVisibility(View.GONE); delete.setVisibility(View.GONE); multipleMode = false; for (File file : selectionFiles) { FileSystemUtils.delete(file); } } }); multiple.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (multipleMode){ copy.setVisibility(View.GONE); cut.setVisibility(View.GONE); paste.setVisibility(View.GONE); delete.setVisibility(View.GONE); multipleMode = false; initialize(mRoot.getName(), mRoot); } else { copy.setVisibility(View.VISIBLE); cut.setVisibility(View.VISIBLE); paste.setVisibility(View.VISIBLE); clear.setVisibility(View.GONE); delete.setVisibility(View.VISIBLE); multipleMode = true; } } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //goUp(true); this.finish(); return true; } return super.onKeyDown(keyCode, event); } @Override public Object onRetainNonConfigurationInstance() { return file; } public void initialize(String title, File file) { ((TextView) this.findViewById(R.id.path)).setText(file.getPath()); mFileList = new ArrayList<File>(); if (getDirectory(file)) { getFiles(mRoot); displayFiles(); } } private boolean getDirectory(File file) { TextView tv = (TextView) findViewById(R.id.filelister_message); // check to see if there's an sd card. String cardstatus = Environment.getExternalStorageState(); if (cardstatus.equals(Environment.MEDIA_REMOVED) || cardstatus.equals(Environment.MEDIA_UNMOUNTABLE) || cardstatus.equals(Environment.MEDIA_UNMOUNTED) || cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { tv.setText("Error"); return false; } mRoot = file; if (!mRoot.exists()) { return false; } return true; } private void getFiles(File f) { mFileList.clear(); //mFileList.add(parent); if (f.isDirectory()) { File[] childs = f.listFiles(); for (File child : childs) { mFileList.add(child); } } } private void displayFiles() { ArrayAdapter<File> fileAdapter; switch (sort) { case SORT_ALPHA: Collections.sort(mFileList, new DirAlphaComparator()); break; case SORT_DATE: Collections.sort(mFileList, new DirDateComparator()); break; case SORT_SIZE: Collections.sort(mFileList, new DirSizeComparator()); break; default: break; } getListView().setItemsCanFocus(false); getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); fileAdapter = new FileAdapter(this, R.layout.file_list_row, mFileList, parent); setListAdapter(fileAdapter); } /** * Stores the path of clicked file in the intent and exits. */ @Override protected void onListItemClick(ListView l, View v, int position, long id) { file = (File) l.getItemAtPosition(position); if (SDCARD.equals(file.getName())){ up.setVisibility(View.GONE); } else { up.setVisibility(View.VISIBLE); } int c; if (multipleMode){ if (selectionFiles.contains(file)){ selectionFiles.remove(file); c = Color.BLUE; } else { selectionFiles.add(file); c = Color.DKGRAY; } v.setBackgroundColor(c); l.getChildAt(position).refreshDrawableState(); } else { if (file != null){ if (file.isDirectory()) { setListAdapter(null); if (file.getParent() != null){ parent = new File(file.getParent()); } else { parent = null; } initialize(file.getName(), file); } else { ActionUtils.openDocument(this, file); } } } } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(this.getString(R.string.feed_menu_title)); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; File file = (File) getListView().getItemAtPosition(info.position); if (file.isFile()){ menu.add(0, 0, Menu.NONE, getString(R.string.share)); menu.add(0, 1, Menu.NONE, getString(R.string.open)); menu.add(0, 2, Menu.NONE, getString(R.string.open_with)); menu.add(0, 5, Menu.NONE, getString(R.string.copy)); menu.add(0, 6, Menu.NONE, getString(R.string.cut)); } else { menu.add(0, 6, Menu.NONE, getString(R.string.move)); } menu.add(0, 3, Menu.NONE, getString(R.string.rename)); menu.add(0, 4, Menu.NONE, getString(R.string.delete)); } @Override public boolean onContextItemSelected(MenuItem menuItem) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo(); } catch (ClassCastException e) { return false; } file = (File) getListView().getItemAtPosition(menuInfo.position); switch (menuItem.getItemId()) { case 0: ActionUtils.shareFileInAssociatedApp(this, file); return true; case 1: ActionUtils.openDocument(this, file); return true; case 2: ActionUtils.openWithDocument(this, file); return true; case 3: showDialog(DIALOG_RENAME); return true; case 4: showDialog(DIALOG_DELETE); return true; case 5: copiedFiles.add(file); ActionUtils.displayMessage(this, R.string.action_clipboard_add); this.findViewById(R.id.paste).setVisibility(View.VISIBLE); this.findViewById(R.id.clear).setVisibility(View.VISIBLE); return true; case 6: cutFiles.add(file); ActionUtils.displayMessage(this, R.string.action_clipboard_add); this.findViewById(R.id.paste).setVisibility(View.VISIBLE); this.findViewById(R.id.clear).setVisibility(View.VISIBLE); return true; default: return super.onContextItemSelected(menuItem); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case EDIT_ACTION: try { String value = data.getStringExtra("value"); if (value != null && value.length() > 0) { //do something with value } } catch (Exception e) { } break; default: break; } } private void goUp(Boolean exit){ if (SDCARD.equals(parent.getName())){ up.setVisibility(View.GONE); } if (file.getParent() != null && SDCARD.equals(file.getName()) == false){ file = new File(file.getParent()); if (file.getParent() != null){ parent = new File(file.getParent()); } initialize(file.getName(), file); } else if (exit) { Intent intent = new Intent(FileChooserActivity.this, HomeActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_NEW_FOLDER: DialogInterface.OnClickListener createFolder = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { FileSystemUtils.createNewFolder(mRoot, input.getText().toString().trim()); initialize(mRoot.getName(), mRoot); } }; return createDialog(R.string.create_folder, R.string.action_create_folder_des, "", createFolder); case DIALOG_DELETE: return new AlertDialog.Builder(this).setTitle(R.string.delete) .setMessage(FileChooserActivity.this.getText(R.string.action_delete_desc) + " " + file.getName() + " ? ").setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { FileSystemUtils.delete(file); initialize(mRoot.getName(), mRoot); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); case DIALOG_RENAME: DialogInterface.OnClickListener rename = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { FileSystemUtils.rename(file, input.getText().toString().trim()); initialize(mRoot.getName(), mRoot); } }; return createDialog(R.string.rename, R.string.action_rename_desc, file.getName(), rename); case DIALOG_ORDER: return new AlertDialog.Builder(this).setTitle(R.string.action_sorting_title) .setSingleChoiceItems(getFiltersLabel(), sorting.indexOf(sort), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); sort = sorting.get(which); initialize(mRoot.getName(), mRoot); } }) .setNegativeButton(this.getText(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); default: return null; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_NEW_FOLDER, 0, R.string.create_folder).setIcon( android.R.drawable.ic_menu_add).setShortcut('0', 'f'); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //Intent intent; switch (item.getItemId()) { case MENU_NEW_FOLDER: showDialog(DIALOG_NEW_FOLDER); return true; } return super.onOptionsItemSelected(item); } class DirAlphaComparator implements Comparator<File> { public int compare(File filea, File fileb) { if (filea.isDirectory() && !fileb.isDirectory()) { return -1; } else if (!filea.isDirectory() && fileb.isDirectory()) { return 1; } else { return filea.getName().compareToIgnoreCase(fileb.getName()); } } } class DirSizeComparator implements Comparator<File> { public int compare(File filea, File fileb) { if (filea.isDirectory() && !fileb.isDirectory()) { return -1; } else if (!filea.isDirectory() && fileb.isDirectory()) { return 1; } else { if (filea.length() > fileb.length()){ return 1; } else if (filea.length() < fileb.length()){ return -1; } else { return 0; } } } } class DirDateComparator implements Comparator<File> { public int compare(File filea, File fileb) { if (filea.lastModified() > fileb.lastModified()){ return 1; } else if (filea.lastModified() < fileb.lastModified()){ return -1; } else { return 0; } } } private void initSortingLabel() { sortingValueLabel.add(this.getText(R.string.action_sorting_name).toString()); sortingValueLabel.add(this.getText(R.string.action_sorting_size).toString()); sortingValueLabel.add(this.getText(R.string.action_sorting_date).toString()); } private void initSorting() { sorting.add(R.string.action_sorting_name); sorting.add(R.string.action_sorting_size); sorting.add(R.string.action_sorting_date); } private CharSequence[] getFiltersLabel() { return sortingValueLabel.toArray(new CharSequence[sorting.size()]); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.model.Favorite; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.utils.MimetypeUtils; public class FavoriteAdapter extends ArrayAdapter<Favorite> { static private class ViewHolder { TextView topText; TextView bottomText; ImageView icon; } private Context context; public FavoriteAdapter(Context context, int textViewResourceId, ArrayList<Favorite> favorites) { super(context, textViewResourceId,favorites); this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = recycleOrCreateView(convertView); ViewHolder vh = (ViewHolder) v.getTag(); Favorite item = getItem(position); updateControls(vh, item); return v; } private View recycleOrCreateView(View v) { if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.feed_list_row, null); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView) v.findViewById(R.id.icon); vh.topText = (TextView) v.findViewById(R.id.toptext); vh.bottomText = (TextView) v.findViewById(R.id.bottomtext); v.setTag(vh); } return v; } private void updateControls(ViewHolder v, Favorite item) { if (item != null) { v.topText.setText(item.getName()); v.bottomText.setText(item.getUrl()); updateControlIcon(v, item); } } private void updateControlIcon(ViewHolder vh, Favorite item) { vh.icon.setImageDrawable(getContext().getResources().getDrawable(MimetypeUtils.getIcon((Activity)context, item.getMimetype()))); } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import org.apache.http.client.ClientProtocolException; import org.dom4j.Document; import org.dom4j.Element; import android.app.Activity; import android.app.Application; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import de.fmaul.android.cmis.FilterPrefs; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.SearchPrefs; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.FeedUtils; import de.fmaul.android.cmis.utils.HttpUtils; import de.fmaul.android.cmis.utils.StorageException; import de.fmaul.android.cmis.utils.StorageUtils; /** * @author Florian Maul */ public class CmisRepository { private static final String TAG = "CmisRepository"; private final String feedRootCollection; private final String feedTypesCollection; private final String uriTemplateQuery; private final String uriTemplateTypeById; private final String repositoryUser; private final String repositoryPassword; private final String repositoryWorkspace; private String feedParams; private Boolean useFeedParams; private final Application application; private final String repositoryName; private String repositoryUrl; private final Server server; private int skipCount = 0; private int maxItems = 0; private Boolean paging; private int numItems; private CmisItem rootItem; /** * Connects to a CMIS Repository with the given connection information FIXME * References to Application should be removed with DI * * @param repositoryUrl * The base ATOM feed URL of the CMIS repository * @param user * The user name to login to the repository * @param password * The password to login to the repository */ private CmisRepository(Application application, Server server) { this.application = application; this.repositoryUser = server.getUsername(); this.repositoryPassword = server.getPassword(); this.repositoryWorkspace = server.getWorkspace(); this.repositoryName = server.getName(); this.repositoryUrl = server.getUrl(); this.server = server; Document doc = FeedUtils.readAtomFeed(repositoryUrl, repositoryUser, repositoryPassword); Element wsElement = FeedUtils.getWorkspace(doc, repositoryWorkspace); feedRootCollection = FeedUtils.getCollectionUrlFromRepoFeed("root", wsElement); feedTypesCollection = FeedUtils.getCollectionUrlFromRepoFeed("types", wsElement); uriTemplateQuery = FeedUtils.getUriTemplateFromRepoFeed("query", wsElement); uriTemplateTypeById = FeedUtils.getUriTemplateFromRepoFeed("typebyid", wsElement); } public String getFeedRootCollection() { return feedRootCollection; } public void setFeedParams(String feedParams) { this.feedParams = feedParams; } public String getHostname() { return repositoryUrl.split("/")[2]; } public String getRepositoryUrl() { return repositoryUrl; } /** * Creates a repository connection from the application preferences. * * @param prefs * @return */ public static CmisRepository create(Application app, final Server server) { return new CmisRepository(app, server); } /** * Returns the root collection with documents and folders. * * @return * @throws Exception * @throws FeedLoadException */ public CmisItemCollection getRootCollection() throws FeedLoadException, Exception { return getCollectionFromFeed(feedRootCollection); } public CmisItemCollection getRootCollection(String params) throws FeedLoadException, StorageException { return getCollectionFromFeed(feedRootCollection + params); } /** * Returns the ATOM feed that can be used to perform a search for the * specified search terms. * * @param queryType * A {@link QueryType} that specifies the type of search. * @param query * A query that will be run against the repository. * @return */ public String getSearchFeed(Activity activity, QueryType queryType, String query) { SearchPrefs pref = new SearchPrefs(activity); switch (queryType) { case TITLE: return FeedUtils.getSearchQueryFeedTitle(uriTemplateQuery, query, pref.getExactSearch()); case FOLDER: return FeedUtils.getSearchQueryFeedFolderTitle(uriTemplateQuery, query, pref.getExactSearch()); case CMISQUERY: return FeedUtils.getSearchQueryFeedCmisQuery(uriTemplateQuery, query); case FULLTEXT: return FeedUtils.getSearchQueryFeedFullText(uriTemplateQuery, query); default: return FeedUtils.getSearchQueryFeed(uriTemplateQuery, query); } } /** * Returns the collection of {@link CmisItem}s for a given feed url from the * CMIS repository. * * @param feedUrl * @return * @throws Exception * @throws FeedLoadException */ public CmisItemCollection getCollectionFromFeed(final String feedUrl) throws FeedLoadException, StorageException { Document doc; Log.d(TAG, "feedUrl : " + feedUrl); if (StorageUtils.isFeedInCache(application, feedUrl, repositoryWorkspace)) { doc = StorageUtils.getFeedFromCache(application, feedUrl, repositoryWorkspace); } else { doc = FeedUtils.readAtomFeed(feedUrl, repositoryUser, repositoryPassword); if (doc != null) { StorageUtils.storeFeedInCache(application, feedUrl, doc, repositoryWorkspace); } } numItems = FeedUtils.getNumItemsFeed(doc); rootItem = CmisItem.createFromFeed(doc.getRootElement()); Log.d(TAG, "NumItems : " + numItems); return CmisItemCollection.createFromFeed(doc); } public CmisTypeDefinition getTypeDefinition(String documentTypeId) { String url = uriTemplateTypeById.replace("{id}", documentTypeId); Document doc = FeedUtils.readAtomFeed(url, repositoryUser, repositoryPassword); return CmisTypeDefinition.createFromFeed(doc); } /** * Fetches the contents from the CMIS repository for the given * {@link CmisItem}. */ private void downloadContent(CmisItemLazy item, OutputStream os) throws ClientProtocolException, IOException { HttpUtils.getWebRessource(item.getContentUrl(), repositoryUser, repositoryPassword).getEntity().writeTo(os); } public void clearCache(String workspace) throws StorageException { StorageUtils.deleteRepositoryFiles(application, workspace); } public void generateParams(Activity activity){ FilterPrefs pref = new FilterPrefs(activity); if (pref.getParams()){ setUseFeedParams(true); if (pref.getPaging()){ setPaging(true); } else { setPaging(false); } setFeedParams(createParams(pref)); } else { setUseFeedParams(false); } } public void generateParams(Activity activity, Boolean isAdd){ FilterPrefs pref = new FilterPrefs(activity); if (pref.getParams()){ setUseFeedParams(true); if (pref.getPaging()){ setPaging(true); } else { setPaging(false); } setFeedParams(createParams(pref, isAdd, false)); } else { setPaging(false); setUseFeedParams(false); } } private String createParams(FilterPrefs pref, Boolean isAdd, Boolean isFirst){ String params = ""; String value = ""; ArrayList<String> listParams = new ArrayList<String>(4); if (pref != null && pref.getParams()){ value = pref.getTypes(); if (value != null && value.length() > 0){ listParams.add("types" + "=" + pref.getTypes()); } /* if (pref.getFilter() != null){ paramsList.put("filter", pref.getFilter()); }*/ if (pref.getPaging()){ if (isFirst){ listParams.add("skipCount" + "=0"); setSkipCount(0); } else { value = pref.getMaxItems(); if (value != null) { if (value.length() == 0 ){ value = "0"; setMaxItems(Integer.parseInt(value)); } int skipCountValue = 0; if (isAdd){ skipCountValue = getSkipCount() + getMaxItems() ; } else { skipCountValue = getSkipCount() - getMaxItems(); } if (skipCountValue < 0){ skipCountValue = 0; } listParams.add("skipCount" + "=" + skipCountValue); setSkipCount(skipCountValue); } } } value = pref.getMaxItems(); if (value != null && value.length() > 0 && Integer.parseInt(value) > 0){ listParams.add("maxItems" + "=" + pref.getMaxItems()); setMaxItems(Integer.parseInt(value)); } value = pref.getOrder() ; if (pref.getOrder() != null && pref.getOrder().length() > 0){ listParams.add("orderBy" + "=" + pref.getOrder()); } params = "?" + TextUtils.join("&", listParams); } try { params = new URI(null, params, null).toASCIIString(); } catch (URISyntaxException e) { } Log.d(TAG, "Params : " + params); return params; } private String createParams(FilterPrefs pref){ return createParams(pref, true, true); } public String getFeedParams() { return feedParams; } public Boolean getUseFeedParams() { if (useFeedParams != null){ return useFeedParams; } else { return false; } } public void setUseFeedParams(Boolean useFeedParams) { this.useFeedParams = useFeedParams; } public Server getServer() { return server; } public void setSkipCount(int skipCount) { Log.d(TAG, "skipCount :" + skipCount); this.skipCount = skipCount; } public int getSkipCount() { return skipCount; } public void setPaging(Boolean paging) { Log.d(TAG, "Paging :" + paging); this.paging = paging; } public Boolean isPaging() { if (paging == null){ paging = false; } return paging; } public void setNumItems(int numItems) { this.numItems = numItems; } public int getNumItems() { return numItems; } public void setMaxItems(int maxItems) { Log.d(TAG, "MaxItems :" + maxItems); this.maxItems = maxItems; } public int getMaxItems() { return maxItems; } public CmisItem getRootItem() { return rootItem; } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import android.os.Parcel; import android.os.Parcelable; public class CmisProperty implements Parcelable { public static final String OBJECT_ID = "cmis:objectId"; public static final String OBJECT_TYPEID = "cmis:objectTypeId"; public static final String OBJECT_BASETYPEID = "cmis:baseTypeId"; public static final String OBJECT_NAME = "cmis:name"; public static final String OBJECT_CREATIONDATE = "cmis:creationDate"; public static final String OBJECT_LASTMODIFIEDBY = "cmis:lastModifiedBy"; public static final String OBJECT_CREATEDBY = "cmis:createdBy"; public static final String OBJECT_LASTMODIFICATION = "cmis:lastModificationDate"; public static final String OBJECT_CHANGETOKEN = "cmis:changeToken"; public static final String DOC_ISLATESTEVERSION= "cmis:isLatestVersion"; public static final String DOC_ISLATESTMAJORVERSION = "cmis:isLatestMajorVersion"; public static final String DOC_VERSIONSERIESID = "cmis:versionSeriesId"; public static final String DOC_VERSIONLABEL = "cmis:versionLabel"; public static final String DOC_ISMAJORVERSION = "cmis:isMajorVersion"; public static final String DOC_ISVERSIONCHECKEDOUT = "cmis:isVersionSeriesCheckedOut"; public static final String DOC_ISVERSIONCHECKEDOUTBY = "cmis:versionSeriesCheckedOutBy"; public static final String DOC_ISVERSIONCHECKEDOUTID = "cmis:versionSeriesCheckedOutId"; public static final String DOC_ISIMMUTABLE = "cmis:isImmutable"; public static final String DOC_CHECINCOMMENT = "cmis:checkinComment"; public static final String CONTENT_STREAMID = "cmis:contentStreamId"; public static final String CONTENT_STREAMLENGTH = "cmis:contentStreamLength"; public static final String CONTENT_STREAMMIMETYPE = "cmis:contentStreamMimeType"; public static final String CONTENT_STREAMFILENAME = "cmis:contentStreamFileName"; public static final String FOLDER_PARENTID = "cmis:parentId"; public static final String FOLDER_PATH = "cmis:path"; public static final String FOLDER_ALLOWCHILDREN = "cmis:allowedChildObjectTypeIds"; private final String type; private final String definitionId; private final String localName; private final String displayName; private final String value; public CmisProperty(String type, String definitionId, String localName, String displayName, String value) { this.type = type; this.definitionId = definitionId; this.localName = localName; this.displayName = displayName; this.value = value; } public CmisProperty(Parcel in) { type = in.readString(); definitionId = in.readString(); localName = in.readString(); displayName = in.readString(); value = in.readString(); } public String getDefinitionId() { return definitionId; } public String getDisplayName() { return displayName; } public String getLocalName() { return localName; } public String getType() { return type; } public String getValue() { return value; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(type); dest.writeString(definitionId); dest.writeString(localName); dest.writeString(displayName); dest.writeString(value); } public static final Parcelable.Creator<CmisProperty> CREATOR = new Parcelable.Creator<CmisProperty>() { public CmisProperty createFromParcel(Parcel in) { return new CmisProperty(in); } public CmisProperty[] newArray(int size) { return new CmisProperty[size]; } }; }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import org.dom4j.Element; import de.fmaul.android.cmis.utils.FeedUtils; public class CmisItem extends CmisItemLazy { public CmisItem(CmisItem item) { super(item); } private CmisItem() { } /** * */ private static final long serialVersionUID = 1L; private Map<String, CmisProperty> properties; public Map<String, CmisProperty> getProperties() { return properties; } public static CmisItem createFromFeed(Element entry) { CmisItem cmi = new CmisItem(); cmi.parseEntry(entry); return cmi; } private void parseEntry(Element entry) { title = entry.element("title").getText(); id = entry.element("id").getText(); downLink = ""; contentUrl = ""; mimeType = ""; author = getAuthorName(entry); modificationDate = getModificationDate(entry); Element contentElement = entry.element("content"); if (contentElement != null) { contentUrl = contentElement.attributeValue("src"); mimeType = contentElement.attributeValue("type"); if (mimeType == null){ mimeType = ""; } } for (Element link : (List<Element>) entry.elements("link")) { if (CmisModel.ITEM_LINK_DOWN.equals(link.attribute("rel").getText())) { if (link.attribute("type").getText().startsWith("application/atom+xml")) { downLink = link.attribute("href").getText(); } } else if (CmisModel.ITEM_LINK_SELF.equals(link.attribute("rel").getText())) { selfUrl = link.attribute("href").getText(); } else if (CmisModel.ITEM_LINK_UP.equals(link.attribute("rel").getText())) { parentUrl = link.attribute("href").getText(); } } properties = FeedUtils.getCmisPropertiesForEntry(entry); if (properties.get(CmisProperty.CONTENT_STREAMLENGTH) != null){ size = properties.get(CmisProperty.CONTENT_STREAMLENGTH).getValue(); } else { size = null; } if (properties.get(CmisProperty.FOLDER_PATH) != null){ path = properties.get(CmisProperty.FOLDER_PATH).getValue(); } if (properties.get(CmisProperty.OBJECT_BASETYPEID) != null){ baseType = properties.get(CmisProperty.OBJECT_BASETYPEID).getValue(); } } private Date getModificationDate(Element entry) { Element updated = entry.element("updated"); if (updated != null) { return parseXmlDate(updated.getText()); } else return null; } private String getAuthorName(Element entry) { Element author = entry.element("author"); if (author != null) { Element name = author.element("name"); if (name != null) { return name.getText(); } } return ""; } private Date parseXmlDate(String date) { // 2009-11-03T11:55:39.495Z Date modfiedDate = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'"); try { modfiedDate = df.parse(date); } catch (ParseException e) { // meh } return modfiedDate; } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import android.app.Activity; import android.os.AsyncTask.Status; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.asynctask.AbstractDownloadTask; public class DownloadItem { private CmisItemLazy item; private AbstractDownloadTask task; public DownloadItem(CmisItemLazy item, AbstractDownloadTask task) { super(); this.item = item; this.task = task; } public CmisItemLazy getItem() { return item; } public void setItem(CmisItem item) { this.item = item; } public AbstractDownloadTask getTask() { return task; } public void setTask(AbstractDownloadTask task) { this.task = task; } public String getStatut(Activity activity) { String statutValue = " "; Status statuts = getTask().getStatus(); if (Status.RUNNING.equals(statuts) && AbstractDownloadTask.CANCELLED != getTask().getState()){ statutValue += getTask().getPercent() + " % " + activity.getText(R.string.download_progress).toString(); } else if (Status.RUNNING.equals(statuts) && AbstractDownloadTask.CANCELLED == getTask().getState()){ statutValue += activity.getText(R.string.cancel_progress).toString(); } else if (Status.FINISHED.equals(statuts) && AbstractDownloadTask.COMPLETE == getTask().getState()){ statutValue += activity.getText(R.string.notif_download_finish).toString(); } else { statutValue += activity.getText(R.string.cancel_complete).toString(); } return statutValue; } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; public enum QueryType { FULLTEXT, TITLE, CMISQUERY, FOLDER, SAVEDSEARCH }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import java.io.File; import java.io.Serializable; import java.util.Date; import android.app.Application; import de.fmaul.android.cmis.utils.StorageException; import de.fmaul.android.cmis.utils.StorageUtils; public class CmisItemLazy implements Serializable { private static final long serialVersionUID = -8274543604325636130L; protected String title; protected String downLink; protected String author; protected String contentUrl; protected String selfUrl; protected String parentUrl; protected String id; protected String mimeType; protected String size; protected String path; protected String baseType; protected Date modificationDate; public CmisItemLazy(){ } public CmisItemLazy(CmisItem item) { super(); this.title = item.getTitle(); this.downLink = item.getDownLink(); this.parentUrl = item.getParentUrl(); this.author = item.getAuthor(); this.contentUrl = item.getContentUrl(); this.selfUrl = item.getSelfUrl(); this.id = item.getId(); this.mimeType = item.getMimeType(); this.size = item.getSize(); this.modificationDate = item.getModificationDate(); this.path = item.getPath(); this.baseType = item.getBaseType(); } public String getTitle() { return title; } @Override public String toString() { return getTitle(); } public String getSelfUrl() { return selfUrl; } public String getAuthor() { return author; } public boolean hasChildren() { return downLink != null && downLink.length() > 0; } public String getDownLink() { return downLink; } public String getContentUrl() { return contentUrl; } public String getId() { return id; } public String getMimeType() { return mimeType; } public Date getModificationDate() { return modificationDate; } public String getSize() { return size; } public String getPath() { return path; } public String getParentUrl() { return parentUrl; } public String getBaseType() { return baseType; } public File getContent(Application application, String repositoryWorkspace) throws StorageException { return StorageUtils.getStorageFile(application, repositoryWorkspace, StorageUtils.TYPE_CONTENT, getId(), getTitle()); } public File getContentDownload(Application application, String saveFolder) throws StorageException { return StorageUtils.getStorageFile(application, saveFolder, getTitle()); } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; public class CmisTypeDefinition { private String id; private String localName; private String localNamespace; private String displayName; private String queryName; private String description; private String baseId; private boolean creatable; private boolean fileable; private boolean queryable; private boolean fulltextIndexed; private boolean includedInSupertypeQuery; private boolean controllablePolicy; private boolean controllableACL; private boolean versionable; private String contentStreamAllowed; Map<String, CmisPropertyTypeDefinition> propertyDefinition = new HashMap<String, CmisPropertyTypeDefinition>(); public static CmisTypeDefinition createFromFeed(Document doc) { CmisTypeDefinition td = new CmisTypeDefinition(); final Namespace CMISRA = Namespace.get("http://docs.oasis-open.org/ns/cmis/restatom/200908/"); final QName CMISRA_TYPE = QName.get("type", CMISRA); Element type = doc.getRootElement().element(CMISRA_TYPE); td.id = type.elementTextTrim("id"); td.localName = type.elementTextTrim("localName"); td.localNamespace = type.elementTextTrim("localNamespace"); td.displayName = type.elementTextTrim("displayName"); td.queryName = type.elementTextTrim("queryName"); td.description = type.elementTextTrim("description"); td.baseId = type.elementTextTrim("baseId"); td.creatable = Boolean.valueOf(type.elementTextTrim("creatable")); td.fileable = Boolean.valueOf(type.elementTextTrim("fileable")); td.queryable = Boolean.valueOf(type.elementTextTrim("queryable")); td.fulltextIndexed = Boolean.valueOf(type.elementTextTrim("fulltextIndexed")); td.includedInSupertypeQuery = Boolean.valueOf(type.elementTextTrim("includedInSupertypeQuery")); td.controllablePolicy = Boolean.valueOf(type.elementTextTrim("controllablePolicy")); td.controllableACL = Boolean.valueOf(type.elementTextTrim("controllableACL")); td.versionable = Boolean.valueOf(type.elementTextTrim("versionable")); td.contentStreamAllowed = type.elementTextTrim("contentStreamAllowed"); List<Element> allElements = doc.getRootElement().element(CMISRA_TYPE).elements(); for (Element element : allElements) { if (element.getName().startsWith("property")) { CmisPropertyTypeDefinition propTypeDef = CmisPropertyTypeDefinition.createFromElement(element); td.propertyDefinition.put(propTypeDef.getId(), propTypeDef); } } return td; } public String getId() { return id; } public String getLocalName() { return localName; } public String getLocalNamespace() { return localNamespace; } public String getDisplayName() { return displayName; } public String getQueryName() { return queryName; } public String getDescription() { return description; } public String getBaseId() { return baseId; } public boolean isCreatable() { return creatable; } public boolean isFileable() { return fileable; } public boolean isQueryable() { return queryable; } public boolean isFulltextIndexed() { return fulltextIndexed; } public boolean isIncludedInSupertypeQuery() { return includedInSupertypeQuery; } public boolean isControllablePolicy() { return controllablePolicy; } public boolean isControllableACL() { return controllableACL; } public boolean isVersionable() { return versionable; } public String getContentStreamAllowed() { return contentStreamAllowed; } public Map<String, CmisPropertyTypeDefinition> getPropertyDefinition() { return propertyDefinition; } private CmisPropertyTypeDefinition getTypeDefinitionForProperty(CmisProperty property) { return getPropertyDefinition().get(property.getDefinitionId()); } public String getDisplayNameForProperty(CmisProperty property) { CmisPropertyTypeDefinition propTypeDef = getTypeDefinitionForProperty(property); if (propTypeDef != null) { return propTypeDef.getDisplayName(); } return ""; } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; public class CmisModel { public final static String ITEM_LINK_UP = "up"; public final static String ITEM_LINK_DOWN = "down"; public final static String ITEM_LINK_SELF = "self"; public final static String CMIS_TYPE_FOLDER= "cmis:folder"; public final static String CMIS_TYPE_DOCUMENTS = "cmis:document"; }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import java.util.ArrayList; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; public class CmisItemCollection { private List<CmisItem> items = new ArrayList<CmisItem>(); private String upLink; private String title; private CmisItemCollection() { } public List<CmisItem> getItems() { return items; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public String getUpLink() { return upLink; } public static CmisItemCollection createFromFeed(Document doc) { CmisItemCollection cic = new CmisItemCollection(); cic.parseEntries(doc); return cic; } @SuppressWarnings("unchecked") private void parseEntries(Document doc) { List<Element> entries = doc.getRootElement().elements("entry"); for (Element entry : entries) { items.add(CmisItem.createFromFeed(entry)); } } public static CmisItemCollection emptyCollection() { CmisItemCollection cmi = new CmisItemCollection(); cmi.title = ""; cmi.upLink = ""; return cmi; } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.app.Activity; import android.text.TextUtils; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.utils.ListUtils; public class CmisPropertyFilter { private Map<String, CmisProperty> extraProps= new LinkedHashMap<String, CmisProperty>(); private Map<String, CmisProperty> objectProps= new LinkedHashMap<String, CmisProperty>(); private Map<String, CmisProperty> docProps= new LinkedHashMap<String, CmisProperty>(); private Map<String, CmisProperty> contentProps= new LinkedHashMap<String, CmisProperty>(); private Map<String, CmisProperty> folderProps= new LinkedHashMap<String, CmisProperty>(); private Map<String, CmisProperty> allProps = new LinkedHashMap<String, CmisProperty>(); private Map<String, Map<String, CmisProperty>> filters = new HashMap<String, Map<String,CmisProperty>>(5); private Map<String[], Map<String, CmisProperty>> filterToProps = new HashMap<String[], Map<String,CmisProperty>>(5); private CmisTypeDefinition typeDefinition; private String[] filterSelected; public CmisPropertyFilter(List<CmisProperty> propList, CmisTypeDefinition typeDefinition){ this.typeDefinition = typeDefinition; initFilters(); dispatch(propList); } public List<Map<String, ?>> render(){ return render(filterSelected); } public List<Map<String, ?>> render(String[] filterSelected){ this.filterSelected = filterSelected; Map<String, CmisProperty> currentProps = allProps; if (filterToProps.containsKey(filterSelected)){ currentProps = filterToProps.get(filterSelected); } List<Map<String, ?>> list = new ArrayList<Map<String, ?>>(); for(Entry<String, CmisProperty> prop : currentProps.entrySet()) { if (prop.getValue() != null){ list.add(ListUtils.createPair(getDisplayNameFromProperty(prop.getValue(), typeDefinition), prop.getValue().getValue())); } } return list; } private String getDisplayNameFromProperty(CmisProperty property, CmisTypeDefinition typeDefinition) { String name = property.getDisplayName(); if (TextUtils.isEmpty(name)) { } name = typeDefinition.getDisplayNameForProperty(property); if (TextUtils.isEmpty(name)) { name = property.getDefinitionId(); } return name.replaceAll("cmis:", ""); } private void dispatch(List<CmisProperty> propList) { for (CmisProperty cmisProperty : propList) { String definitionId = cmisProperty.getDefinitionId(); if (definitionId != null) { if (filters.get(definitionId) != null){ filters.get(definitionId).put(definitionId, cmisProperty); allProps.put(definitionId, cmisProperty); } else { extraProps.put(definitionId, cmisProperty); } } } allProps.putAll(extraProps); } private void initFilters(){ initPropsFilter(LIST_OBJECT, objectProps); initPropsFilter(LIST_FOLDER, folderProps); initPropsFilter(LIST_DOC, docProps); initPropsFilter(LIST_CONTENT, contentProps); initPropsFilter(LIST_EXTRA, extraProps); initAllPropsFilter(); } private void initPropsFilter(String[] props, Map<String, CmisProperty> listProps){ //LinkedHashMap<String, CmisProperty> hashMap = new LinkedHashMap<String, CmisProperty>(props.length); for (int i = 0; i < props.length; i++) { listProps.put(props[i], null); filters.put(props[i], listProps); } //listProps.putAll(hashMap; filterToProps.put(props, listProps); } private void initAllPropsFilter(){ allProps.putAll(objectProps); allProps.putAll(folderProps); allProps.putAll(docProps); allProps.putAll(contentProps); } public static final String[] LIST_EXTRA = { }; public static final String[] LIST_ALL = { }; public static final String[] LIST_OBJECT = { CmisProperty.OBJECT_NAME, CmisProperty.OBJECT_ID, CmisProperty.OBJECT_TYPEID, CmisProperty.OBJECT_BASETYPEID, CmisProperty.OBJECT_CREATEDBY, CmisProperty.OBJECT_CREATIONDATE, CmisProperty.OBJECT_LASTMODIFIEDBY, CmisProperty.OBJECT_LASTMODIFICATION, CmisProperty.OBJECT_CHANGETOKEN }; public static final String[] LIST_DOC = { CmisProperty.DOC_VERSIONLABEL, CmisProperty.DOC_ISLATESTEVERSION, CmisProperty.DOC_ISLATESTMAJORVERSION, CmisProperty.DOC_VERSIONSERIESID, CmisProperty.DOC_ISMAJORVERSION, CmisProperty.DOC_ISVERSIONCHECKEDOUT, CmisProperty.DOC_ISVERSIONCHECKEDOUTBY, CmisProperty.DOC_ISVERSIONCHECKEDOUTID, CmisProperty.DOC_ISIMMUTABLE, CmisProperty.DOC_CHECINCOMMENT }; public static final String[] LIST_CONTENT = { CmisProperty.CONTENT_STREAMID, CmisProperty.CONTENT_STREAMLENGTH, CmisProperty.CONTENT_STREAMMIMETYPE, CmisProperty.CONTENT_STREAMFILENAME }; public static final String[] LIST_FOLDER = { CmisProperty.FOLDER_PARENTID, CmisProperty.FOLDER_PATH, CmisProperty.FOLDER_ALLOWCHILDREN, }; public static String[] concat(String[] A, String[] B) { String[] C = new String[A.length + B.length]; System.arraycopy(A, 0, C, 0, A.length); System.arraycopy(B, 0, C, A.length, B.length); return C; } public static String[] generateFilter(ArrayList<String[]> workingFilters){ String[] C = {}; for (String[] strings : workingFilters) { C = concat(C, strings); } return C; } public static String[] getFilter(CmisItemLazy item){ if (CmisModel.CMIS_TYPE_FOLDER.equals(item.getBaseType())){ return concat(LIST_OBJECT, LIST_FOLDER); } else if (CmisModel.CMIS_TYPE_DOCUMENTS.equals(item.getBaseType())){ if (item.getSize() != null && item.getSize().equals("0") == false){ return concat(LIST_OBJECT,concat(LIST_DOC, LIST_CONTENT)); } else { return concat(LIST_OBJECT, LIST_DOC); } } else { return LIST_OBJECT; } } public static ArrayList<String[]> getFilters(CmisItemLazy item) { ArrayList<String[]> filters = new ArrayList<String[]>(5); filters.add(LIST_OBJECT); if (CmisModel.CMIS_TYPE_FOLDER.equals(item.getBaseType())){ filters.add(LIST_FOLDER); } else if (CmisModel.CMIS_TYPE_DOCUMENTS.equals(item.getBaseType())){ filters.add(LIST_DOC); filters.add(LIST_CONTENT); } filters.add(LIST_EXTRA); filters.add(LIST_ALL); return filters; } private static ArrayList<String> getFilters(Activity activity, CmisItemLazy item) { ArrayList<String> filters = new ArrayList<String>(5); filters.add(activity.getText(R.string.item_filter_object).toString()); if (CmisModel.CMIS_TYPE_FOLDER.equals(item.getBaseType())){ filters.add(activity.getText(R.string.item_filter_folder).toString()); } else if (CmisModel.CMIS_TYPE_DOCUMENTS.equals(item.getBaseType())){ filters.add(activity.getText(R.string.item_filter_document).toString()); filters.add(activity.getText(R.string.item_filter_content).toString()); } filters.add(activity.getText(R.string.item_filter_extra).toString()); filters.add(activity.getText(R.string.item_filter_all).toString()); return filters; } public static CharSequence[] getFiltersLabel(Activity activity, CmisItemLazy item) { ArrayList<String> filters = getFilters(activity, item); return filters.toArray(new CharSequence[filters.size()]); } public static ArrayList<String[]> createFilters() { ArrayList<String[]> filters = new ArrayList<String[]>(5); filters.add(LIST_OBJECT); filters.add(LIST_FOLDER); filters.add(LIST_DOC); filters.add(LIST_CONTENT); filters.add(LIST_EXTRA); filters.add(LIST_ALL); return filters; } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.repo; import org.dom4j.Element; public class CmisPropertyTypeDefinition { private String id; private String localName; private String localNamespace; private String displayName; private String queryName; private String description; private String propertyType; private String cardinality; private String updatability; private boolean inherited; private boolean required; private boolean queryable; private boolean orderable; private boolean openChoice; public static CmisPropertyTypeDefinition createFromElement(Element propElement) { CmisPropertyTypeDefinition cpd = new CmisPropertyTypeDefinition(); cpd.id = propElement.elementText("id"); cpd.localName = propElement.elementText("localName"); cpd.localNamespace = propElement.elementText("localNamespace"); cpd.displayName = propElement.elementText("displayName"); cpd.queryName = propElement.elementText("queryName"); cpd.description = propElement.elementText("description"); cpd.propertyType = propElement.elementText("propertyType"); cpd.cardinality = propElement.elementText("cardinality"); cpd.updatability = propElement.elementText("updatability"); cpd.inherited = Boolean.parseBoolean(propElement.elementText("inherited")); cpd.required = Boolean.parseBoolean(propElement.elementText("required")); cpd.queryable = Boolean.parseBoolean(propElement.elementText("queryable")); cpd.orderable = Boolean.parseBoolean(propElement.elementText("orderable")); cpd.openChoice = Boolean.parseBoolean(propElement.elementText("openChoice")); return cpd; } public String getId() { return id; } public String getLocalName() { return localName; } public String getLocalNamespace() { return localNamespace; } public String getDisplayName() { return displayName; } public String getQueryName() { return queryName; } public String getDescription() { return description; } public String getPropertyType() { return propertyType; } public String getCardinality() { return cardinality; } public String getUpdatability() { return updatability; } public boolean isInherited() { return inherited; } public boolean isRequired() { return required; } public boolean isQueryable() { return queryable; } public boolean isOrderable() { return orderable; } public boolean isOpenChoice() { return openChoice; } }
Java
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.utils; /** * <p>Encapsulates the result of a barcode scan invoked through {@link IntentIntegrator}.</p> * * @author Sean Owen */ public final class IntentResult { private final String contents; private final String formatName; IntentResult(String contents, String formatName) { this.contents = contents; this.formatName = formatName; } /** * @return raw content of barcode */ public String getContents() { return contents; } /** * @return name of format, like "QR_CODE", "UPC_A". See <code>BarcodeFormat</code> for more format names. */ public String getFormatName() { return formatName; } }
Java
package de.fmaul.android.cmis.utils; import android.graphics.drawable.Drawable; import android.view.View.OnClickListener; /** * Action item, displayed as menu with icon and text. * * @author Lorensius. W. L. T * */ public class ActionItem { private Drawable icon; private String title; private OnClickListener listener; /** * Constructor */ public ActionItem() {} /** * Constructor * * @param icon {@link Drawable} action icon */ public ActionItem(Drawable icon) { this.icon = icon; } /** * Set action title * * @param title action title */ public void setTitle(String title) { this.title = title; } /** * Get action title * * @return action title */ public String getTitle() { return this.title; } /** * Set action icon * * @param icon {@link Drawable} action icon */ public void setIcon(Drawable icon) { this.icon = icon; } /** * Get action icon * @return {@link Drawable} action icon */ public Drawable getIcon() { return this.icon; } /** * Set on click listener * * @param listener on click listener {@link View.OnClickListener} */ public void setOnClickListener(OnClickListener listener) { this.listener = listener; } /** * Get on click listener * * @return on click listener {@link View.OnClickListener} */ public OnClickListener getListener() { return this.listener; } }
Java
/* * Copyright 2009 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.utils; import android.app.AlertDialog; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; /** * <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple * way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the * project's source code.</p> * * <h2>Initiating a barcode scan</h2> * * <p>Integration is essentially as easy as calling {@link #initiateScan(Activity)} and waiting * for the result in your app.</p> * * <p>It does require that the Barcode Scanner application is installed. The * {@link #initiateScan(Activity)} method will prompt the user to download the application, if needed.</p> * * <p>There are a few steps to using this integration. First, your {@link Activity} must implement * the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:</p> * * <p>{@code * public void onActivityResult(int requestCode, int resultCode, Intent intent) { * IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); * if (scanResult != null) { * // handle scan result * } * // else continue with any other code you need in the method * ... * } * }</p> * * <p>This is where you will handle a scan result. * Second, just call this in response to a user action somewhere to begin the scan process:</p> * * <p>{@code IntentIntegrator.initiateScan(yourActivity);}</p> * * <p>You can use {@link #initiateScan(Activity, CharSequence, CharSequence, CharSequence, CharSequence)} or * {@link #initiateScan(Activity, int, int, int, int)} to customize the download prompt with * different text labels.</p> * * <p>Note that {@link #initiateScan(Activity)} returns an {@link AlertDialog} which is non-null if the * user was prompted to download the application. This lets the calling app potentially manage the dialog. * In particular, ideally, the app dismisses the dialog if it's still active in its {@link Activity#onPause()} * method.</p> * * <h2>Sharing text via barcode</h2> * * <p>To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(Activity, CharSequence)}.</p> * * <p>Some code, particularly download integration, was contributed from the Anobiit application.</p> * * @author Sean Owen * @author Fred Lin * @author Isaac Potoczny-Jones * @author Brad Drehmer */ public final class IntentIntegrator { public static final int REQUEST_CODE = 0x0ba7c0de; // get it? public static final String DEFAULT_TITLE = "Install Barcode Scanner?"; public static final String DEFAULT_MESSAGE = "This application requires Barcode Scanner. Would you like to install it?"; public static final String DEFAULT_YES = "Yes"; public static final String DEFAULT_NO = "No"; // supported barcode formats public static final String PRODUCT_CODE_TYPES = "UPC_A,UPC_E,EAN_8,EAN_13"; public static final String ONE_D_CODE_TYPES = PRODUCT_CODE_TYPES + ",CODE_39,CODE_93,CODE_128"; public static final String QR_CODE_TYPES = "QR_CODE"; public static final String ALL_CODE_TYPES = null; private IntentIntegrator() { } /** * See {@link #initiateScan(Activity, CharSequence, CharSequence, CharSequence, CharSequence)} -- * same, but uses default English labels. */ public static AlertDialog initiateScan(Activity activity) { return initiateScan(activity, DEFAULT_TITLE, DEFAULT_MESSAGE, DEFAULT_YES, DEFAULT_NO); } /** * See {@link #initiateScan(Activity, CharSequence, CharSequence, CharSequence, CharSequence)} -- * same, but takes string IDs which refer * to the {@link Activity}'s resource bundle entries. */ public static AlertDialog initiateScan(Activity activity, int stringTitle, int stringMessage, int stringButtonYes, int stringButtonNo) { return initiateScan(activity, activity.getString(stringTitle), activity.getString(stringMessage), activity.getString(stringButtonYes), activity.getString(stringButtonNo)); } /** * See {@link #initiateScan(Activity, CharSequence, CharSequence, CharSequence, CharSequence, CharSequence)} -- * same, but scans for all supported barcode types. * @param stringTitle title of dialog prompting user to download Barcode Scanner * @param stringMessage text of dialog prompting user to download Barcode Scanner * @param stringButtonYes text of button user clicks when agreeing to download * Barcode Scanner (e.g. "Yes") * @param stringButtonNo text of button user clicks when declining to download * Barcode Scanner (e.g. "No") * @return an {@link AlertDialog} if the user was prompted to download the app, * null otherwise */ public static AlertDialog initiateScan(Activity activity, CharSequence stringTitle, CharSequence stringMessage, CharSequence stringButtonYes, CharSequence stringButtonNo) { return initiateScan(activity, stringTitle, stringMessage, stringButtonYes, stringButtonNo, ALL_CODE_TYPES); } /** * Invokes scanning. * * @param stringTitle title of dialog prompting user to download Barcode Scanner * @param stringMessage text of dialog prompting user to download Barcode Scanner * @param stringButtonYes text of button user clicks when agreeing to download * Barcode Scanner (e.g. "Yes") * @param stringButtonNo text of button user clicks when declining to download * Barcode Scanner (e.g. "No") * @param stringDesiredBarcodeFormats a comma separated list of codes you would * like to scan for. * @return an {@link AlertDialog} if the user was prompted to download the app, * null otherwise * @throws InterruptedException if timeout expires before a scan completes */ public static AlertDialog initiateScan(Activity activity, CharSequence stringTitle, CharSequence stringMessage, CharSequence stringButtonYes, CharSequence stringButtonNo, CharSequence stringDesiredBarcodeFormats) { Intent intentScan = new Intent("com.google.zxing.client.android.SCAN"); intentScan.addCategory(Intent.CATEGORY_DEFAULT); // check which types of codes to scan for if (stringDesiredBarcodeFormats != null) { // set the desired barcode types intentScan.putExtra("SCAN_FORMATS", stringDesiredBarcodeFormats); } try { activity.startActivityForResult(intentScan, REQUEST_CODE); return null; } catch (ActivityNotFoundException e) { return showDownloadDialog(activity, stringTitle, stringMessage, stringButtonYes, stringButtonNo); } } private static AlertDialog showDownloadDialog(final Activity activity, CharSequence stringTitle, CharSequence stringMessage, CharSequence stringButtonYes, CharSequence stringButtonNo) { AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity); downloadDialog.setTitle(stringTitle); downloadDialog.setMessage(stringMessage); downloadDialog.setPositiveButton(stringButtonYes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); activity.startActivity(intent); } }); downloadDialog.setNegativeButton(stringButtonNo, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) {} }); return downloadDialog.show(); } /** * <p>Call this from your {@link Activity}'s * {@link Activity#onActivityResult(int, int, Intent)} method.</p> * * @return null if the event handled here was not related to {@link IntentIntegrator}, or * else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning, * the fields will be null. */ public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT"); return new IntentResult(contents, formatName); } else { return new IntentResult(null, null); } } return null; } /** * See {@link #shareText(Activity, CharSequence, CharSequence, CharSequence, CharSequence, CharSequence)} -- * same, but uses default English labels. */ public static void shareText(Activity activity, CharSequence text) { shareText(activity, text, DEFAULT_TITLE, DEFAULT_MESSAGE, DEFAULT_YES, DEFAULT_NO); } /** * See {@link #shareText(Activity, CharSequence, CharSequence, CharSequence, CharSequence, CharSequence)} -- * same, but takes string IDs which refer to the {@link Activity}'s resource bundle entries. */ public static void shareText(Activity activity, CharSequence text, int stringTitle, int stringMessage, int stringButtonYes, int stringButtonNo) { shareText(activity, text, activity.getString(stringTitle), activity.getString(stringMessage), activity.getString(stringButtonYes), activity.getString(stringButtonNo)); } /** * Shares the given text by encoding it as a barcode, such that another user can * scan the text off the screen of the device. * * @param text the text string to encode as a barcode * @param stringTitle title of dialog prompting user to download Barcode Scanner * @param stringMessage text of dialog prompting user to download Barcode Scanner * @param stringButtonYes text of button user clicks when agreeing to download * Barcode Scanner (e.g. "Yes") * @param stringButtonNo text of button user clicks when declining to download * Barcode Scanner (e.g. "No") */ public static void shareText(Activity activity, CharSequence text, CharSequence stringTitle, CharSequence stringMessage, CharSequence stringButtonYes, CharSequence stringButtonNo) { Intent intent = new Intent(); intent.setAction("com.google.zxing.client.android.ENCODE"); intent.putExtra("ENCODE_TYPE", "TEXT_TYPE"); intent.putExtra("ENCODE_DATA", text); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { showDownloadDialog(activity, stringTitle, stringMessage, stringButtonYes, stringButtonNo); } } }
Java
package de.fmaul.android.cmis.utils; public class StorageException extends Exception { /** * */ private static final long serialVersionUID = 329581492462074017L; StorageException(String erreur, Exception e){ super(erreur, e); } public StorageException(String erreur) { super(erreur); } }
Java
package de.fmaul.android.cmis.utils; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.widget.ImageView; import android.widget.TextView; import android.widget.LinearLayout; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; import android.view.ViewGroup; import java.util.ArrayList; import de.fmaul.android.cmis.R; /** * Popup window, shows action list as icon and text (QuickContact / Twitter app). * * @author Lorensius. W. T */ public class QuickAction extends CustomPopupWindow { private final View root; private final ImageView mArrowUp; private final ImageView mArrowDown; private final Animation mTrackAnim; private final LayoutInflater inflater; private final Context context; protected static final int ANIM_GROW_FROM_LEFT = 1; protected static final int ANIM_GROW_FROM_RIGHT = 2; public static final int ANIM_GROW_FROM_CENTER = 3; protected static final int ANIM_AUTO = 4; private int animStyle; private boolean animateTrack; private ViewGroup mTrack; private ArrayList<ActionItem> actionList; /** * Constructor * * @param anchor {@link View} on where the popup should be displayed */ public QuickAction(View anchor) { super(anchor); actionList = new ArrayList<ActionItem>(); context = anchor.getContext(); inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); root = (ViewGroup) inflater.inflate(R.layout.quickaction, null); mArrowDown = (ImageView) root.findViewById(R.id.arrow_down); mArrowUp = (ImageView) root.findViewById(R.id.arrow_up); setContentView(root); mTrackAnim = AnimationUtils.loadAnimation(anchor.getContext(), R.anim.rail); mTrackAnim.setInterpolator(new Interpolator() { public float getInterpolation(float t) { // Pushes past the target area, then snaps back into place. // Equation for graphing: 1.2-((x*1.6)-1.1)^2 final float inner = (t * 1.55f) - 1.1f; return 1.2f - inner * inner; } }); mTrack = (ViewGroup) root.findViewById(R.id.tracks); animStyle = ANIM_AUTO; animateTrack = true; } /** * Animate track * * @param animateTrack flag to animate track */ public void animateTrack(boolean animateTrack) { this.animateTrack = animateTrack; } /** * Set animation style * * @param animStyle animation style, default is set to ANIM_AUTO */ public void setAnimStyle(int animStyle) { this.animStyle = animStyle; } /** * Add action item * * @param action {@link ActionItem} */ public void addActionItem(ActionItem action) { actionList.add(action); } /** * Show popup window */ public void show () { preShow(); int[] location = new int[2]; anchor.getLocationOnScreen(location); Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] + anchor.getHeight()); root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); int rootWidth = root.getMeasuredWidth(); int rootHeight = root.getMeasuredHeight(); int screenWidth = windowManager.getDefaultDisplay().getWidth(); //int screenHeight = windowManager.getDefaultDisplay().getHeight(); int xPos = (screenWidth - rootWidth) / 2; int yPos = anchorRect.top - rootHeight; boolean onTop = true; // display on bottom if (rootHeight > anchorRect.top) { yPos = anchorRect.bottom; onTop = false; } showArrow(((onTop) ? R.id.arrow_down : R.id.arrow_up), anchorRect.centerX()); setAnimationStyle(screenWidth, anchorRect.centerX(), onTop); createActionList(); window.showAtLocation(this.anchor, Gravity.NO_GRAVITY, xPos, yPos); if (animateTrack) mTrack.startAnimation(mTrackAnim); } /** * Set animation style * * @param screenWidth Screen width * @param requestedX distance from left screen * @param onTop flag to indicate where the popup should be displayed. Set TRUE if displayed on top of anchor and vice versa */ private void setAnimationStyle(int screenWidth, int requestedX, boolean onTop) { int arrowPos = requestedX - mArrowUp.getMeasuredWidth()/2; switch (animStyle) { case ANIM_GROW_FROM_LEFT: window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); break; case ANIM_GROW_FROM_RIGHT: window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Right : R.style.Animations_PopDownMenu_Right); break; case ANIM_GROW_FROM_CENTER: window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); break; case ANIM_AUTO: if (arrowPos <= screenWidth/4) { window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Left : R.style.Animations_PopDownMenu_Left); } else if (arrowPos > screenWidth/4 && arrowPos < 3 * (screenWidth/4)) { window.setAnimationStyle((onTop) ? R.style.Animations_PopUpMenu_Center : R.style.Animations_PopDownMenu_Center); } else { window.setAnimationStyle((onTop) ? R.style.Animations_PopDownMenu_Right : R.style.Animations_PopDownMenu_Right); } break; } } /** * Create action list * */ private void createActionList() { View view; String title; Drawable icon; OnClickListener listener; int index = 1; for (int i = 0; i < actionList.size(); i++) { title = actionList.get(i).getTitle(); icon = actionList.get(i).getIcon(); listener = actionList.get(i).getListener(); view = getActionItem(title, icon, listener); view.setFocusable(true); view.setClickable(true); mTrack.addView(view, index); index++; } } /** * Get action item {@link View} * * @param title action item title * @param icon {@link Drawable} action item icon * @param listener {@link View.OnClickListener} action item listener * @return action item {@link View} */ private View getActionItem(String title, Drawable icon, OnClickListener listener) { LinearLayout container = (LinearLayout) inflater.inflate(R.layout.action_item, null); ImageView img = (ImageView) container.findViewById(R.id.icon); TextView text = (TextView) container.findViewById(R.id.title); if (icon != null) { img.setImageDrawable(icon); } else { img.setVisibility(View.GONE); } if (title != null) { text.setText(title); } else { text.setVisibility(View.GONE); } if (listener != null) { container.setOnClickListener(listener); } return container; } /** * Show arrow * * @param whichArrow arrow type resource id * @param requestedX distance from left screen */ private void showArrow(int whichArrow, int requestedX) { final View showArrow = (whichArrow == R.id.arrow_up) ? mArrowUp : mArrowDown; final View hideArrow = (whichArrow == R.id.arrow_up) ? mArrowDown : mArrowUp; final int arrowWidth = mArrowUp.getMeasuredWidth(); showArrow.setVisibility(View.VISIBLE); ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams)showArrow.getLayoutParams(); param.leftMargin = requestedX - arrowWidth / 2; hideArrow.setVisibility(View.INVISIBLE); } }
Java
package de.fmaul.android.cmis.utils; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.DialogInterface; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.widget.AdapterView; import android.widget.EditText; import android.widget.GridView; import android.widget.ListView; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisRepository; public class UIUtils { public static void createSearchMenu(Menu menu) { SubMenu searchMenu = menu.addSubMenu(R.string.menu_item_search); searchMenu.setIcon(R.drawable.search); searchMenu.getItem().setAlphabeticShortcut(SearchManager.MENU_KEY); searchMenu.setHeaderIcon(R.drawable.search); searchMenu.add(Menu.NONE, 20, 0, R.string.menu_item_search_title); searchMenu.add(Menu.NONE, 21, 0, R.string.menu_item_search_folder_title); searchMenu.add(Menu.NONE, 22, 0, R.string.menu_item_search_fulltext); searchMenu.add(Menu.NONE, 23, 0, R.string.menu_item_search_cmis); searchMenu.add(Menu.NONE, 24, 0, R.string.menu_item_search_saved_search); } public static void createContextMenu(ListActivity activity, ContextMenu menu, ContextMenuInfo menuInfo) { menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(activity.getString(R.string.feed_menu_title)); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; CmisItem doc = (CmisItem) activity.getListView().getItemAtPosition(info.position); menu.add(0, 2, Menu.NONE, activity.getString(R.string.menu_item_details)); menu.add(0, 3, Menu.NONE, activity.getString(R.string.menu_item_share)); if (doc != null && doc.getProperties().get("cmis:contentStreamLength") != null){ menu.add(0, 1, Menu.NONE, activity.getString(R.string.download)); } menu.add(0, 4, Menu.NONE, activity.getString(R.string.menu_item_favorites)); } public static boolean onContextItemSelected(Activity activity, MenuItem menuItem, Prefs prefs) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo(); } catch (ClassCastException e) { return false; } GridView gridview = (GridView) activity.findViewById(R.id.gridview); ListView listView = ((ListActivity) activity).getListView(); CmisItem item = null; if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ item = (CmisItem) gridview.getItemAtPosition(menuInfo.position); } else { item = (CmisItem) listView.getItemAtPosition(menuInfo.position); } CmisRepository repository = ((CmisApp) activity.getApplication()).getRepository(); switch (menuItem.getItemId()) { case 1: if (item != null && item.hasChildren() == false) { ActionUtils.openDocument(activity, item); } return true; case 2: if (item != null) { ActionUtils.displayDocumentDetails(activity, item); } return true; case 3: if (item != null) { ActionUtils.shareDocument(activity, repository.getServer().getWorkspace(), item); } return true; case 4: if (item != null) { ActionUtils.createFavorite(activity, repository.getServer(), item); } return true; default: return false; } } public static AlertDialog createDialog(Activity activity, int title, int message, String defaultValue, DialogInterface.OnClickListener positiveClickListener){ final AlertDialog.Builder alert = new AlertDialog.Builder(activity); alert.setTitle(title); alert.setMessage(message); EditText input = new EditText(activity); input.setText(defaultValue); alert.setView(input); alert.setPositiveButton(R.string.validate, positiveClickListener); alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); return alert.create(); } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.io.FileUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import de.fmaul.android.cmis.CmisApp; import android.app.Application; import android.os.Environment; import android.util.Log; public class StorageUtils { public static final String TYPE_FEEDS = "cache"; public static final String TYPE_CONTENT = "files"; public static final String TYPE_DOWNLOAD = "download"; public static final String ROOT_FOLDER_APP = "android-cmis-browser"; public static boolean isFeedInCache(Application app, String url, String workspace) throws StorageException { File cacheFile = getFeedFile(app, workspace, md5(url)); return cacheFile != null && cacheFile.exists(); } public static Document getFeedFromCache(Application app, String url, String workspace) throws StorageException { File cacheFile = getFeedFile(app, workspace, md5(url)); Log.d("CmisRepository", cacheFile.getAbsolutePath()); Document document = null; SAXReader reader = new SAXReader(); // dom4j SAXReader try { document = reader.read(cacheFile); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } // dom4j Document return document; } private static File getFeedFile(Application app, String repoId, String feedHash) throws StorageException { return getStorageFile(app, repoId, TYPE_FEEDS, null, feedHash + ".xml"); } public static void storeFeedInCache(Application app, String url, Document doc, String workspace) throws StorageException { File cacheFile = getFeedFile(app, workspace, md5(url)); ensureOrCreatePathAndFile(cacheFile); try { XMLWriter writer = new XMLWriter(new FileOutputStream(cacheFile)); writer.write(doc); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); ensureOrCreatePathAndFile(dst); OutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } public static File getDownloadRoot(Application app) throws StorageException { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { StringBuilder builder = new StringBuilder(); builder.append(((CmisApp) app).getPrefs().getDownloadFolder()); builder.append("/"); builder.append(ROOT_FOLDER_APP); return new File(builder.toString()); } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { throw new StorageException("Storage in Read Only Mode"); } else { throw new StorageException("Storage is unavailable"); } } public static File getStorageFile(Application app, String saveFolder, String filename) throws StorageException { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { StringBuilder builder = new StringBuilder(); builder.append(saveFolder); builder.append("/"); builder.append(ROOT_FOLDER_APP); builder.append("/"); builder.append(((CmisApp) app).getRepository().getServer().getName()); if (filename != null) { builder.append("/"); builder.append(filename); } return new File(builder.toString()); } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { throw new StorageException("Storage in Read Only Mode"); } else { throw new StorageException("Storage is unavailable"); } } public static File getStorageFile(Application app, String repoId, String storageType, String itemId, String filename) throws StorageException { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { StringBuilder builder = new StringBuilder(); builder.append(Environment.getExternalStorageDirectory()); builder.append("/"); builder.append("Android"); builder.append("/"); builder.append("data"); builder.append("/"); builder.append(app.getPackageName()); builder.append("/"); if (storageType != null) { builder.append("/"); builder.append(storageType); } if (repoId != null) { builder.append("/"); builder.append(repoId); } if (itemId != null) { builder.append("/"); builder.append(itemId.replaceAll(":", "_")); } if (filename != null) { builder.append("/"); builder.append(filename); } return new File(builder.toString()); } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { throw new StorageException("Storage in Read Only Mode"); } else { throw new StorageException("Storage is unavailable"); } } private static void ensureOrCreatePathAndFile(File contentFile) { try { contentFile.getParentFile().mkdirs(); contentFile.createNewFile(); } catch (IOException iox) { throw new RuntimeException(iox); } } public static String md5(String s) { try { // Create MD5 Hash MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte messageDigest[] = digest.digest(); // Create Hex String StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) hexString.append(Integer.toHexString(0xFF & messageDigest[i])); return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } public static boolean deleteRepositoryFiles(Application app, String repoId) throws StorageException { File repoDir = getStorageFile(app, repoId, TYPE_FEEDS, null, null); try { FileUtils.deleteDirectory(repoDir); return true; } catch (IOException e) { return false; } } public static boolean deleteCacheFolder(Application app) throws StorageException { File contentDir = getStorageFile(app, null, TYPE_CONTENT, null, null); File feedsDir = getStorageFile(app, null, TYPE_FEEDS, null, null); try { FileUtils.deleteDirectory(contentDir); FileUtils.deleteDirectory(feedsDir); return true; } catch (IOException e) { return false; } } public static boolean deleteRepositoryCacheFiles(Application app, String repoId) throws StorageException { File contentDir = getStorageFile(app, repoId, TYPE_CONTENT, null, null); File feedsDir = getStorageFile(app, repoId, TYPE_FEEDS, null, null); try { FileUtils.deleteDirectory(contentDir); FileUtils.deleteDirectory(feedsDir); return true; } catch (IOException e) { return false; } } public static boolean deleteFeedFile(Application app, String repoId, String url) throws StorageException { File feedFile = getFeedFile(app, repoId, md5(url)); Log.d("CmisRepository", feedFile.getAbsolutePath()); if (feedFile.exists()){ feedFile.delete(); return true; } else { return false; } } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.utils; /** * Runtime excpetion that is thrown in case a CMIS feed can not be loaded. * Usually contains the cause as inner exception. * * @author Florian Maul */ public class FeedLoadException extends RuntimeException { public FeedLoadException(Throwable e) { super(e); } /** * */ private static final long serialVersionUID = -7034486177281832030L; }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.utils; import java.io.File; import android.app.Activity; import android.text.TextUtils; import android.widget.Toast; public class FileSystemUtils { public static boolean rename(File file, String newName){ if (file.exists()){ return file.renameTo(new File(file.getParent(), newName)); } else { return false; } } public static boolean rename(File folder, File file){ if (folder.exists()){ return file.renameTo(new File(folder, file.getName())); } else { return false; } } public static boolean delete(File file){ if (file.exists()){ if (file.isDirectory()) { return recursiveDelete(file); } else { return file.delete(); } } else { return true; } } public static void open(Activity activity, File file){ if (file.exists()){ ActionUtils.openDocument(activity, file); } } private static boolean recursiveDelete(File file) { // Recursively delete all contents. File[] files = file.listFiles(); if (files != null) { for (int x=0; x<files.length; x++) { File childFile = files[x]; if (childFile.isDirectory()) { if (!recursiveDelete(childFile)) { return false; } } else { if (!childFile.delete()) { return false; } } } } if (!file.delete()) { return false; } return true; } public static boolean createNewFolder(File currentDirectory, String foldername) { if (!TextUtils.isEmpty(foldername)) { File file = new File(currentDirectory, foldername); if (file.mkdirs()){ return true; } else { return false; } } else { return false; } } }
Java
package de.fmaul.android.cmis.utils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.app.Activity; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisModel; import de.fmaul.android.cmis.repo.CmisPropertyFilter; public class MimetypeUtils { private static ArrayList<String> getOpenWithRows(Activity activity) { ArrayList<String> filters = new ArrayList<String>(5); filters.add(activity.getText(R.string.open_with_text).toString()); filters.add(activity.getText(R.string.open_with_image).toString()); filters.add(activity.getText(R.string.open_with_audio).toString()); filters.add(activity.getText(R.string.open_with_video).toString()); return filters; } public static ArrayList<String> getDefaultMimeType() { ArrayList<String> filters = new ArrayList<String>(5); filters.add("text/plain"); filters.add("image/jpeg"); filters.add("audio/mpeg3"); filters.add("video/avi"); return filters; } public static CharSequence[] getOpenWithRowsLabel(Activity activity) { ArrayList<String> filters = getOpenWithRows(activity); return filters.toArray(new CharSequence[filters.size()]); } public static Integer getIcon(Activity activity, CmisItemLazy item) { if (item.hasChildren()) { return R.drawable.mt_folderopen; } else { String mimetype = item.getMimeType(); if (((CmisApp) activity.getApplication()).getMimetypesMap().containsKey(mimetype)){ return ((CmisApp) activity.getApplication()).getMimetypesMap().get(mimetype); } else { return R.drawable.mt_file; } } } public static Integer getIcon(Activity activity, String mimetype) { if (mimetype != null && mimetype.length() != 0 && mimetype.equals("cmis:folder") == false) { if (((CmisApp) activity.getApplication()).getMimetypesMap().containsKey(mimetype)){ return ((CmisApp) activity.getApplication()).getMimetypesMap().get(mimetype); } else { return R.drawable.mt_file; } } else { return R.drawable.mt_folderopen; } } public static Map<String,Integer> createIconMap(){ Map<String,Integer> iconMap = new HashMap<String, Integer>(); iconMap.put("application/atom+xml",R.drawable.mt_xml); iconMap.put("application/javascript",R.drawable.mt_script); iconMap.put("application/mp4",R.drawable.mt_video); iconMap.put("application/octet-stream",R.drawable.mt_file); iconMap.put("application/msword",R.drawable.mt_msword); iconMap.put("application/pdf",R.drawable.mt_pdf); iconMap.put("application/postscript",R.drawable.mt_script); iconMap.put("application/rtf",R.drawable.mt_text); iconMap.put("application/sgml",R.drawable.mt_xml); iconMap.put("application/vnd.ms-excel",R.drawable.mt_msexcel); iconMap.put("application/vnd.ms-powerpoint",R.drawable.mt_mspowerpoint); iconMap.put("application/xml",R.drawable.mt_xml); iconMap.put("application/x-tar",R.drawable.mt_package); iconMap.put("application/zip",R.drawable.mt_package); iconMap.put("audio/basic",R.drawable.mt_audio); iconMap.put("audio/mpeg",R.drawable.mt_audio); iconMap.put("audio/mp4",R.drawable.mt_audio); iconMap.put("audio/x-aiff",R.drawable.mt_audio); iconMap.put("audio/x-wav",R.drawable.mt_audio); iconMap.put("image/gif",R.drawable.mt_image); iconMap.put("image/jpeg",R.drawable.mt_image); iconMap.put("image/png",R.drawable.mt_image); iconMap.put("image/tiff",R.drawable.mt_image); iconMap.put("image/x-portable-bitmap",R.drawable.mt_image); iconMap.put("image/x-portable-graymap",R.drawable.mt_image); iconMap.put("image/x-portable-pixmap",R.drawable.mt_image); iconMap.put("multipart/x-zip",R.drawable.mt_package); iconMap.put("multipart/x-gzip",R.drawable.mt_package); iconMap.put("text/css",R.drawable.mt_css); iconMap.put("text/csv",R.drawable.mt_sql); iconMap.put("text/html",R.drawable.mt_html); iconMap.put("text/plain",R.drawable.mt_text); iconMap.put("text/richtext",R.drawable.mt_text); iconMap.put("text/rtf",R.drawable.mt_text); iconMap.put("text/tab-separated-value",R.drawable.mt_sql); iconMap.put("text/xml",R.drawable.mt_xml); iconMap.put("video/h264",R.drawable.mt_video); iconMap.put("video/dv",R.drawable.mt_video); iconMap.put("video/mpeg",R.drawable.mt_video); iconMap.put("video/quicktime",R.drawable.mt_video); iconMap.put("video/msvideo",R.drawable.mt_video); return iconMap; } public static Map<String,String> createExtensionMap(){ Map<String,String> extensionMap = new HashMap<String, String>(); extensionMap.put("bmp", "image/bmp"); extensionMap.put("doc", "application/msword"); extensionMap.put("jpg", "image/jpeg"); extensionMap.put("jpeg", "image/jpeg"); extensionMap.put("mp3", "audio/mp3"); extensionMap.put("pdf", "application/pdf"); extensionMap.put("ppt", "application/vnd.ms-powerpoint"); extensionMap.put("png", "image/png"); extensionMap.put("xls", "application/vnd.ms-excel"); extensionMap.put("mp3", "audio/mp3"); extensionMap.put("wav", "audio/wav"); extensionMap.put("ogg", "audio/x-ogg"); extensionMap.put("mid", "audio/mid"); extensionMap.put("midi", "audio/midi"); extensionMap.put("amr", "audio/AMR"); extensionMap.put("mpeg", "video/mpeg"); extensionMap.put("3gp", "video/3gpp"); extensionMap.put("jar", "application/java-archive"); extensionMap.put("zip", "application/zip"); extensionMap.put("rar", "application/x-rar-compressed"); extensionMap.put("gz", "application/gzip"); extensionMap.put("htm", "text/html"); extensionMap.put("html", "text/html"); extensionMap.put("php", "text/php"); extensionMap.put("txt", "text/plain"); extensionMap.put("csv", "text/csv"); extensionMap.put("xml", "text/xml"); extensionMap.put("apk", "application/vnd.android.package-archive"); return extensionMap; } public static String getMimetype(Activity activity, File file) { if (file.exists() && file.isFile()) { Map<String, String> map = createExtensionMap(); String name = file.getName(); String extension = name.substring(name.lastIndexOf(".")+1, name.length()); if (map.containsKey(extension)){ return map.get(extension); } else { return ""; } } else { return ""; } } }
Java
package de.fmaul.android.cmis.utils; import de.fmaul.android.cmis.R; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.PopupWindow; /** * This class does most of the work of wrapping the {@link PopupWindow} so it's simpler to use. * Edited by Lorensius. W. L. T * * @author qberticus * */ public class CustomPopupWindow { protected final View anchor; protected final PopupWindow window; private View root; private Drawable background = null; protected final WindowManager windowManager; /** * Create a QuickAction * * @param anchor * the view that the QuickAction will be displaying 'from' */ public CustomPopupWindow(View anchor) { this.anchor = anchor; this.window = new PopupWindow(anchor.getContext()); // when a touch even happens outside of the window // make the window go away window.setTouchInterceptor(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { CustomPopupWindow.this.window.dismiss(); return true; } return false; } }); windowManager = (WindowManager) anchor.getContext().getSystemService(Context.WINDOW_SERVICE); onCreate(); } /** * Anything you want to have happen when created. Probably should create a view and setup the event listeners on * child views. */ protected void onCreate() {} /** * In case there is stuff to do right before displaying. */ protected void onShow() {} protected void preShow() { if (root == null) { throw new IllegalStateException("setContentView was not called with a view to display."); } onShow(); if (background == null) { window.setBackgroundDrawable(new BitmapDrawable()); } else { window.setBackgroundDrawable(background); } // if using PopupWindow#setBackgroundDrawable this is the only values of the width and hight that make it work // otherwise you need to set the background of the root viewgroup // and set the popupwindow background to an empty BitmapDrawable window.setWidth(WindowManager.LayoutParams.WRAP_CONTENT); window.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); window.setTouchable(true); window.setFocusable(true); window.setOutsideTouchable(true); window.setContentView(root); } public void setBackgroundDrawable(Drawable background) { this.background = background; } /** * Sets the content view. Probably should be called from {@link onCreate} * * @param root * the view the popup will display */ public void setContentView(View root) { this.root = root; window.setContentView(root); } /** * Will inflate and set the view from a resource id * * @param layoutResID */ public void setContentView(int layoutResID) { LayoutInflater inflator = (LayoutInflater) anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); setContentView(inflator.inflate(layoutResID, null)); } /** * If you want to do anything when {@link dismiss} is called * * @param listener */ public void setOnDismissListener(PopupWindow.OnDismissListener listener) { window.setOnDismissListener(listener); } /** * Displays like a popdown menu from the anchor view */ public void showDropDown() { showDropDown(0, 0); } /** * Displays like a popdown menu from the anchor view. * * @param xOffset * offset in X direction * @param yOffset * offset in Y direction */ public void showDropDown(int xOffset, int yOffset) { preShow(); window.setAnimationStyle(R.style.Animations_PopDownMenu_Left); window.showAsDropDown(anchor, xOffset, yOffset); } /** * Displays like a QuickAction from the anchor view. */ public void showLikeQuickAction() { showLikeQuickAction(0, 0); } /** * Displays like a QuickAction from the anchor view. * * @param xOffset * offset in the X direction * @param yOffset * offset in the Y direction */ public void showLikeQuickAction(int xOffset, int yOffset) { preShow(); window.setAnimationStyle(R.style.Animations_PopUpMenu_Center); int[] location = new int[2]; anchor.getLocationOnScreen(location); Rect anchorRect = new Rect(location[0], location[1], location[0] + anchor.getWidth(), location[1] + anchor.getHeight()); root.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); root.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); int rootWidth = root.getMeasuredWidth(); int rootHeight = root.getMeasuredHeight(); int screenWidth = windowManager.getDefaultDisplay().getWidth(); //int screenHeight = windowManager.getDefaultDisplay().getHeight(); int xPos = ((screenWidth - rootWidth) / 2) + xOffset; int yPos = anchorRect.top - rootHeight + yOffset; // display on bottom if (rootHeight > anchorRect.top) { yPos = anchorRect.bottom + yOffset; window.setAnimationStyle(R.style.Animations_PopDownMenu_Center); } window.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos); } public void dismiss() { window.dismiss(); } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.utils; import java.io.IOException; import java.io.InputStream; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; /** * Wrapper against commons http client which is included in android. * Unfortunately it is an older version with an old syntax. Better encapsulate * all everything here to support easier migration. * * @author Florian Maul * */ public class HttpUtils { public static HttpResponse getWebRessource(String url, String user, String password) throws IOException, ClientProtocolException { HttpGet get = new HttpGet(url); HttpClient client = createClient(user, password); return client.execute(get); } public static InputStream getWebRessourceAsStream(String url, String user, String password) throws IOException, ClientProtocolException { return getWebRessource(url, user, password).getEntity().getContent(); } private static HttpClient createClient(String user, String password) { DefaultHttpClient client = new DefaultHttpClient(); if (user != null && user.length() > 0) { Credentials defaultcreds = new UsernamePasswordCredentials(user, password); client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds); } return client; } }
Java
/* * Copyright (C) 2010 Florian Maul * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fmaul.android.cmis.utils; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.client.ClientProtocolException; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.dom4j.io.SAXReader; import android.text.TextUtils; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisProperty; public class FeedUtils { private static final Namespace CMISRA = Namespace.get("http://docs.oasis-open.org/ns/cmis/restatom/200908/"); private static final Namespace CMIS = Namespace.get("http://docs.oasis-open.org/ns/cmis/core/200908/"); private static final QName CMISRA_REPO_INFO = QName.get("repositoryInfo", CMISRA); private static final QName CMIS_REPO_NAME = QName.get("repositoryName", CMIS); private static final QName CMIS_REPO_CAPABILITES = QName.get("capabilities", CMIS); private static final QName CMIS_REPO_ACL_CAPABILITES = QName.get("aclCapability", CMIS); private static final QName CMISRA_COLLECTION_TYPE = QName.get("collectionType", CMISRA); private static final QName CMISRA_URI_TEMPLATE = QName.get("uritemplate", CMISRA); private static final QName CMISRA_TYPE = QName.get("type", CMISRA); private static final QName CMISRA_TEMPLATE = QName.get("template", CMISRA); private static final QName CMISRA_OBJECT = QName.get("object", CMISRA); private static final QName CMISRA_NUMITEMS = QName.get("numItems", CMISRA); private static final QName CMIS_PROPERTIES = QName.get("properties", CMIS); private static final QName CMIS_VALUE = QName.get("value", CMIS); public static Document readAtomFeed(final String feed, final String user, final String password) throws FeedLoadException { Document document = null; try { InputStream is = HttpUtils.getWebRessourceAsStream(feed, user, password); SAXReader reader = new SAXReader(); // dom4j SAXReader document = reader.read(is); // dom4j Document } catch (ClientProtocolException e) { throw new FeedLoadException(e); } catch (IOException e) { throw new FeedLoadException(e); } catch (DocumentException e) { throw new FeedLoadException(e); } catch (Exception e) { throw new FeedLoadException(e); } return document; } public static List<String> getRootFeedsFromRepo(String url, String user, String password) throws Exception { try { Document doc = readAtomFeed(url, user, password); return getWorkspacesFromRepoFeed(doc); } catch (Exception e) { throw new Exception("Wrong Parameters"); } } public static List<String> getWorkspacesFromRepoFeed(Document doc) { List<String> listWorkspace = new ArrayList<String>(2); if (doc != null) { List<Element> workspaces = doc.getRootElement().elements("workspace"); if (workspaces.size() > 0){ for (Element workspace : workspaces) { Element repoInfo = workspace.element(CMISRA_REPO_INFO); Element repoId = repoInfo.element(CMIS_REPO_NAME); listWorkspace.add(repoId.getText()); } } } return listWorkspace; } public static String getCollectionUrlFromRepoFeed(String type, Element workspace) { if (workspace != null) { List<Element> collections = workspace.elements("collection"); for (Element collection : collections) { String currentType = collection.elementText(CMISRA_COLLECTION_TYPE); if (type.equals(currentType.toLowerCase())) { return collection.attributeValue("href"); } } } return ""; } public static int getNumItemsFeed(Document doc) { if (doc != null) { Element numItems = doc.getRootElement().element(CMISRA_NUMITEMS); if (numItems != null){ return Integer.parseInt(numItems.getText()); } } return 0; } public static Element getWorkspace(Document doc, String workspaceName){ List<Element> workspaces = doc.getRootElement().elements("workspace"); Element workspace = null; if (workspaces.size() > 0){ for (Element wSpace : workspaces) { Element repoInfo = wSpace.element(CMISRA_REPO_INFO); Element repoId = repoInfo.element(CMIS_REPO_NAME); if (workspaceName.equals(repoId.getData())){ return workspace = wSpace; } } } else { workspace = null; } return workspace; } public static Element getWorkspace(String workspace, String url, String user, String password) throws Exception { return getWorkspace(readAtomFeed(url, user, password), workspace); } public static String getSearchQueryFeedTitle(String urlTemplate, String query, boolean isExact) { if (isExact){ return getSearchQueryFeedCmisQuery(urlTemplate, "SELECT * FROM cmis:document WHERE cmis:name LIKE '" + query + "'"); } else { return getSearchQueryFeedCmisQuery(urlTemplate, "SELECT * FROM cmis:document WHERE cmis:name LIKE '%" + query + "%'"); } } public static String getSearchQueryFeedFolderTitle(String urlTemplate, String query, boolean isExact) { if (isExact){ return getSearchQueryFeedCmisQuery(urlTemplate, "SELECT * FROM cmis:folder WHERE cmis:name LIKE '" + query + "'"); } else { return getSearchQueryFeedCmisQuery(urlTemplate, "SELECT * FROM cmis:folder WHERE cmis:name LIKE '%" + query + "%'"); } } public static String getSearchQueryFeed(String urlTemplate, String query) { final CharSequence feedUrl = TextUtils.replace(urlTemplate, new String[] { "{q}", "{searchAllVersions}", "{maxItems}", "{skipCount}", "{includeAllowableActions}", "{includeRelationships}" }, new String[] { query, "false", "50", "0", "false", "false" }); return feedUrl.toString(); } public static String getSearchQueryFeedFullText(String urlTemplate, String query) { String[] words = TextUtils.split(query.trim(), "\\s+"); for (int i = 0; i < words.length; i++) { words[i] = "contains ('" + words[i] + "')"; } String condition = TextUtils.join(" AND ", words); return getSearchQueryFeedCmisQuery(urlTemplate, "SELECT * FROM cmis:document WHERE " + condition); } public static String getSearchQueryFeedCmisQuery(String urlTemplate, String cmisQuery) { String encodedCmisQuery=""; try { encodedCmisQuery = URLEncoder.encode(cmisQuery,"iso-8859-1"); } catch (UnsupportedEncodingException e) { encodedCmisQuery = URLEncoder.encode(cmisQuery); } final CharSequence feedUrl = TextUtils.replace(urlTemplate, new String[] { "{q}", "{searchAllVersions}", "{maxItems}", "{skipCount}", "{includeAllowableActions}", "{includeRelationships}" }, new String[] { encodedCmisQuery, "false", "50", "0", "false", "false" }); return feedUrl.toString(); } public static String getUriTemplateFromRepoFeed(String type, Element workspace) { List<Element> templates = workspace.elements(CMISRA_URI_TEMPLATE); for (Element template : templates) { String currentType = template.elementText(CMISRA_TYPE); if (type.equals(currentType.toLowerCase())) { return template.elementText(CMISRA_TEMPLATE); } } return null; } public static Map<String, CmisProperty> getCmisPropertiesForEntry(Element feedEntry) { Map<String, CmisProperty> props = new HashMap<String, CmisProperty>(); Element objectElement = feedEntry.element(CMISRA_OBJECT); if (objectElement != null) { Element properitesElement = objectElement.element(CMIS_PROPERTIES); if (properitesElement != null) { List<Element> properties = properitesElement.elements(); for (Element property : properties) { final String id = property.attributeValue("propertyDefinitionId"); props.put(id, new CmisProperty( property.getName(), id, property.attributeValue("localName"), property.attributeValue("displayName"), property.elementText(CMIS_VALUE)) ); } } } return props; } public static Map<String, ArrayList<CmisProperty>> getCmisRepositoryProperties(Element feedEntry) { Map<String, ArrayList<CmisProperty>> infoServerList = new HashMap<String, ArrayList<CmisProperty>>(); ArrayList<CmisProperty> propsList = new ArrayList<CmisProperty>(); ArrayList<CmisProperty> propsCapabilities = new ArrayList<CmisProperty>(); ArrayList<CmisProperty> propsACLCapabilities = new ArrayList<CmisProperty>(); Element objectElement = feedEntry.element(CMISRA_REPO_INFO); if (objectElement != null) { List<Element> properties = objectElement.elements(); for (Element property : properties) { if (CMIS_REPO_CAPABILITES.equals(property.getQName())) { List<Element> props = property.elements(); for (Element prop : props) { propsCapabilities.add(new CmisProperty(null, null, null, prop.getName().replace("capability", ""), prop.getText())); } } else if (CMIS_REPO_ACL_CAPABILITES.equals(property.getQName())) { /*List<Element> props = property.elements(); for (Element prop : props) { propsACLCapabilities.add(new CmisProperty(null, null, null, prop.getName().replace("cmis:", ""), prop.getText())); }*/ } else { propsList.add(new CmisProperty(null, null, null, property.getName(), property.getText())); } } infoServerList.put(Server.INFO_GENERAL, propsList); infoServerList.put(Server.INFO_CAPABILITIES, propsCapabilities); infoServerList.put(Server.INFO_ACL_CAPABILITIES, propsACLCapabilities); } return infoServerList; } }
Java