code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
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); } } }
0xsleizer-kianxali
src/kianxali/decoder/arch/x86/X86Context.java
Java
gpl3
6,287
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(); } }
0xsleizer-kianxali
src/kianxali/decoder/arch/x86/Prefix.java
Java
gpl3
1,375
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; } }
0xsleizer-kianxali
src/kianxali/decoder/arch/x86/X86Instruction.java
Java
gpl3
20,087
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); }
0xsleizer-kianxali
src/kianxali/decoder/Decoder.java
Java
gpl3
476
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); }
0xsleizer-kianxali
src/kianxali/decoder/Operand.java
Java
gpl3
956
package kianxali.decoder; /** * This interface is used to tag enumerations that represent CPU registers * @author fwi * */ public interface Register { }
0xsleizer-kianxali
src/kianxali/decoder/Register.java
Java
gpl3
159
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); }
0xsleizer-kianxali
src/kianxali/disassembler/DataListener.java
Java
gpl3
579
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); }
0xsleizer-kianxali
src/kianxali/disassembler/InstructionVisitor.java
Java
gpl3
531
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; } }
0xsleizer-kianxali
src/kianxali/disassembler/DataEntry.java
Java
gpl3
5,603
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(); }
0xsleizer-kianxali
src/kianxali/disassembler/DisassemblyListener.java
Java
gpl3
648
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(); } }
0xsleizer-kianxali
src/kianxali/disassembler/Function.java
Java
gpl3
1,434
/** * 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;
0xsleizer-kianxali
src/kianxali/disassembler/package-info.java
Java
gpl3
513
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); } } } }
0xsleizer-kianxali
src/kianxali/disassembler/DisassemblyData.java
Java
gpl3
10,431
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); }
0xsleizer-kianxali
src/kianxali/disassembler/AddressNameListener.java
Java
gpl3
384
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()); } } }
0xsleizer-kianxali
src/kianxali/disassembler/Disassembler.java
Java
gpl3
20,171
/* * 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; } }
10hc-ml-wolves
trunk/Source/KMean/src/untils/DoiTuong.java
Java
gpl3
2,663
/* * 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; } }
10hc-ml-wolves
trunk/Source/KMean/src/untils/PhanLop.java
Java
gpl3
4,435
/* * 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; } }
10hc-ml-wolves
trunk/Source/KMean/src/untils/Nhom.java
Java
gpl3
1,836
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; } }
10hc-ml-wolves
trunk/Source/KMean/src/untils/ExampleFileFilter.java
Java
gpl3
2,812
/* * 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 }
10hc-ml-wolves
trunk/Source/KMean/src/kmean/jfMain.java
Java
gpl3
10,929
/* * 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; } }
10hc-ml-wolves
trunk/Source/KMean/src/kmean/KMean.java
Java
gpl3
1,120
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); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/Part.java
Java
epl
595
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); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/PartString.java
Java
epl
641
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){} }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/BonusPause.java
Java
epl
1,338
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; } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/BonusRewind.java
Java
epl
956
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; } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/BonusTorpedo.java
Java
epl
686
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; } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/Level.java
Java
epl
3,119
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; } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/BonusFactory.java
Java
epl
645
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(); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/ProgBob4.java
Java
epl
51,011
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; } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/AbstractBonus.java
Java
epl
1,735
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; }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/Item.java
Java
epl
233
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); }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/AbstractParser.java
Java
epl
567
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; }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/Bubble.java
Java
epl
308
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(); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/ProgBob2.java
Java
epl
55,814
package game.tests; public class IEventHandler { }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/IEventHandler.java
Java
epl
58
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 } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/AbstractGameState.java
Java
epl
1,377
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); }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/AbstractTransition.java
Java
epl
732
package game.tests; public class GameManager { }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/GameManager.java
Java
epl
56
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()); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/TxtParserTest.java
Java
epl
382
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); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/ExampleTransition.java
Java
epl
450
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){ } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/ExampleGameState.java
Java
epl
816
package game.tests; public class GameLoop { }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/tests/GameLoop.java
Java
epl
53
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; } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/BonusSmRocks.java
Java
epl
854
package game; public class PathPoint { double x; double y; double dist_to_next; }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/PathPoint.java
Java
epl
95
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); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/PartBub.java
Java
epl
419
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(); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/progbobcommented.java
Java
epl
71,529
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(); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/BubblefishBob.java
Java
epl
888
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(); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/ProgBob1.java
Java
epl
54,918
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(); } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/ProgBob.java
Java
epl
51,539
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; } }
108bubblefishcode-conradshun
trunk/ 108bubblefishcode-conradshun/spring11_cps108_06_bubblefish/game/TxtParser.java
Java
epl
3,002
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()]); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/FileChooserActivity.java
Java
asf20
19,767
/* * 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()))); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/FavoriteAdapter.java
Java
asf20
2,639
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisRepository.java
Java
asf20
11,066
/* * 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]; } }; }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisProperty.java
Java
asf20
4,220
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisItem.java
Java
asf20
3,707
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/DownloadItem.java
Java
asf20
2,127
/* * 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 }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/QueryType.java
Java
asf20
728
/* * 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()); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisItemLazy.java
Java
asf20
3,156
/* * 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 ""; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisTypeDefinition.java
Java
asf20
4,874
/* * 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"; }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisModel.java
Java
asf20
974
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisItemCollection.java
Java
asf20
1,766
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisPropertyFilter.java
Java
asf20
8,369
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/repo/CmisPropertyTypeDefinition.java
Java
asf20
3,103
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/IntentResult.java
Java
asf20
1,325
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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/ActionItem.java
Java
asf20
1,488
/* * 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); } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/IntentIntegrator.java
Java
asf20
12,713
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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/StorageException.java
Java
asf20
332
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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/QuickAction.java
Java
asf20
7,957
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(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/UIUtils.java
Java
asf20
4,308
/* * 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; } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/StorageUtils.java
Java
asf20
8,436
/* * 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; }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/FeedLoadException.java
Java
asf20
1,033
/* * 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; } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/FileSystemUtils.java
Java
asf20
2,357
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 ""; } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/MimetypeUtils.java
Java
asf20
6,512
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(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/CustomPopupWindow.java
Java
asf20
5,763
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/HttpUtils.java
Java
asf20
2,215
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/FeedUtils.java
Java
asf20
10,321
/* * Copyright (C) 2010 Florian Maul & 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 java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.DocumentDetailsActivity; import de.fmaul.android.cmis.ListCmisFeedActivity; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.asynctask.AbstractDownloadTask; import de.fmaul.android.cmis.asynctask.ItemPropertiesDisplayTask; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.FavoriteDAO; import de.fmaul.android.cmis.database.SearchDAO; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.repo.CmisPropertyFilter; import de.fmaul.android.cmis.repo.CmisRepository; public class ActionUtils { public static void openDocument(final Activity contextActivity, final CmisItemLazy item) { try { File content = getItemFile(contextActivity, contextActivity.getIntent().getStringExtra("workspace"), item); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())){ viewFileInAssociatedApp(contextActivity, content, item.getMimeType()); } else { confirmDownload(contextActivity, item, true); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void openWithDocument(final Activity contextActivity, final CmisItemLazy item) { try { File content = getItemFile(contextActivity, contextActivity.getIntent().getStringExtra("workspace"), item); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())){ openWith(contextActivity, content); } else { confirmDownload(contextActivity, item, false); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } private static void openWith(final Activity contextActivity, final File tempFile){ CharSequence[] cs = MimetypeUtils.getOpenWithRowsLabel(contextActivity); AlertDialog.Builder builder = new AlertDialog.Builder(contextActivity); builder.setTitle(R.string.open_with_title); builder.setSingleChoiceItems(cs, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { viewFileInAssociatedApp(contextActivity, tempFile, MimetypeUtils.getDefaultMimeType().get(which)); dialog.dismiss(); } }); builder.setNegativeButton(contextActivity.getText(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } private static void startDownload(final Activity contextActivity, final CmisItemLazy item, final boolean openAutomatic){ new AbstractDownloadTask(getRepository(contextActivity), contextActivity) { @Override public void onDownloadFinished(File contentFile) { if (contentFile != null && contentFile.exists()) { if (openAutomatic){ viewFileInAssociatedApp(contextActivity, contentFile, item.getMimeType()); } else { openWith(contextActivity, contentFile); } } else { displayMessage(contextActivity, R.string.error_file_does_not_exists); } } }.execute(item); } private static void confirmDownloadBackground(final Activity contextActivity, final CmisItemLazy item) { if (getPrefs(contextActivity).isConfirmDownload() && Integer.parseInt(item.getSize()) > convertSizeToKb(getPrefs(contextActivity).getDownloadFileSize())) { AlertDialog.Builder builder = new AlertDialog.Builder(contextActivity); builder.setMessage( contextActivity.getText(R.string.confirm_donwload) + " " + convertAndFormatSize(contextActivity, item.getSize()) + " " + contextActivity.getText(R.string.confirm_donwload2) ) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { NotificationUtils.downloadNotification(contextActivity); startDownloadBackground(contextActivity, item); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } else { startDownloadBackground(contextActivity, item); } } private static void startDownloadBackground(final Activity contextActivity, final CmisItemLazy item){ new AbstractDownloadTask(getRepository(contextActivity), contextActivity, true) { @Override public void onDownloadFinished(File contentFile) { if (contentFile != null && contentFile.exists()) { NotificationUtils.downloadNotification(contextActivity, contentFile, item.getMimeType()); } else { NotificationUtils.cancelDownloadNotification(contextActivity); //displayMessage(contextActivity, R.string.error_file_does_not_exists); } } }.execute(item); } private static void confirmDownload(final Activity contextActivity, final CmisItemLazy item, final boolean notification) { if (getPrefs(contextActivity).isConfirmDownload() && Integer.parseInt(item.getSize()) > convertSizeToKb(getPrefs(contextActivity).getDownloadFileSize())) { AlertDialog.Builder builder = new AlertDialog.Builder(contextActivity); builder.setMessage( contextActivity.getText(R.string.confirm_donwload) + " " + convertAndFormatSize(contextActivity, item.getSize()) + " " + contextActivity.getText(R.string.confirm_donwload2) ) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { startDownload(contextActivity, item, true); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } else { startDownload(contextActivity, item, true); } } public static void displayMessage(Activity contextActivity, int messageId) { Toast.makeText(contextActivity, messageId, Toast.LENGTH_LONG).show(); } public static void displayMessage(Activity contextActivity, String messageId) { Toast.makeText(contextActivity, messageId, Toast.LENGTH_LONG).show(); } public static void viewFileInAssociatedApp(final Activity contextActivity, final File tempFile, String mimeType) { Intent viewIntent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.fromFile(tempFile); //viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewIntent.setDataAndType(data, mimeType.toLowerCase()); try { contextActivity.startActivity(viewIntent); } catch (ActivityNotFoundException e) { //Toast.makeText(contextActivity, R.string.application_not_available, Toast.LENGTH_SHORT).show(); openWith(contextActivity, tempFile); } } public static void saveAs(final Activity contextActivity, final String workspace, final CmisItemLazy item){ try { File content = item.getContentDownload(contextActivity.getApplication(), ((CmisApp) contextActivity.getApplication()).getPrefs().getDownloadFolder()); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())){ viewFileInAssociatedApp(contextActivity, content, item.getMimeType()); } else { File cacheContent = item.getContent(contextActivity.getApplication(), workspace); if (cacheContent != null && cacheContent.length() > 0 && cacheContent.length() == Long.parseLong(item.getSize())){ //TODO AsyncTask ProgressDialog pg = ProgressDialog.show(contextActivity, "", contextActivity.getText(R.string.loading), true, true); StorageUtils.copy(cacheContent, content); pg.dismiss(); viewFileInAssociatedApp(contextActivity, cacheContent, item.getMimeType()); } else { confirmDownloadBackground(contextActivity, item); } } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void shareDocument(final Activity activity, final String workspace, final CmisItemLazy item) { try { File content = getItemFile(activity, workspace, item); if (item.getMimeType().length() == 0){ shareFileInAssociatedApp(activity, content, item); //} else if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())) { // shareFileInAssociatedApp(contextActivity, content, item); } else { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(activity.getText(R.string.share_question)).setCancelable(true) .setPositiveButton(activity.getText(R.string.share_link), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { shareFileInAssociatedApp(activity, null, item); } }).setNegativeButton(activity.getText(R.string.share_content), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { File content = getItemFile(activity, workspace, item); if (content != null) { shareFileInAssociatedApp(activity, content, item); } else { new AbstractDownloadTask(getRepository(activity), activity) { @Override public void onDownloadFinished(File contentFile) { shareFileInAssociatedApp(activity, contentFile, item); } }.execute(item); } } catch (StorageException e) { displayMessage(activity, R.string.generic_error); } } }); AlertDialog alert = builder.create(); alert.show(); } } catch (Exception e) { displayMessage(activity, R.string.generic_error); } } private static void shareFileInAssociatedApp(Activity contextActivity, File contentFile, CmisItemLazy item) { shareFileInAssociatedApp(contextActivity, contentFile, item, item.getMimeType()); } private static void shareFileInAssociatedApp(Activity contextActivity, File contentFile, CmisItemLazy item, String mimetype) { Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_SUBJECT, item.getTitle()); if (contentFile != null && contentFile.exists()){ i.putExtra(Intent.EXTRA_TEXT, item.getContentUrl()); i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(contentFile)); i.setType(mimetype); } else { i.putExtra(Intent.EXTRA_TEXT, item.getSelfUrl()); i.setType("text/plain"); } contextActivity.startActivity(Intent.createChooser(i, contextActivity.getText(R.string.share))); } private static File getItemFile(final Activity contextActivity, final String workspace, final CmisItemLazy item) throws StorageException{ File content = item.getContent(contextActivity.getApplication(), workspace); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())) { return content; } content = item.getContentDownload(contextActivity.getApplication(), ((CmisApp) contextActivity.getApplication()).getPrefs().getDownloadFolder()); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())) { return content; } return null; } public static void createFavorite(Activity activity, Server server, CmisItemLazy item){ Database database = null; try { database = Database.create(activity); FavoriteDAO favDao = new FavoriteDAO(database.open()); long result = 1L; if (favDao.isPresentByURL(item.getSelfUrl()) == false){ String mimetype = ""; if (item.getMimeType() == null || item.getMimeType().length() == 0){ mimetype = item.getBaseType(); } else { mimetype = item.getMimeType(); } result = favDao.insert(item.getTitle(), item.getSelfUrl(), server.getId(), mimetype); if (result == -1){ Toast.makeText(activity, R.string.favorite_create_error, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, R.string.favorite_create, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(activity, R.string.favorite_present, Toast.LENGTH_LONG).show(); } } catch (Exception e) { displayMessage(activity, R.string.generic_error); for (int i = 0; i < e.getStackTrace().length; i++) { Log.d("CmisRepository", e.getStackTrace()[i].toString()); } } finally { if (database != null){ database.close(); } } } public static void createSaveSearch(Activity activity, Server server, String name, String url){ Database database = null; try { database = Database.create(activity); SearchDAO searchDao = new SearchDAO(database.open()); long result = 1L; if (searchDao.isPresentByURL(url) == false){ Log.d("CmisRepository", name + " - " + url + " - " + server.getId()); result = searchDao.insert(name, url, server.getId()); if (result == -1){ Toast.makeText(activity, R.string.saved_search_create_error, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, R.string.saved_search_create, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(activity, R.string.saved_search_present, Toast.LENGTH_LONG).show(); } } catch (Exception e) { displayMessage(activity, R.string.generic_error); for (int i = 0; i < e.getStackTrace().length; i++) { Log.d("CmisRepository", e.getStackTrace()[i].toString()); } } finally { if (database != null){ database.close(); } } } public static void displayDocumentDetails(Activity activity, CmisItem doc) { displayDocumentDetails(activity, getRepository(activity).getServer(), doc); } public static void displayDocumentDetails(Activity activity, Server server, CmisItem doc) { try { ((CmisApp) activity.getApplication()).setCmisPropertyFilter(null); Intent intent =getDocumentDetailsIntent(activity, server, doc); activity.startActivity(intent); } catch (Exception e) { displayMessage(activity, R.string.generic_error); } } public static Intent getDocumentDetailsIntent(Activity activity, Server server, CmisItem doc) { try { Intent intent = new Intent(activity, DocumentDetailsActivity.class); ArrayList<CmisProperty> propList = new ArrayList<CmisProperty>(doc.getProperties().values()); intent.putParcelableArrayListExtra("properties", propList); intent.putExtra("workspace", server.getWorkspace()); intent.putExtra("objectTypeId", doc.getProperties().get("cmis:objectTypeId").getValue()); intent.putExtra("baseTypeId", doc.getProperties().get("cmis:baseTypeId").getValue()); intent.putExtra("item", new CmisItemLazy(doc)); return intent; } catch (Exception e) { return null; } } private static int convertSizeToKb(String size){ return Integer.parseInt(size) * 1024; } public static String convertAndFormatSize(Activity activity, String size) { int sizeInByte = Integer.parseInt(size); return convertAndFormatSize(activity, sizeInByte); } public static String convertAndFormatSize(Activity activity, int sizeInByte) { if (sizeInByte < 1024) { return String.valueOf(sizeInByte) + " " + activity.getText(R.string.file_size_bytes); } else { int sizeInKB = sizeInByte / 1024; if (sizeInKB < 1024) { return String.valueOf(sizeInKB) + " " + activity.getText(R.string.file_size_kilobytes); } else { int sizeInMB = sizeInKB / 1024; if (sizeInMB < 1024) { return String.valueOf(sizeInMB) + " " + activity.getText(R.string.file_size_megabytes); } else { return String.valueOf(sizeInMB / 1024) + " " + activity.getText(R.string.file_size_gigabytes); } } } } public static void openNewListViewActivity(Activity activity, CmisItem item) { openNewListViewActivity(activity, new CmisItemLazy(item)); } public static void openNewListViewActivity(Activity activity, CmisItemLazy item) { Intent intent = new Intent(activity, ListCmisFeedActivity.class); if (item != null){ intent.putExtra("item", item); } else { intent.putExtra("title", getRepository(activity).getServer().getName()); } activity.startActivity(intent); } public static void openDocument(final Activity contextActivity, final File content) { try { if (content != null && content.length() > 0 ){ viewFileInAssociatedApp(contextActivity, content, MimetypeUtils.getMimetype(contextActivity, content)); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void openWithDocument(final Activity contextActivity, final File content) { try { if (content != null && content.length() > 0){ openWith(contextActivity, content); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void shareFileInAssociatedApp(Activity contextActivity, File contentFile) { Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_SUBJECT, contentFile.getName()); i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(contentFile)); i.setType(MimetypeUtils.getMimetype(contextActivity, contentFile)); contextActivity.startActivity(Intent.createChooser(i, contextActivity.getText(R.string.share))); } public static void initPrefs(Activity activity) { SharedPreferences sharePrefs = PreferenceManager.getDefaultSharedPreferences(activity); ArrayList<Boolean> quickActionsServer = new ArrayList<Boolean>(6); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_open).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_info).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_edit).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_favorite).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_search).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_delete).toString(), true)); ((CmisApp) activity.getApplication()).setPrefs( new Prefs( Integer.parseInt(sharePrefs.getString("default_view", "1")), sharePrefs.getString(activity.getText(R.string.cmis_dlfolder).toString(), "/sdcard/Download"), sharePrefs.getBoolean(activity.getText(R.string.cmis_scan).toString(), true), sharePrefs.getBoolean(activity.getText(R.string.cmis_download).toString(), true), sharePrefs.getString(activity.getText(R.string.cmis_download_size).toString(), "100"), quickActionsServer ) ); } private static CmisRepository getRepository(Activity activity) { return ((CmisApp) activity.getApplication()).getRepository(); } private static Prefs getPrefs(Activity activity) { return ((CmisApp) activity.getApplication()).getPrefs(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/ActionUtils.java
Java
asf20
21,023
package de.fmaul.android.cmis.utils; import java.io.File; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.RemoteViews; import de.fmaul.android.cmis.DownloadProgressActivity; import de.fmaul.android.cmis.HomeActivity; import de.fmaul.android.cmis.R; public class NotificationUtils { public static final int DOWNLOAD_ID = 3313; public static void downloadNotification(Activity activity, File contentFile, String mimetype){ NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.cmisexplorer, activity.getText(R.string.notif_download_finish), System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL; Intent viewIntent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.fromFile(contentFile); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewIntent.setDataAndType(data, mimetype.toLowerCase()); PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, viewIntent, 0); String titreNotification = activity.getText(R.string.notif_download_title).toString(); String texteNotification = activity.getText(R.string.notif_download_texte) + contentFile.getName(); notification.setLatestEventInfo(activity, titreNotification, texteNotification, pendingIntent); notificationManager.notify(DOWNLOAD_ID, notification); } public static void downloadNotification(Activity activity){ NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.cmisexplorer, activity.getText(R.string.download_progress), System.currentTimeMillis()); Intent viewIntent = new Intent(activity, DownloadProgressActivity.class); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, viewIntent, 0); String titreNotification = activity.getText(R.string.download_progress).toString(); String texteNotification = activity.getText(R.string.notif_open).toString(); notification.setLatestEventInfo(activity, titreNotification, texteNotification, pendingIntent); notificationManager.notify(DOWNLOAD_ID, notification); } public static void cancelDownloadNotification(Activity contextActivity){ NotificationManager notificationManager = (NotificationManager) contextActivity.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(DOWNLOAD_ID); } public static void updateDownloadNotification(Activity activity, String message){ NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.cmisexplorer, activity.getText(R.string.download_progress), System.currentTimeMillis()); Intent viewIntent = new Intent(activity, DownloadProgressActivity.class); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, viewIntent, 0); String titreNotification = activity.getText(R.string.download_progress).toString(); String texteNotification = message; notification.setLatestEventInfo(activity, titreNotification, texteNotification, pendingIntent); notificationManager.notify(DOWNLOAD_ID, notification); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/NotificationUtils.java
Java
asf20
3,664
/* * Copyright (C) 2010 Florian Maul & 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.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import de.fmaul.android.cmis.repo.CmisProperty; public class ListUtils { public static List<Map<String, ?>> buildListOfNameValueMaps(List<CmisProperty> propList) { List<Map<String, ?>> list = new ArrayList<Map<String, ?>>(); for (CmisProperty cmisProperty : propList) { list.add(createPair(cmisProperty.getDisplayName(), cmisProperty.getValue())); } return list; } public static Map<String, ?> createPair(String name, String value) { HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("name", name); hashMap.put("value", value); return hashMap; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/utils/ListUtils.java
Java
asf20
1,400
/* * 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; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import de.fmaul.android.cmis.asynctask.FeedDisplayTask; import de.fmaul.android.cmis.asynctask.FeedItemDisplayTask; import de.fmaul.android.cmis.asynctask.ServerInitTask; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.QueryType; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.FeedUtils; import de.fmaul.android.cmis.utils.IntentIntegrator; import de.fmaul.android.cmis.utils.IntentResult; import de.fmaul.android.cmis.utils.StorageUtils; import de.fmaul.android.cmis.utils.UIUtils; public class ListCmisFeedActivity extends ListActivity { private static final String TAG = "ListCmisFeedActivity"; private List<String> workspaces; private CharSequence[] cs; private Context context = this; private ListActivity activity = this; private OnSharedPreferenceChangeListener listener; private CmisItemLazy item; private CmisItemLazy itemParent; private CmisItemCollection items; private GridView gridview; private ListView listView; private Prefs prefs; private ArrayList<CmisItemLazy> currentStack = new ArrayList<CmisItemLazy>(); private ListCmisFeedActivitySave save; private boolean firstStart = false; protected static final int REQUEST_CODE_FAVORITE = 1; /** * Contains the current connection information and methods to access the * CMIS repository. */ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (activityIsCalledWithSearchAction()){ Intent intent = new Intent(this, SearchActivity.class); intent.putExtras(getIntent()); Server s = getRepository().getServer(); intent.putExtra("server", s); intent.putExtra("title", s.getName()); this.finish(); startActivity(intent); } else { initWindow(); initActionIcon(); Bundle extra = this.getIntent().getExtras(); if (extra != null && extra.getBoolean("isFirstStart")) { firstStart = true; } //Restart if (getLastNonConfigurationInstance() != null ){ save = (ListCmisFeedActivitySave) getLastNonConfigurationInstance(); this.item = save.getItem(); this.itemParent = save.getItemParent(); this.items = save.getItems(); this.currentStack = save.getCurrentStack(); firstStart = false; new FeedDisplayTask(this, getRepository(), null, item, items).execute(); } if (initRepository() == false){ processSearchOrDisplayIntent(); } //Filter Management listener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (prefs.getBoolean(activity.getString(R.string.cmis_repo_params), false)){ getRepository().generateParams(activity); } } }; PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(listener); //Set Default Breadcrumbs ((TextView) activity.findViewById(R.id.path)).setText("/"); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK){ this.finish(); return true; } return super.onKeyDown(keyCode, event); } @Override public Object onRetainNonConfigurationInstance() { if (item == null){ item = getRepository().getRootItem(); itemParent = item; currentStack.add(item); } return new ListCmisFeedActivitySave(item, itemParent, getItems(), currentStack); } @Override protected void onDestroy() { if (activityIsCalledWithSearchAction() == false){ setSaveContext(null); } super.onDestroy(); } private void initActionIcon() { Button home = (Button) findViewById(R.id.home); Button up = (Button) findViewById(R.id.up); Button back = (Button) findViewById(R.id.back); Button next = (Button) findViewById(R.id.next); Button refresh = (Button) findViewById(R.id.refresh); Button filter = (Button) findViewById(R.id.preference); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); Intent intent = new Intent(activity, HomeActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); up.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { goUP(false); } }); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getRepository().generateParams(activity, false); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), item).execute(item.getDownLink()); } }); next.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (item == null) { item = getRepository().getRootItem(); } getRepository().generateParams(activity, true); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), item).execute(item.getDownLink()); } }); filter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(activity, CmisFilterActivity.class)); } }); refresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { refresh(); } }); } private boolean initRepository() { boolean init = true; try { if (getRepository() == null) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { // Case if we change repository. if (firstStart) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { init = false; } } } catch (FeedLoadException fle) { ActionUtils.displayMessage(activity, R.string.generic_error); } return init; } public void processSearchOrDisplayIntent() { if (getRepository() != null) { //if (activityIsCalledWithSearchAction()) { // doSearchWithIntent(getIntent()); //} else { // Start this activity from favorite Bundle extras = getIntent().getExtras(); if (extras != null) { if (extras.get("item") != null) { item = (CmisItemLazy) extras.get("item"); } } new FeedDisplayTask(this, getRepository(), item).execute(item.getDownLink()); //} } else { Toast.makeText(this, getText(R.string.error_repo_connexion), 5); } } /** * The type of the query is passed by the SearchManager through a bundle in * the search intent. * * @param intent * @return */ /*private QueryType getQueryTypeFromIntent(Intent intent) { Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { String queryType = appData.getString(QueryType.class.getName()); return QueryType.valueOf(queryType); } return QueryType.FULLTEXT; }*/ /** * Tests if this activity is called with a Search intent. * * @return */ private boolean activityIsCalledWithSearchAction() { final String queryAction = getIntent().getAction(); return Intent.ACTION_SEARCH.equals(queryAction); } /** * Initialize the window and the activity. */ private void initWindow() { setRequestedOrientation(getResources().getConfiguration().orientation); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.feed_list_main); gridview = (GridView) activity.findViewById(R.id.gridview); listView = activity.getListView(); prefs = ((CmisApp) activity.getApplication()).getPrefs(); gridview.setOnItemClickListener(new CmisDocSelectedListener()); gridview.setTextFilterEnabled(true); gridview.setClickable(true); gridview.setOnCreateContextMenuListener(this); listView.setTextFilterEnabled(true); listView.setItemsCanFocus(true); listView.setClickable(true); listView.setOnItemClickListener(new CmisDocSelectedListener()); listView.setOnCreateContextMenuListener(this); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); UIUtils.createContextMenu(activity, menu, menuInfo); } @Override public boolean onContextItemSelected(MenuItem menuItem) { return UIUtils.onContextItemSelected(this, menuItem, prefs); } protected void reload(String workspace) { Intent intent = new Intent(this, ListCmisFeedActivity.class); intent.putExtra("EXIT", true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("isFirstStart", true); Server s = getRepository().getServer(); if (workspace != null){ s.setWorkspace(workspace); } intent.putExtra("server", s); intent.putExtra("title",s.getName()); this.finish(); startActivity(intent); } private void refresh() { if (item == null){ item = getRepository().getRootItem(); } getRepository().generateParams(activity, false); try { if (StorageUtils.deleteFeedFile(getApplication(), getRepository().getServer().getWorkspace(), item.getDownLink())){ new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), item).execute(item.getDownLink()); } else { displayError(R.string.application_not_available); } } catch (Exception e) { e.printStackTrace(); } } protected void restart(String workspace) { reload(workspace); } protected void restart() { reload(null); } private void displayError(int messageId) { Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); } /** * Listener that is called whenever a user clicks on a file or folder in the * list. */ private class CmisDocSelectedListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CmisItem doc = (CmisItem) parent.getItemAtPosition(position); if (activityIsCalledWithSearchAction()){ if (doc.hasChildren()) { ActionUtils.openNewListViewActivity(activity, doc); } else { ActionUtils.displayDocumentDetails(activity, getRepository().getServer(), doc); } } else { if (doc.hasChildren()) { if (getRepository().isPaging()) { getRepository().setSkipCount(0); getRepository().generateParams(activity); } if (item == null || currentStack.size() == 0) { item = getRepository().getRootItem(); currentStack.add(item); } currentStack.add(doc); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), doc).execute(doc.getDownLink()); itemParent = item; item = doc; } else { ActionUtils.displayDocumentDetails(ListCmisFeedActivity.this, doc); } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.add(Menu.NONE, 1, 0, R.string.menu_item_add_favorite); item.setIcon(R.drawable.favorite); createRepoMenu(menu); UIUtils.createSearchMenu(menu); createToolsMenu(menu); item = menu.add(Menu.NONE, 3, 0, R.string.menu_item_about); item.setIcon(R.drawable.cmisexplorer); item = menu.add(Menu.NONE, 11, 0, R.string.menu_item_view); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ item.setIcon(R.drawable.viewlisting); } else { item.setIcon(R.drawable.viewicons); } return true; } private void createRepoMenu(Menu menu) { SubMenu settingsMenu = menu.addSubMenu(R.string.menu_item_settings); settingsMenu.setIcon(R.drawable.repository); settingsMenu.setHeaderIcon(android.R.drawable.ic_menu_info_details); settingsMenu.add(Menu.NONE, 7, 0, R.string.menu_item_settings_reload); settingsMenu.add(Menu.NONE, 8, 0, R.string.menu_item_settings_repo); settingsMenu.add(Menu.NONE, 9, 0, R.string.menu_item_settings_ws); } private void createToolsMenu(Menu menu) { SubMenu toolsMenu = menu.addSubMenu(R.string.menu_item_tools); toolsMenu.setIcon(R.drawable.tools); toolsMenu.setHeaderIcon(android.R.drawable.ic_menu_info_details); if (getCmisPrefs().isEnableScan()){ toolsMenu.add(Menu.NONE, 10, 0, R.string.menu_item_scanner); } toolsMenu.add(Menu.NONE, 12, 0, R.string.menu_item_download_manager); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: Intent intent = new Intent(this, FavoriteActivity.class); intent.putExtra("server", getRepository().getServer()); startActivity(intent); return true; case 3: startActivity(new Intent(this, AboutActivity.class)); return true; case 20: onSearchRequested(QueryType.TITLE); return true; case 21: onSearchRequested(QueryType.FOLDER); return true; case 22: onSearchRequested(QueryType.FULLTEXT); return true; case 23: onSearchRequested(QueryType.CMISQUERY); return true; case 24: Intent intents = new Intent(this, SavedSearchActivity.class); intents.putExtra("server", getRepository().getServer()); startActivity(intents); return true; case 7: restart(); return true; case 8: startActivity(new Intent(this, ServerActivity.class)); return true; case 9: chooseWorkspace(); return true; case 10: IntentIntegrator.initiateScan(this); return true; case 11: if(prefs.getDataView() == Prefs.GRIDVIEW){ prefs.setDataView(Prefs.LISTVIEW); } else { prefs.setDataView(Prefs.GRIDVIEW); } refresh(); return true; case 12: startActivity(new Intent(this, DownloadProgressActivity.class)); return true; } return false; } private void chooseWorkspace(){ try { Server server = getRepository().getServer(); workspaces = FeedUtils.getRootFeedsFromRepo(server.getUrl(), server.getUsername(), server.getPassword()); cs = workspaces.toArray(new CharSequence[workspaces.size()]); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.cmis_repo_choose_workspace); builder.setSingleChoiceItems(cs, workspaces.indexOf(server.getWorkspace()) ,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { dialog.dismiss(); restart(cs[item].toString()); } }); AlertDialog alert = builder.create(); alert.show(); } catch (Exception e) { Toast.makeText(ListCmisFeedActivity.this, R.string.error_repo_connexion, Toast.LENGTH_LONG).show(); } } public void onActivityResult(int requestCode, int resultCode, Intent intent) { /* super.onActivityResult(requestCode, resultCode, intent); switch (requestCode) { case REQUEST_CODE_FAVORITE: if (resultCode == RESULT_OK && intent != null) { } break; }*/ IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null && scanResult.getContents() != null) if (scanResult.getContents().length() > 0 && scanResult.getContents().contains("http://")) { if ( scanResult.getContents().contains(getRepository().getHostname())){ new FeedItemDisplayTask(activity, getRepository().getServer(), scanResult.getContents()).execute(); } else { ActionUtils.displayMessage(this, R.string.scan_error_repo); } }else { ActionUtils.displayMessage(this, R.string.scan_error_url); } } public void goUP(boolean isBack){ if (activityIsCalledWithSearchAction()){ itemParent = null; currentStack.clear(); } if (item != null && item.getPath() != null && item.getPath().equals("/") == false){ if (getRepository().isPaging()) { getRepository().setSkipCount(0); getRepository().generateParams(activity); } if (itemParent != null) { currentStack.remove(item); item = currentStack.get(currentStack.size()-1); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), itemParent).execute(itemParent.getDownLink()); if (currentStack.size()-2 > 0){ itemParent = currentStack.get(currentStack.size()-2); } else { itemParent = currentStack.get(0); } } else { new FeedItemDisplayTask(activity, getRepository().getServer(), item.getParentUrl(), FeedItemDisplayTask.DISPLAY_FOLDER).execute(); } } else if (isBack) { Intent intent = new Intent(activity, ServerActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } /* * (non-Javadoc) * * @see android.app.Activity#onSearchRequested() */ public boolean onSearchRequested(QueryType queryType) { Bundle appData = new Bundle(); appData.putString(QueryType.class.getName(), queryType.name()); startSearch("", false, appData, false); return true; } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } void setRepository(CmisRepository repo) { ((CmisApp) getApplication()).setRepository(repo); } CmisItemCollection getItems() { return ((CmisApp) getApplication()).getItems(); } void setItems(CmisItemCollection items) { ((CmisApp) getApplication()).setItems(items); } Prefs getCmisPrefs() { return ((CmisApp) getApplication()).getPrefs(); } public CmisItemLazy getItem() { return item; } public void setItem(CmisItemLazy item) { this.item = item; } public ListCmisFeedActivitySave getSaveContext(){ return ((CmisApp) getApplication()).getSavedContextItems(); } public void setSaveContext(ListCmisFeedActivitySave save){ ((CmisApp) getApplication()).setSavedContextItems(save); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/ListCmisFeedActivity.java
Java
asf20
19,569
/* * 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; import java.util.ArrayList; public class Prefs { public static final int LISTVIEW = 1; public static final int GRIDVIEW = 2; private int dataView; private String downloadFolder; private boolean enableScan; private boolean confirmDownload; private String downloadFileSize; private ArrayList<Boolean> quickActionServer; public Prefs(int dataView) { super(); this.dataView = dataView; } public Prefs( int dataView, String downloadFolder, boolean enableScan, boolean confirmDownload, String downloadFileSize, ArrayList<Boolean> quickActionServer) { super(); this.dataView = dataView; this.downloadFolder = downloadFolder; this.enableScan = enableScan; this.confirmDownload = confirmDownload; this.downloadFileSize = downloadFileSize; this.quickActionServer = quickActionServer; } public int getDataView() { return dataView; } public void setDataView(int dataView) { this.dataView = dataView; } public void setDownloadFolder(String downloadFolder) { this.downloadFolder = downloadFolder; } public String getDownloadFolder() { return downloadFolder; } public void setEnableScan(boolean enableScan) { this.enableScan = enableScan; } public boolean isEnableScan() { return enableScan; } public void setConfirmDownload(boolean confirmDownload) { this.confirmDownload = confirmDownload; } public boolean isConfirmDownload() { return confirmDownload; } public void setDownloadFileSize(String downloadFileSize) { this.downloadFileSize = downloadFileSize; } public String getDownloadFileSize() { return downloadFileSize; } public void setQuickActionServer(ArrayList<Boolean> quickActionServer) { this.quickActionServer = quickActionServer; } public ArrayList<Boolean> getQuickActionServer() { return quickActionServer; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/Prefs.java
Java
asf20
2,582
/* * 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 android.app.Activity; import android.os.Bundle; import android.view.Window; import de.fmaul.android.cmis.asynctask.ServerInfoDisplayTask; public class ServerInfoGeneralActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); new ServerInfoDisplayTask(this).execute(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/ServerInfoGeneralActivity.java
Java
asf20
1,079
/* * 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.asynctask; import android.app.ListActivity; import android.content.pm.ActivityInfo; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.GridView; import android.widget.ListView; import android.widget.TextView; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.CmisItemCollectionAdapter; import de.fmaul.android.cmis.GridAdapter; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class SearchDisplayTask extends AsyncTask<String, Void, CmisItemCollection> { private static final String TAG = "SearchDisplayTask"; private final ListActivity activity; private final CmisRepository repository; private final String queryString; private View layout; private CmisItemCollection items; private ListView layoutListing; private GridView layoutGrid; private Boolean errorOnExit = false; public SearchDisplayTask(ListActivity activity, CmisRepository repository, String queryString) { this(activity, repository, queryString, null); } public SearchDisplayTask(ListActivity activity, CmisRepository repository, String queryString, CmisItemCollection items) { super(); this.activity = activity; this.repository = repository; this.queryString = queryString; this.items = items; } @Override protected void onPreExecute() { activity.setProgressBarIndeterminateVisibility(true); //Hide Data during Animation layoutListing = activity.getListView(); layoutListing.setVisibility(View.GONE); activity.findViewById(R.id.empty).setVisibility(View.GONE); //Setting TITLE activity.getWindow().setTitle(repository.getServer().getName() + " > " + activity.getString(R.string.search_progress)); //Setting Breadcrumb ((TextView) activity.findViewById(R.id.path)).setText(">"); //Loading Animation layout = activity.findViewById(R.id.animation); layout.setVisibility(View.VISIBLE); View objet = activity.findViewById(R.id.transfert); Animation animation = AnimationUtils.loadAnimation(activity, R.anim.download); objet.startAnimation(animation); } @Override protected CmisItemCollection doInBackground(String... params) { try { if (items != null){ return items; } else { String feed = params[0]; return repository.getCollectionFromFeed(feed); } } catch (FeedLoadException fle) { Log.d(TAG, fle.getMessage()); errorOnExit = true; return CmisItemCollection.emptyCollection(); } catch (StorageException e) { Log.d(TAG, e.getMessage()); errorOnExit = true; return CmisItemCollection.emptyCollection(); } } @Override protected void onPostExecute(CmisItemCollection itemCollection) { itemCollection.setTitle(queryString); if (errorOnExit){ ActionUtils.displayMessage(activity, R.string.generic_error); } ((CmisApp) activity.getApplication()).setItems(itemCollection); Prefs prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ GridView gridview = (GridView) activity.findViewById(R.id.gridview); gridview.setAdapter(new GridAdapter(activity, R.layout.feed_grid_row, itemCollection)); } else { layoutListing.setAdapter(new CmisItemCollectionAdapter(activity, R.layout.feed_list_row, itemCollection)); } //Setting TITLE activity.getWindow().setTitle(repository.getServer().getName() + " > " + activity.getString(R.string.menu_item_search)); //Setting BreadCrumb ((TextView) activity.findViewById(R.id.path)).setText( itemCollection.getItems().size() + " " + activity.getString(R.string.search_results_for) + " " + queryString); //Show Data & Hide Animation prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ layoutGrid.setVisibility(View.VISIBLE); } else { layoutListing.setVisibility(View.VISIBLE); } layout.setVisibility(View.GONE); activity.setProgressBarIndeterminateVisibility(false); if (itemCollection.getItems().size() == 0 ){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } else { activity.findViewById(R.id.empty).setVisibility(View.GONE); } //Allow screen rotation activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } @Override protected void onCancelled() { activity.setProgressBarIndeterminateVisibility(false); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/SearchDisplayTask.java
Java
asf20
5,643
/* * 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.asynctask; import android.app.ListActivity; import android.content.pm.ActivityInfo; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.GridView; import android.widget.ListView; import android.widget.TextView; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.CmisItemCollectionAdapter; import de.fmaul.android.cmis.GridAdapter; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class FeedDisplayTask extends AsyncTask<String, Void, CmisItemCollection> { private static final String TAG = "FeedDisplayTask"; private final ListActivity activity; private final CmisRepository repository; private final String title; private String feedParams = ""; private View layout; private CmisItemLazy item; private CmisItemCollection items; private ListView layoutListing; private GridView layoutGrid; public FeedDisplayTask(ListActivity activity, CmisRepository repository, String title) { this(activity, repository, title, null, null); } public FeedDisplayTask(ListActivity activity, CmisRepository repository, CmisItemLazy item) { this(activity, repository, item.getTitle(), item, null); } public FeedDisplayTask(ListActivity activity, CmisRepository repository, String title, CmisItemLazy item, CmisItemCollection items) { super(); this.activity = activity; this.repository = repository; this.title = title; this.item = item; this.items = items; } @Override protected void onPreExecute() { activity.setProgressBarIndeterminateVisibility(true); if (items == null && repository != null && repository.getUseFeedParams()){ feedParams = repository.getFeedParams(); } //Hide Data during Animation layoutGrid = (GridView) activity.findViewById(R.id.gridview); layoutListing = activity.getListView(); layoutListing.setVisibility(View.GONE); layoutGrid.setVisibility(View.GONE); activity.findViewById(R.id.empty).setVisibility(View.GONE); //Loading Animation layout = activity.findViewById(R.id.animation); layout.setVisibility(View.VISIBLE); View objet = activity.findViewById(R.id.transfert); Animation animation = AnimationUtils.loadAnimation(activity, R.anim.download); objet.startAnimation(animation); } @Override protected CmisItemCollection doInBackground(String... params) { try { if (items != null){ return items; } else { String feed = params[0]; if (feed == null || feed.length() == 0) { return repository.getRootCollection(feedParams); } else { return repository.getCollectionFromFeed(feed + feedParams); } } } catch (FeedLoadException fle) { Log.d(TAG, fle.getMessage()); //ActionUtils.displayMessage(activity, R.string.generic_error); return CmisItemCollection.emptyCollection(); } catch (StorageException e) { Log.d(TAG, e.getMessage()); //ActionUtils.displayMessage(activity, R.string.generic_error); return CmisItemCollection.emptyCollection(); } } @Override protected void onPostExecute(CmisItemCollection itemCollection) { if (items == null){ if (title != null){ itemCollection.setTitle(title); } else { itemCollection.setTitle(item.getTitle()); } } ((CmisApp) activity.getApplication()).setItems(itemCollection); Prefs prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ GridView gridview = (GridView) activity.findViewById(R.id.gridview); gridview.setAdapter(new GridAdapter(activity, R.layout.feed_grid_row, itemCollection)); } else { layoutListing.setAdapter(new CmisItemCollectionAdapter(activity, R.layout.feed_list_row, itemCollection)); } //No Case Button back = ((Button) activity.findViewById(R.id.back)); Button next = ((Button) activity.findViewById(R.id.next)); String title_paging = ""; if (repository.isPaging() == false){ Log.d(TAG, "PAGING : NO"); back.setVisibility(View.GONE); next.setVisibility(View.GONE); } else { //First Case if (repository.getSkipCount() == 0 && (repository.getSkipCount() + repository.getMaxItems()) >= repository.getNumItems()){ Log.d(TAG, "PAGING : UNIQUE"); back.setVisibility(View.GONE); next.setVisibility(View.GONE); } else if (repository.getSkipCount() == 0 && (repository.getSkipCount() + repository.getMaxItems()) < repository.getNumItems()){ Log.d(TAG, "PAGING : FIRST"); int nb_page = repository.getNumItems() > 0 ? ((int) Math.ceil((double) repository.getNumItems()/ (double) repository.getMaxItems())) : 0; title_paging = " [1/" + nb_page + "]"; next.setVisibility(View.VISIBLE); back.setVisibility(View.GONE); } else if (repository.getSkipCount() != 0 && (repository.getSkipCount() + repository.getMaxItems()) >= repository.getNumItems()){ int nb_page = repository.getNumItems() > 0 ? ((int) Math.ceil((double) repository.getNumItems()/ (double) repository.getMaxItems())) : 0; title_paging = " [" + nb_page + "/" + nb_page + "]"; Log.d(TAG, "PAGING : END"); next.setVisibility(View.GONE); back.setVisibility(View.VISIBLE); } else { int nb_page = repository.getNumItems() > 0 ? ((int) Math.ceil((double) repository.getNumItems()/ (double) repository.getMaxItems())) : 0; int currentPage = repository.getSkipCount() > 0 ? ((int) Math.floor((double) repository.getSkipCount()/ (double) repository.getMaxItems())) + 1 : 0; title_paging = " [" + currentPage + "/" + nb_page + "]"; Log.d(TAG, "PAGING : MIDDLE"); back.setVisibility(View.VISIBLE); next.setVisibility(View.VISIBLE); } } //Setting TITLE activity.getWindow().setTitle(itemCollection.getTitle() + title_paging); //Setting BreadCrumb if (item != null && item.getPath() != null){ ((TextView) activity.findViewById(R.id.path)).setText(item.getPath()); } else { ((TextView) activity.findViewById(R.id.path)).setText("/"); } //Show Data & Hide Animation prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ layoutGrid.setVisibility(View.VISIBLE); } else { layoutListing.setVisibility(View.VISIBLE); } layout.setVisibility(View.GONE); activity.setProgressBarIndeterminateVisibility(false); if (itemCollection.getItems().size() == 0 ){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } else { activity.findViewById(R.id.empty).setVisibility(View.GONE); } //Allow screen rotation activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } @Override protected void onCancelled() { activity.setProgressBarIndeterminateVisibility(false); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/FeedDisplayTask.java
Java
asf20
8,111
package de.fmaul.android.cmis.asynctask; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.AsyncTask; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.ListUtils; public class ServerInfoDisplayTask extends AsyncTask<String, Void, SimpleAdapter> { private final Activity activity; public ServerInfoDisplayTask(Activity activity) { super(); this.activity = activity; } @Override protected void onPreExecute() { activity.setProgressBarIndeterminateVisibility(true); } @Override protected SimpleAdapter doInBackground(String... params) { try { ArrayList<CmisProperty> propList = activity.getIntent().getParcelableArrayListExtra(activity.getIntent().getStringExtra("context")); List<Map<String, ?>> list = ListUtils.buildListOfNameValueMaps(propList); SimpleAdapter props = new SimpleAdapter(activity, list, R.layout.document_details_row, new String[] { "name", "value" }, new int[] { R.id.propertyName, R.id.propertyValue }); return props; } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(SimpleAdapter props) { //Init View activity.setContentView(R.layout.server_info_general); ListView listInfo = (ListView) activity.findViewById(R.id.server_info_general); listInfo.setAdapter(props); if (listInfo.getCount() == 0){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } activity.setProgressBarIndeterminateVisibility(false); } @Override protected void onCancelled() { activity.setProgressBarIndeterminateVisibility(false); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/ServerInfoDisplayTask.java
Java
asf20
1,894
package de.fmaul.android.cmis.asynctask; import java.util.ArrayList; import java.util.Map; import org.dom4j.Element; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.ServerInfoActivity; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.FeedUtils; public class ServerInfoLoadingTask extends AsyncTask<String, Void, Map<String, ArrayList<CmisProperty>>> { private final Activity activity; private Server server; private ProgressDialog pg; public ServerInfoLoadingTask(Activity activity, Server server) { super(); this.activity = activity; this.server = server; } @Override protected void onPreExecute() { pg = ProgressDialog.show(activity, "", activity.getText(R.string.loading), true); } @Override protected Map<String, ArrayList<CmisProperty>> doInBackground(String... params) { try { Element workspace; Map<String, ArrayList<CmisProperty>> properties = null; try { workspace = FeedUtils.getWorkspace(server.getWorkspace(), server.getUrl(), server.getUsername(), server.getPassword()); properties = FeedUtils.getCmisRepositoryProperties(workspace); } catch (Exception e) { e.printStackTrace(); } return properties; } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(Map<String, ArrayList<CmisProperty>> properties) { //Init View Intent intent = new Intent(activity, ServerInfoActivity.class); intent.putExtra("title", "Info " + server.getName()); intent.putParcelableArrayListExtra(Server.INFO_GENERAL, properties.get(Server.INFO_GENERAL)); intent.putParcelableArrayListExtra(Server.INFO_ACL_CAPABILITIES, properties.get(Server.INFO_ACL_CAPABILITIES)); intent.putParcelableArrayListExtra(Server.INFO_CAPABILITIES, properties.get(Server.INFO_CAPABILITIES)); activity.startActivity(intent); pg.dismiss(); } @Override protected void onCancelled() { pg.dismiss(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/ServerInfoLoadingTask.java
Java
asf20
2,239
package de.fmaul.android.cmis.asynctask; import android.app.Activity; import android.app.Application; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.ListCmisFeedActivity; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.SearchActivity; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class ServerSearchInitTask extends AsyncTask<String, Void, CmisRepository> { private final Activity currentActivity; private ProgressDialog pg; private Server server; private Application app; private Intent intent; public ServerSearchInitTask(Activity activity, Application app, final Server server, Intent intent) { super(); this.currentActivity = activity; this.app = app; this.server = server; this.intent = intent; } @Override protected void onPreExecute() { pg = ProgressDialog.show(currentActivity, "", currentActivity.getText(R.string.loading), true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ServerSearchInitTask.this.cancel(true); currentActivity.finish(); dialog.dismiss(); } }); } @Override protected CmisRepository doInBackground(String... params) { try { return CmisRepository.create(app, server); } catch (FeedLoadException fle) { return null; } catch (Exception fle) { return null; } } @Override protected void onPostExecute(CmisRepository repo) { try { repo.generateParams(currentActivity); ((CmisApp) currentActivity.getApplication()).setRepository(repo); repo.clearCache(repo.getServer().getWorkspace()); Intent i = new Intent(currentActivity, SearchActivity.class); i.putExtras(intent); currentActivity.startActivity(i); currentActivity.finish(); pg.dismiss(); } catch (StorageException e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); pg.dismiss(); } catch (Exception e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); currentActivity.finish(); pg.dismiss(); } } @Override protected void onCancelled() { currentActivity.finish(); pg.dismiss(); } private String getFeedFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("feed") != null) { return extras.get("feed").toString(); } } return null; } private String getTitleFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("title") != null) { return extras.get("title").toString(); } } return null; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/ServerSearchInitTask.java
Java
asf20
3,138
package de.fmaul.android.cmis.asynctask; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import android.app.Activity; import android.app.Application; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.view.View; import android.widget.Button; import de.fmaul.android.cmis.FileChooserActivity; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FileSystemUtils; import de.fmaul.android.cmis.utils.StorageException; public class CopyFilesTask extends AsyncTask<String, Integer, Boolean> { private final Activity activity; private ProgressDialog progressDialog; private Application app; private static final int MAX_BUFFER_SIZE = 1024; public static final String STATUSES[] = {"Downloading", "Paused", "Complete", "Cancelled", "Error"}; public static final int DOWNLOADING = 0; public static final int PAUSED = 1; public static final int COMPLETE = 2; public static final int CANCELLED = 3; public static final int ERROR = 4; private int status; private int downloaded; private float sizeTotal = 0f; private File folder; private List<File> listingFiles; private List<File> moveFiles; public CopyFilesTask(Activity activity, final List<File> listingFiles, final List<File> moveFiles, final File folder) { super(); this.activity = activity; this.folder = folder; this.listingFiles = listingFiles; this.moveFiles = moveFiles; } @Override protected void onPreExecute() { status = DOWNLOADING; downloaded = 0; progressDialog = new ProgressDialog(activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); //progressDialog.setMessage(this.activity.getText(R.string.copy)); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CopyFilesTask.this.cancel(true); status = CANCELLED; dialog.dismiss(); } }); progressDialog.setCancelable(true); progressDialog.setTitle(this.activity.getText(R.string.copy)); //progressDialog.setMessage(this.activity.getText(R.string.copy)); progressDialog.setProgress(0); progressDialog.setMax(100); progressDialog.show(); for (File file : listingFiles) { sizeTotal += file.length(); } } @Override protected Boolean doInBackground(String... params) { try { for (File file : listingFiles) { copyFile(file); } for (File fileToMove : moveFiles) { FileSystemUtils.rename(folder, fileToMove); } return true; } catch (Exception fle) { return false; } } @Override protected void onPostExecute(Boolean statut) { try { if (statut){ listingFiles.clear(); moveFiles.clear(); activity.findViewById(R.id.paste).setVisibility(View.GONE); activity.findViewById(R.id.clear).setVisibility(View.GONE); progressDialog.dismiss(); ActionUtils.displayMessage(activity, R.string.action_paste_success); ((FileChooserActivity) activity).initialize(folder.getName(), folder); } else { ActionUtils.displayMessage(activity, R.string.generic_error); progressDialog.dismiss(); } } catch (Exception e) { ActionUtils.displayMessage(activity, R.string.generic_error); activity.finish(); progressDialog.dismiss(); } } @Override protected void onCancelled() { activity.finish(); progressDialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int percent = Math.round((float) values[0] / sizeTotal * 100); progressDialog.setProgress(percent); } private void copyFile(File src) throws StorageException { OutputStream os = null; InputStream in = null; int size = (int) src.length(); try { in = new FileInputStream(src); os = new FileOutputStream(createUniqueCopyName(src.getName())); byte[] buffer = new byte[MAX_BUFFER_SIZE]; while (status == DOWNLOADING) { if (size - downloaded < MAX_BUFFER_SIZE) { buffer = new byte[size - downloaded]; } int read = in.read(buffer); if (read == -1 || size == downloaded) break; os.write(buffer, 0, read); downloaded += read; stateChanged(); } if (status == DOWNLOADING) { status = COMPLETE; stateChanged(); } } catch (Exception e) { } finally { if (os != null) { try { os.close(); } catch (Exception e) {} } if (in != null) { try { in.close(); } catch (Exception e) {} } } } private File createUniqueCopyName(String fileName) { File file = new File(folder, fileName); if (!file.exists()) { return file; } file = new File(folder, activity.getString(R.string.copied_file_name) + fileName); if (!file.exists()) { return file; } int copyIndex = 2; while (copyIndex < 500) { file = new File(folder, activity.getString(R.string.copied_file_name) + copyIndex + "_" + fileName); if (!file.exists()) { return file; } copyIndex++; } return null; } private void stateChanged() { publishProgress(downloaded); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/CopyFilesTask.java
Java
asf20
5,909
package de.fmaul.android.cmis.asynctask; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.view.View; import android.widget.SimpleAdapter; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.DocumentDetailsActivity; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.repo.CmisPropertyFilter; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.CmisTypeDefinition; import de.fmaul.android.cmis.utils.FeedLoadException; public class ItemPropertiesDisplayTask extends AsyncTask<String, Void, List<Map<String, ?>>> { private final DocumentDetailsActivity activity; private ProgressDialog pg; private String[] filterProperties; private CmisPropertyFilter propertiesFilters; private boolean screenRotation = false; public ItemPropertiesDisplayTask(DocumentDetailsActivity activity) { super(); this.activity = activity; } public ItemPropertiesDisplayTask(DocumentDetailsActivity activity, boolean screenRotation) { super(); this.activity = activity; this.screenRotation = true; } public ItemPropertiesDisplayTask(DocumentDetailsActivity activity, String[] filterProperties) { super(); this.activity = activity; this.filterProperties = filterProperties; } @Override protected void onPreExecute() { pg = ProgressDialog.show(activity, "", activity.getText(R.string.loading), true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ItemPropertiesDisplayTask.this.cancel(true); activity.finish(); dialog.dismiss(); } }); propertiesFilters = ((CmisApp) activity.getApplication()).getCmisPropertyFilter(); } @Override protected List<Map<String, ?>> doInBackground(String... params) { try { if (propertiesFilters != null){ if (screenRotation) { return propertiesFilters.render(); } else { return propertiesFilters.render(filterProperties); } } else { List<CmisProperty> propList = getPropertiesFromIntent(); CmisTypeDefinition typeDefinition = getRepository().getTypeDefinition(getObjectTypeIdFromIntent()); if (propertiesFilters == null){ propertiesFilters = new CmisPropertyFilter(propList, typeDefinition); } return propertiesFilters.render(filterProperties); } } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(List<Map<String, ?>> list) { ((CmisApp) activity.getApplication()).setCmisPropertyFilter(propertiesFilters); SimpleAdapter props = new SimpleAdapter(activity, list, R.layout.document_details_row, new String[] { "name", "value" }, new int[] { R.id.propertyName, R.id.propertyValue }); activity.setListAdapter(props); if (list.size() == 0 ){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } else { activity.findViewById(R.id.empty).setVisibility(View.GONE); } pg.dismiss(); } @Override protected void onCancelled() { pg.dismiss(); } private String getObjectTypeIdFromIntent() { return activity.getIntent().getStringExtra("objectTypeId"); } private ArrayList<CmisProperty> getPropertiesFromIntent() { ArrayList<CmisProperty> propList = activity.getIntent().getParcelableArrayListExtra("properties"); return propList; } CmisRepository getRepository() { return ((CmisApp) activity.getApplication()).getRepository(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/ItemPropertiesDisplayTask.java
Java
asf20
3,745
package de.fmaul.android.cmis.asynctask; import org.dom4j.Document; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.FeedUtils; public class FeedItemDisplayTask extends AsyncTask<String, Void, CmisItem> { private static final String TAG = "FeedItemDisplayTask"; private final Activity activity; private ProgressDialog pg; private Server server; private String url; private int action; public static final int DISPLAY_DETAILS = 0; public static final int DISPLAY_FOLDER = 1; public FeedItemDisplayTask(Activity activity, final Server server, String url) { this(activity, server, url, -1); } public FeedItemDisplayTask(Activity activity, final Server server, String url, int action) { super(); this.activity = activity; this.url = url; this.server = server; this.action = action; } @Override protected void onPreExecute() { pg = ProgressDialog.show(activity, "", activity.getText(R.string.loading), true); } @Override protected CmisItem doInBackground(String... params) { try { Document doc = FeedUtils.readAtomFeed(url, server.getUsername(), server.getPassword()); return CmisItem.createFromFeed(doc.getRootElement()); } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(CmisItem item) { if (item != null){ if (action == -1){ if (item.getBaseType() == null){ action = DISPLAY_FOLDER; } else { action = DISPLAY_DETAILS; } } switch (action) { case DISPLAY_DETAILS: ActionUtils.displayDocumentDetails(activity, server, item); break; case DISPLAY_FOLDER: ActionUtils.openNewListViewActivity(activity, item); break; default: break; } } else { ActionUtils.displayMessage(activity, R.string.favorite_error_loading); } pg.dismiss(); } @Override protected void onCancelled() { pg.dismiss(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/FeedItemDisplayTask.java
Java
asf20
2,283
package de.fmaul.android.cmis.asynctask; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.DownloadItem; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.HttpUtils; import de.fmaul.android.cmis.utils.NotificationUtils; import de.fmaul.android.cmis.utils.StorageException; import de.fmaul.android.cmis.utils.StorageUtils; public abstract class AbstractDownloadTask extends AsyncTask<CmisItemLazy, Integer, File> { private final CmisRepository repository; private final Activity activity; private ProgressDialog progressDialog; private Boolean isDownload; private CmisItemLazy item; private static final int MAX_BUFFER_SIZE = 1024; private static final int NB_NOTIF = 10; public static final int DOWNLOADING = 0; private static final int PAUSED = 1; public static final int COMPLETE = 2; public static final int CANCELLED = 3; private static final int ERROR = 4; public int state; private int downloaded; private int size; private int notifCount = 0; private int percent; public AbstractDownloadTask(CmisRepository repository, Activity activity) { this(repository, activity, false); } public AbstractDownloadTask(CmisRepository repository, Activity activity, Boolean isDownload) { this.repository = repository; this.activity = activity; this.isDownload = isDownload; } @Override protected void onPreExecute() { super.onPreExecute(); if (isDownload == false){ state = DOWNLOADING; downloaded = 0; progressDialog = new ProgressDialog(activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(this.activity.getText(R.string.download)); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { AbstractDownloadTask.this.cancel(true); state = CANCELLED; //NotificationUtils.cancelDownloadNotification(activity); dialog.dismiss(); } }); progressDialog.setCancelable(true); progressDialog.setTitle(this.activity.getText(R.string.download)); progressDialog.setMessage(this.activity.getText(R.string.download_progress)); progressDialog.setProgress(0); progressDialog.setMax(100); progressDialog.show(); } else { ActionUtils.displayMessage(activity, R.string.download_progress); } } @Override protected File doInBackground(CmisItemLazy... params) { item = params[0]; List<DownloadItem> dl = ((CmisApp) activity.getApplication()).getDownloadedFiles(); if (dl == null) { dl = new ArrayList<DownloadItem>(); } dl.add(new DownloadItem(item, this)); if (item != null) { //progressDialog.setMax(Integer.parseInt(item.getSize())); size = Integer.parseInt(item.getSize()); try { if (isDownload){ return retreiveContent(item, ((CmisApp) activity.getApplication()).getPrefs().getDownloadFolder()); } else { return retreiveContent(item); } } catch (Exception e) { ActionUtils.displayMessage(activity, R.string.generic_error); return null; } } return null; } protected void onPostExecute(File result) { if (state == CANCELLED){ result.delete(); result = null; } if (progressDialog != null && progressDialog.isShowing()){ progressDialog.dismiss(); } onDownloadFinished(result); } @Override protected void onCancelled() { state = CANCELLED; if (progressDialog.isShowing()){ progressDialog.dismiss(); } } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); percent = Math.round(((float) values[0] / Float.parseFloat(item.getSize())) * 100); if (isDownload == false){ progressDialog.setProgress(percent); } else { if (notifCount == NB_NOTIF){ String message = activity.getText(R.string.progress) + " : " + percent + " %"; NotificationUtils.updateDownloadNotification(activity, message); notifCount = 0; } else { notifCount++; } } } public abstract void onDownloadFinished(File result); private File retreiveContent(CmisItemLazy item) throws StorageException { File contentFile = StorageUtils.getStorageFile(activity.getApplication(), repository.getServer().getWorkspace(), StorageUtils.TYPE_CONTENT, item.getId(), item.getTitle()); return retreiveContent(item, contentFile); } private File retreiveContent(CmisItemLazy item, String downloadFolder) throws StorageException { File contentFile = item.getContentDownload(activity.getApplication(), downloadFolder); return retreiveContent(item, contentFile); } private File retreiveContent(CmisItemLazy item, File contentFile) throws StorageException { OutputStream os = null; InputStream in = null; try { contentFile.getParentFile().mkdirs(); contentFile.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(contentFile)); in = HttpUtils.getWebRessourceAsStream(item.getContentUrl(), repository.getServer().getUsername(), repository.getServer().getPassword()); byte[] buffer = new byte[MAX_BUFFER_SIZE]; while (state == DOWNLOADING) { if (size - downloaded < MAX_BUFFER_SIZE) { buffer = new byte[size - downloaded]; } int read = in.read(buffer); if (read == -1) break; os.write(buffer, 0, read); downloaded += read; stateChanged(); } if (state == DOWNLOADING) { state = COMPLETE; stateChanged(); } return contentFile; } catch (Exception e) { } finally { // Close file. if (os != null) { try { os.close(); } catch (Exception e) {} } // Close connection to server. if (in != null) { try { in.close(); } catch (Exception e) {} } } return null; } private void stateChanged() { publishProgress(downloaded); } public int getPercent() { return percent; } public void setState(int state) { this.state = state; } public int getState(){ return state; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/AbstractDownloadTask.java
Java
asf20
7,144
package de.fmaul.android.cmis.asynctask; import android.app.Activity; import android.app.Application; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.ListCmisFeedActivity; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class ServerInitTask extends AsyncTask<String, Void, CmisRepository> { private final Activity currentActivity; private final ListCmisFeedActivity ListActivity; private final Activity activity; private ProgressDialog pg; private Server server; private Application app; public ServerInitTask(ListCmisFeedActivity activity, Application app, final Server server) { super(); this.currentActivity = activity; this.ListActivity = activity; this.app = app; this.server = server; this.activity = null; } public ServerInitTask(Activity activity, Application app, final Server server) { super(); this.currentActivity = activity; this.ListActivity = null; this.activity = activity; this.app = app; this.server = server; } @Override protected void onPreExecute() { pg = ProgressDialog.show(currentActivity, "", currentActivity.getText(R.string.loading), true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ServerInitTask.this.cancel(true); currentActivity.finish(); dialog.dismiss(); } }); } @Override protected CmisRepository doInBackground(String... params) { try { return CmisRepository.create(app, server); } catch (FeedLoadException fle) { return null; } catch (Exception fle) { return null; } } @Override protected void onPostExecute(CmisRepository repo) { try { repo.generateParams(currentActivity); ((CmisApp) currentActivity.getApplication()).setRepository(repo); repo.clearCache(repo.getServer().getWorkspace()); if (ListActivity != null){ ListActivity.setItem(repo.getRootItem()); new FeedDisplayTask(ListActivity, repo, getTitleFromIntent()).execute(getFeedFromIntent()); } pg.dismiss(); } catch (StorageException e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); pg.dismiss(); } catch (Exception e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); currentActivity.finish(); pg.dismiss(); } } @Override protected void onCancelled() { currentActivity.finish(); pg.dismiss(); } private String getFeedFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("feed") != null) { return extras.get("feed").toString(); } } return null; } private String getTitleFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("title") != null) { return extras.get("title").toString(); } } return null; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/asynctask/ServerInitTask.java
Java
asf20
3,454
/* * 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; import java.util.ArrayList; import android.app.ListActivity; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisItemLazy; public class ListCmisFeedActivitySave extends ListActivity { public CmisItemLazy getItem() { return item; } public CmisItemLazy getItemParent() { return itemParent; } public CmisItemCollection getItems() { return items; } public ArrayList<CmisItemLazy> getCurrentStack() { return currentStack; } public ListCmisFeedActivitySave(CmisItemLazy item, CmisItemLazy itemParent, CmisItemCollection items, ArrayList<CmisItemLazy> currentStack) { super(); this.item = item; this.itemParent = itemParent; this.items = items; this.currentStack = currentStack; } private CmisItemLazy item; private CmisItemLazy itemParent; private CmisItemCollection items; private ArrayList<CmisItemLazy> currentStack = new ArrayList<CmisItemLazy>(); }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/ListCmisFeedActivitySave.java
Java
asf20
1,555
/* * 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; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.StorageException; import de.fmaul.android.cmis.utils.StorageUtils; public class CmisPreferences extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); ( (CheckBoxPreference) (getPreferenceManager().findPreference(this.getText(R.string.cmis_cache)))).setChecked(false); getPreferenceManager().findPreference(this.getText(R.string.cmis_cache)).setEnabled(true); getPreferenceManager().findPreference(this.getText(R.string.cmis_cache)).setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference){ try { StorageUtils.deleteCacheFolder(CmisPreferences.this.getApplication()); } catch (StorageException e) { ActionUtils.displayMessage(CmisPreferences.this, R.string.generic_error); } preference.setEnabled(false); return true; } }); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); ActionUtils.initPrefs(this); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/CmisPreferences.java
Java
asf20
2,123
/* * 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.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.utils.ActionItem; import de.fmaul.android.cmis.utils.QuickAction; public class ServerAdapter extends ArrayAdapter<Server> { private final Context context; private ArrayList<Server> items; private Server server; private ServerActivity serverActivity; private static final Integer ACTION_SERVER_OPEN = 0; private static final Integer ACTION_SERVER_INFO = 1; private static final Integer ACTION_SERVER_EDIT = 2; private static final Integer ACTION_SERVER_FAVORITE = 3; private static final Integer ACTION_SERVER_SEARCH = 4; private static final Integer ACTION_SERVER_DELETE = 5; public ServerAdapter(Context context, int textViewResourceId, ArrayList<Server> servers) { super(context, textViewResourceId,servers); this.items = servers; this.context = context; this.serverActivity = (ServerActivity) context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.server_row, null); } server = items.get(position); if (server != null) { TextView tv = (TextView) v.findViewById(R.id.rowserver); ImageView iv = (ImageView) v.findViewById(R.id.iconserver); iv.setTag(position); iv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Integer position = (Integer)v.getTag(); server = items.get(position); showQuickAction(v); } }); if (tv != null) { tv.setText(server.getName()); } if(iv != null){ iv.setImageResource(R.drawable.repository); } } return v; } private void showQuickAction(View v){ final QuickAction qa = new QuickAction(v); v.getParent().getParent(); if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_OPEN)){ final ActionItem actionItem = new ActionItem(); actionItem.setTitle(context.getText(R.string.open).toString()); actionItem.setIcon(context.getResources().getDrawable(R.drawable.open_remote)); actionItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ListCmisFeedActivity.class); intent.putExtra("isFirstStart", true); intent.putExtra("server", server); intent.putExtra("title", server.getName()); context.startActivity(intent); qa.dismiss(); } }); qa.addActionItem(actionItem); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_INFO)){ final ActionItem info = new ActionItem(); info.setTitle(context.getText(R.string.server_info).toString()); info.setIcon(context.getResources().getDrawable(R.drawable.info)); info.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { serverActivity.getInfoServer(server); qa.dismiss(); } }); qa.addActionItem(info); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_EDIT)){ final ActionItem edit = new ActionItem(); edit.setTitle(context.getText(R.string.edit).toString()); edit.setIcon(context.getResources().getDrawable(R.drawable.editmetada)); edit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { serverActivity.editServer(server); qa.dismiss(); } }); qa.addActionItem(edit); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_FAVORITE)){ final ActionItem favorite = new ActionItem(); favorite.setTitle(context.getText(R.string.menu_item_favorites).toString()); favorite.setIcon(context.getResources().getDrawable(R.drawable.favorite)); favorite.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, FavoriteActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); context.startActivity(intent); qa.dismiss(); } }); qa.addActionItem(favorite); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_SEARCH)){ final ActionItem search = new ActionItem(); search.setTitle(context.getText(R.string.menu_item_search).toString()); search.setIcon(context.getResources().getDrawable(R.drawable.search)); search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { serverActivity.startSearch(); qa.dismiss(); } }); qa.addActionItem(search); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_DELETE)){ final ActionItem delete = new ActionItem(); delete.setTitle(context.getText(R.string.delete).toString()); delete.setIcon(context.getResources().getDrawable(R.drawable.delete)); delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.delete); builder.setMessage(context.getText(R.string.action_delete_desc) + " " + server.getName() + " ? ") .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { serverActivity.deleteServer(server.getId()); qa.dismiss(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); qa.dismiss(); } }).create(); builder.show(); } }); qa.addActionItem(delete); } qa.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER); qa.show(); } Prefs getCmisPrefs() { return ((CmisApp) serverActivity.getApplication()).getPrefs(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/ServerAdapter.java
Java
asf20
7,149
/* * 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; import android.app.Activity; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class SearchPrefs { private final Activity activity; public SearchPrefs(Activity activity) { this.activity = activity; } public boolean getExactSearch() { return getPrefs().getBoolean(activity.getString(R.string.cmis_repo_exact_search), false); } private SharedPreferences getPrefs() { return PreferenceManager.getDefaultSharedPreferences(activity); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/SearchPrefs.java
Java
asf20
1,161
/* * 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; import android.app.AlertDialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; 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.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import de.fmaul.android.cmis.asynctask.SearchDisplayTask; import de.fmaul.android.cmis.asynctask.ServerSearchInitTask; import de.fmaul.android.cmis.model.Search; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.QueryType; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageUtils; import de.fmaul.android.cmis.utils.UIUtils; public class SearchActivity extends ListActivity { private static final String TAG = "SearchActivity"; private ListActivity activity = this; private ListView listView; private Server server; private String searchFeed; private String queryString; private Prefs prefs; private Search savedSearch = null; private EditText input; /** * Contains the current connection information and methods to access the * CMIS repository. */ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWindow(); initActionIcon(); Bundle bundle = getIntent().getExtras(); if (bundle != null){ savedSearch = (Search) bundle.getSerializable("savedSearch"); } //Restart if (getLastNonConfigurationInstance() != null ){ } if (initRepository() == false){ doSearchWithIntent(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK){ this.finish(); return true; } return super.onKeyDown(keyCode, event); } @Override public Object onRetainNonConfigurationInstance() { return null; } @Override protected void onDestroy() { super.onDestroy(); } private void initActionIcon() { Button home = (Button) findViewById(R.id.home); Button refresh = (Button) findViewById(R.id.refresh); Button save = (Button) findViewById(R.id.save); Button pref = (Button) findViewById(R.id.preference); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); Intent intent = new Intent(activity, HomeActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); refresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { if (StorageUtils.deleteFeedFile(getApplication(), getRepository().getServer().getWorkspace(), searchFeed)){ Log.d(TAG, "SearchFeed : " + searchFeed); if (savedSearch != null){ queryString = savedSearch.getName(); } if (new SearchPrefs(activity).getExactSearch()){ searchFeed = searchFeed.replaceAll("%25", ""); } new SearchDisplayTask(SearchActivity.this, getRepository(), queryString).execute(searchFeed); } } catch (Exception e) { // TODO: handle exception } } }); save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DialogInterface.OnClickListener saveSearch = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (server == null){ server = getRepository().getServer(); } Log.d(TAG, "SearchFeed : " + server + " - " + searchFeed.substring( searchFeed.indexOf("=")+1, searchFeed.indexOf("&")) + " - " + input.getText().toString()); ActionUtils.createSaveSearch(SearchActivity.this, server, input.getText().toString(), searchFeed.substring( searchFeed.indexOf("=")+1, searchFeed.indexOf("&"))); } }; createDialog(R.string.search_create_title, R.string.search_create_desc, "", saveSearch).show(); } }); pref.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(activity, SearchPreferencesActivity.class)); } }); } private boolean initRepository() { if (savedSearch != null) { return false; } boolean init = true; try { if (getRepository() == null) { new ServerSearchInitTask(this, getApplication(), (Server) getIntent().getBundleExtra(SearchManager.APP_DATA).getSerializable("server"), getIntent()).execute(); } else { // Case if we change repository. server = (Server) getIntent().getBundleExtra(SearchManager.APP_DATA).getSerializable("server"); if (getRepository().getServer() != null && server!= null) { if (getRepository().getServer().getName().equals(server.getName())) { init = false; } else { new ServerSearchInitTask(this, getApplication(), (Server) getIntent().getBundleExtra(SearchManager.APP_DATA).getSerializable("server"), getIntent()).execute(); } } else { init = false; } } } catch (FeedLoadException fle) { ActionUtils.displayMessage(activity, R.string.generic_error); } return init; } /** * Initialize the window and the activity. */ private void initWindow() { setRequestedOrientation(getResources().getConfiguration().orientation); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.search_list_main); prefs = ((CmisApp) activity.getApplication()).getPrefs(); listView = activity.getListView(); listView.setTextFilterEnabled(true); listView.setItemsCanFocus(true); listView.setClickable(true); listView.setOnItemClickListener(new CmisDocSelectedListener()); listView.setOnCreateContextMenuListener(this); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); UIUtils.createContextMenu(activity, menu, menuInfo); } @Override public boolean onContextItemSelected(MenuItem menuItem) { return UIUtils.onContextItemSelected(this, menuItem, prefs); } /** * Process the current intent as search intent, build a query url and * display the feed. * * @param queryIntent */ private void doSearchWithIntent() { if (savedSearch != null){ searchFeed = getRepository().getSearchFeed(this, QueryType.SAVEDSEARCH, savedSearch.getUrl()); Log.d(TAG, "SearchFeed : " + searchFeed); new SearchDisplayTask(this, getRepository(), savedSearch.getName()).execute(searchFeed); } else { queryString = getIntent().getStringExtra(SearchManager.QUERY); QueryType queryType = getQueryTypeFromIntent(getIntent()); searchFeed = getRepository().getSearchFeed(this, queryType, queryString); Log.d(TAG, "SearchFeed : " + searchFeed); new SearchDisplayTask(this, getRepository(), queryString).execute(searchFeed); } } /** * The type of the query is passed by the SearchManager through a bundle in * the search intent. * * @param intent * @return */ private QueryType getQueryTypeFromIntent(Intent intent) { Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { String queryType = appData.getString(QueryType.class.getName()); return QueryType.valueOf(queryType); } return QueryType.FULLTEXT; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); UIUtils.createSearchMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 20: onSearchRequested(QueryType.TITLE); return true; case 21: onSearchRequested(QueryType.FOLDER); return true; case 22: onSearchRequested(QueryType.FULLTEXT); return true; case 23: onSearchRequested(QueryType.CMISQUERY); return true; case 24: Intent intent = new Intent(this, SavedSearchActivity.class); if (server == null){ server = getRepository().getServer(); } intent.putExtra("server", server); startActivity(intent); this.finish(); return true; default: return false; } } public boolean onSearchRequested(QueryType queryType) { Bundle appData = new Bundle(); appData.putString(QueryType.class.getName(), queryType.name()); startSearch("", false, appData, false); return true; } /** * Listener that is called whenever a user clicks on a file or folder in the * list. */ private class CmisDocSelectedListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CmisItem doc = (CmisItem) parent.getItemAtPosition(position); if (doc.hasChildren()) { ActionUtils.openNewListViewActivity(activity, doc); } else { ActionUtils.displayDocumentDetails(activity, getRepository().getServer(), doc); } } } 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(); } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } void setRepository(CmisRepository repo) { ((CmisApp) getApplication()).setRepository(repo); } CmisItemCollection getItems() { return ((CmisApp) getApplication()).getItems(); } void setItems(CmisItemCollection items) { ((CmisApp) getApplication()).setItems(items); } Prefs getCmisPrefs() { return ((CmisApp) getApplication()).getPrefs(); } public ListCmisFeedActivitySave getSaveContext(){ return ((CmisApp) getApplication()).getSavedContextItems(); } public void setSaveContext(ListCmisFeedActivitySave save){ ((CmisApp) getApplication()).setSavedContextItems(save); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/SearchActivity.java
Java
asf20
11,392
/* * 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 de.fmaul.android.cmis.utils.ActionUtils; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class HomeActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getIntent().getBooleanExtra("EXIT", false)) { finish(); } setContentView(R.layout.main); ActionUtils.initPrefs(this); ((Button) findViewById(R.id.about)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, AboutActivity.class)); } }); ((Button) findViewById(R.id.preferences)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /*int PICK_REQUEST_CODE = 0; Intent intent = new Intent(); intent.setAction(Intent.ACTION_PICK); Uri startDir = Uri.fromFile(new File("/sdcard")); // Files and directories ! intent.setDataAndType(startDir, "vnd.android.cursor.dir/*"); //intent.setData(startDir); startActivityForResult(intent, PICK_REQUEST_CODE);*/ startActivity(new Intent(HomeActivity.this, CmisPreferences.class)); //startActivity(new Intent(HomeActivity.this, FileChooserActivity.class)); } }); ((Button) findViewById(R.id.filesystem)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, FileChooserActivity.class)); } }); ((Button) findViewById(R.id.repository)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, ServerActivity.class)); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { if (resultCode == RESULT_OK) { Toast.makeText(this, "Hello ! ", Toast.LENGTH_LONG); } } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/HomeActivity.java
Java
asf20
3,028
/* * 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.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import de.fmaul.android.cmis.asynctask.ServerInfoLoadingTask; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.ServerDAO; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.QueryType; import de.fmaul.android.cmis.utils.ActionItem; import de.fmaul.android.cmis.utils.QuickAction; import de.fmaul.android.cmis.utils.UIUtils; public class ServerActivity extends ListActivity { private ServerAdapter cmisSAdapter; private ArrayList<Server> listServer; private Server server; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (activityIsCalledWithSearchAction()){ Intent intent = new Intent(this, SearchActivity.class); intent.putExtras(getIntent()); this.finish(); startActivity(intent); } else { setContentView(R.layout.server); createServerList(); registerForContextMenu(getListView()); } } private boolean activityIsCalledWithSearchAction() { final String queryAction = getIntent().getAction(); return Intent.ACTION_SEARCH.equals(queryAction); } public void createServerList(){ Database db = Database.create(this); ServerDAO serverDao = new ServerDAO(db.open()); listServer = new ArrayList<Server>(serverDao.findAll()); db.close(); cmisSAdapter = new ServerAdapter(this, R.layout.server_row, listServer); setListAdapter(cmisSAdapter); } public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuItem menuItem = menu.add(Menu.NONE, 1, 0, R.string.menu_item_server_add); menuItem.setIcon(R.drawable.add); menuItem = menu.add(Menu.NONE, 2, 0, R.string.menu_item_filter); menuItem.setIcon(R.drawable.filter); menuItem = menu.add(Menu.NONE, 3, 0, R.string.quit); menuItem.setIcon(R.drawable.quit); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case 1: startActivity(new Intent(this,ServerEditActivity.class)); return true; case 2: startActivity( new Intent(this, CmisFilterActivity.class)); return true; case 3: Intent intent = new Intent(this, HomeActivity.class); intent.putExtra("EXIT", true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } protected void onListItemClick(ListView l, View v, int position, long id) { Server s = listServer.get(position); if (s != null){ Intent intent = new Intent(this, ListCmisFeedActivity.class); intent.putExtra("isFirstStart", true); intent.putExtra("server", s); intent.putExtra("title", s.getName()); startActivity(intent); } else { Toast.makeText(this, R.string.generic_error, Toast.LENGTH_LONG); } } 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.context_menu_title)); menu.add(0, 1, Menu.NONE, getString(R.string.server_info)); menu.add(0, 2, Menu.NONE, getString(R.string.edit)); menu.add(0, 3, Menu.NONE, getString(R.string.delete)); menu.add(0, 4, Menu.NONE, getString(R.string.menu_item_favorites)); UIUtils.createSearchMenu(menu); } @Override public boolean onContextItemSelected(MenuItem menuItem) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo(); } catch (ClassCastException e) { return false; } if (menuInfo != null){ server = (Server) getListView().getItemAtPosition(menuInfo.position); } switch (menuItem.getItemId()) { case 1: if (server != null) { getInfoServer(server); } return true; case 2: if (server != null) { editServer(server); } return true; case 3: if (server != null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.delete); builder.setMessage(ServerActivity.this.getText(R.string.action_delete_desc) + " " + server.getName() + " ? ") .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deleteServer(server.getId()); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); builder.show(); } return true; case 4: if (server != null) { Intent intent = new Intent(this, FavoriteActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); startActivity(intent); } return true; case 20: onSearchRequested(QueryType.TITLE); return true; case 21: onSearchRequested(QueryType.FOLDER); return true; case 22: onSearchRequested(QueryType.FULLTEXT); return true; case 23: onSearchRequested(QueryType.CMISQUERY); return true; case 24: Intent intent = new Intent(this, SavedSearchActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); startActivity(intent); return true; default: return super.onContextItemSelected(menuItem); } } public boolean onSearchRequested(QueryType queryType) { Bundle appData = new Bundle(); appData.putString(QueryType.class.getName(), queryType.name()); appData.putSerializable("server", server); startSearch("", false, appData, false); return true; } public void deleteServer(long id){ Database db = Database.create(this); ServerDAO serverDao = new ServerDAO(db.open()); if (serverDao.delete(id)) { Toast.makeText(this, this.getString(R.string.server_delete), Toast.LENGTH_LONG).show(); createServerList(); } else { Toast.makeText(this, this.getString(R.string.server_delete_error), Toast.LENGTH_LONG).show(); } db.close(); } public void editServer(Server server){ Intent intent = new Intent(this, ServerEditActivity.class); intent.putExtra("server", server); startActivity(intent); } public void getInfoServer(Server server){ new ServerInfoLoadingTask(this, server).execute(); } private static ArrayList<String> getSearchItems(Activity activity) { ArrayList<String> filters = new ArrayList<String>(5); filters.add(activity.getText(R.string.menu_item_search_title).toString()); filters.add(activity.getText(R.string.menu_item_search_folder_title).toString()); filters.add(activity.getText(R.string.menu_item_search_fulltext).toString()); filters.add(activity.getText(R.string.menu_item_search_cmis).toString()); filters.add(activity.getText(R.string.menu_item_search_saved_search).toString()); return filters; } private ArrayList<QueryType> getQueryType() { ArrayList<QueryType> filters = new ArrayList<QueryType>(5); filters.add(QueryType.TITLE); filters.add(QueryType.FOLDER); filters.add(QueryType.FULLTEXT); filters.add(QueryType.CMISQUERY); filters.add(null); return filters; } private CharSequence[] getSearchItemsLabel() { ArrayList<String> filters = getSearchItems(this); return filters.toArray(new CharSequence[filters.size()]); } void startSearch(){ CharSequence[] cs = getSearchItemsLabel(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.search); builder.setTitle(R.string.menu_item_search); builder.setSingleChoiceItems(cs, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (getQueryType().get(which) != null){ onSearchRequested(getQueryType().get(which)); } else { Intent intent = new Intent(ServerActivity.this, SavedSearchActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); startActivity(intent); } dialog.dismiss(); } }); builder.setNegativeButton(this.getText(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/ServerActivity.java
Java
asf20
9,860
/* * 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.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import de.fmaul.android.cmis.asynctask.FeedItemDisplayTask; import de.fmaul.android.cmis.asynctask.ServerInitTask; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.FavoriteDAO; import de.fmaul.android.cmis.model.Favorite; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; public class FavoriteActivity extends ListActivity { private ArrayList<Favorite> listFavorite; private Server currentServer; private Activity activity; private boolean firstStart = true; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = this; Bundle bundle = getIntent().getExtras(); if (bundle != null){ currentServer = (Server) bundle.getSerializable("server"); firstStart = bundle.getBoolean("isFirstStart"); } setContentView(R.layout.server); setTitle(this.getText(R.string.favorite_title) + " " + currentServer.getName()); createFavoriteList(); registerForContextMenu(getListView()); initRepository(); } public void createFavoriteList(){ Database db = Database.create(this); FavoriteDAO favoriteDao = new FavoriteDAO(db.open()); listFavorite = new ArrayList<Favorite>(favoriteDao.findAll(currentServer.getId())); db.close(); setListAdapter(new FavoriteAdapter(this, R.layout.feed_list_row, listFavorite)); } protected void onListItemClick(ListView l, View v, int position, long id) { final Favorite f = listFavorite.get(position); if (f != null){ if (f.getMimetype() != null && f.getMimetype().length() != 0 && f.getMimetype().equals("cmis:folder") == false){ new FeedItemDisplayTask(activity, currentServer, f.getUrl()).execute(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(FavoriteActivity.this.getText(R.string.favorite_open)).setCancelable(true) .setPositiveButton(FavoriteActivity.this.getText(R.string.favorite_open_details), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { new FeedItemDisplayTask(activity, currentServer, f.getUrl(), FeedItemDisplayTask.DISPLAY_DETAILS).execute(); } }).setNegativeButton(FavoriteActivity.this.getText(R.string.favorite_open_folder), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { new FeedItemDisplayTask(activity, currentServer, f.getUrl(), FeedItemDisplayTask.DISPLAY_FOLDER).execute(); } }); AlertDialog alert = builder.create(); alert.show(); } } else { ActionUtils.displayMessage(this, R.string.favorite_error); } } 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.favorite_option)); menu.add(0, 1, 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; } Favorite favorite = (Favorite) getListView().getItemAtPosition(menuInfo.position); switch (menuItem.getItemId()) { case 1: if (favorite != null) { delete(favorite.getId()); } return true; default: return super.onContextItemSelected(menuItem); } } public void delete(long id){ Database db = Database.create(this); FavoriteDAO favoriteDao = new FavoriteDAO(db.open()); if (favoriteDao.delete(id)) { Toast.makeText(this, this.getString(R.string.favorite_delete), Toast.LENGTH_LONG).show(); createFavoriteList(); } else { Toast.makeText(this, this.getString(R.string.favorite_delete_error), Toast.LENGTH_LONG).show(); } db.close(); } private boolean initRepository() { boolean init = true; try { if (getRepository() == null) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { // Case if we change repository. if (firstStart) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { init = false; } } } catch (FeedLoadException fle) { ActionUtils.displayMessage(activity, R.string.generic_error); } return init; } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/FavoriteActivity.java
Java
asf20
6,063