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 net.cardgame.orcalecard.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import android.util.Log; public class XmlParserInfoApp { public XmlParserInfoApp() { } public String getXmlFromUrl(String url) { String xml = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); // xml = EntityUtils.toString(httpEntity); InputStream inputStream = httpEntity.getContent(); xml = convertStreamToString(inputStream); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return xml; } public static String convertStreamToString(InputStream is) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); return sb.toString(); } public Document getDomElement(String xml) { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = (Document) db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error1: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error2: ", e.getMessage()); return null; } catch (IOException e) { Log.e("Error3: ", e.getMessage()); return null; } return doc; } /** * Getting node value * * @param elem * element */ public final String getElementValue(Node elem) { Node child; if (elem != null) { if (elem.hasChildNodes()) { for (child = elem.getFirstChild(); child != null; child = child .getNextSibling()) { if (child.getNodeType() == Node.TEXT_NODE) { return child.getNodeValue(); } } } } return ""; } /** * Getting node value * * @param Element * node * @param key * string * */ public String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); return this.getElementValue(n.item(0)); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/utils/XmlParserInfoApp.java
Java
art
3,353
package net.cardgame.orcalecard.utils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; 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.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import net.cardgame.oraclecard.service.DownloadUnzipObject; import net.cardgame.oraclecard.service.ServiceDownloadListener; import net.lingala.zip4j.core.ZipFile; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.io.ZipInputStream; import net.lingala.zip4j.model.FileHeader; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Shader.TileMode; import android.os.Environment; import android.os.StatFs; import android.util.Log; /** * Lớp xử lý chung các vấn đề về File * */ public class FileUtils { static double totalTime = 0; private ServiceDownloadListener listener; private DownloadUnzipObject downloadUnzipObject; private boolean cancel = false; public void stopUnzip() { cancel = true; } private synchronized void setPercentDownload(int percent) { downloadUnzipObject.setPercent(percent); synchronized (listener) { if (listener != null) { listener.onUpdateProgressListener( downloadUnzipObject.getPercent(), downloadUnzipObject.getPosition(), downloadUnzipObject.getDeckId()); } } } public void registryUnzipListener(ServiceDownloadListener listener) { this.listener = listener; } public FileUtils() { // TODO Auto-generated constructor stub } /** * Mã hóa file * * @param sourcePath * @param destinationPath * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static void encrypt(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // Here you read the cleartext. FileInputStream fis = new FileInputStream(sourcePath); // This stream write the encrypted text. This stream will be wrapped by // another stream. FileOutputStream fos = new FileOutputStream(destinationPath); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[4096]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); } /** * Giải mã file * * @param sourcePath * @param destinationPath * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static void decrypt(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(sourcePath); FileOutputStream fos = new FileOutputStream(destinationPath); SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[4096]; while ((b = cis.read(d)) != -1) { fos.write(d, 0, b); } fos.flush(); fos.close(); cis.close(); } /** * * Giải mã file thành byte[] để xử lý * * @param sourcePath * @param destinationPath * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public static byte[] decryptToByteArray(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(sourcePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[4096]; while ((b = cis.read(d)) != -1) { bos.write(d, 0, b); } bos.flush(); cis.close(); return bos.toByteArray(); } public static byte[] testDecrytToByteArray(String sourcePath, String destinationPath) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { FileInputStream fis = new FileInputStream(sourcePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); CipherInputStream cis = new CipherInputStream(fis, cipher); int b; byte[] d = new byte[4096]; b = cis.read(d); cis.close(); bos.write(d, 0, b); boolean firstByte = true; while ((b = fis.read(d)) != -1) { if (firstByte) { firstByte = false; continue; } bos.write(d, 0, b); } bos.flush(); fis.close(); return bos.toByteArray(); } public static InputStream decrytToInputStream(String sourcePath) { try { return new ByteArrayInputStream(decryptToByteArray(sourcePath, "")); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* Checks if external storage is available for read and write */ public static boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } /* Checks if external storage is available to at least read */ public static boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } static final int FILE_IMAGE_RESIZE = 1; static final int FILE_IMAGE_UNZIP = 2; static final int FILE_TEXT = 3; int getFileType(String fileName, String strDeckId) { if (fileName.contains("txt")) return FILE_TEXT; else if (fileName.contains("c" + strDeckId)) { fileName = fileName.substring(3, 5); if (convertStringToNumber(fileName) > 0) return FILE_IMAGE_RESIZE; else return FILE_IMAGE_UNZIP; } return FILE_IMAGE_UNZIP; } int convertStringToNumber(String str) { try { int i = Integer.parseInt(str); return i; } catch (Exception ex) { return -1; } } void testEncryptInputStream(byte[] data, String pathOutput) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException { InputStream inStreamX = new ByteArrayInputStream(data); FileOutputStream fosX = new FileOutputStream(pathOutput); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipherX = Cipher.getInstance("AES"); cipherX.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cosX = new CipherOutputStream(fosX, cipherX); // Writes bytes int b; byte[] d = new byte[4096]; // boolean firstByte = true; while ((b = inStreamX.read(d)) != -1) { cosX.write(d, 0, b); } cosX.flush(); cosX.close(); inStreamX.close(); } void testEncryptInputStream(ZipInputStream inputStream, FileOutputStream outputStream) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException { // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(outputStream, cipher); // Writes bytes int b; byte[] d = new byte[4096]; while ((b = inputStream.read(d)) != -1) { cos.write(d, 0, b); } cos.flush(); cos.close(); inputStream.close(); } public boolean unzipFile(DownloadUnzipObject object) { this.downloadUnzipObject = object; return unzipFile(object.getPathSaveFile(), object.getDeckId(), object.getPosition()); } /** * Create by hungcv * * perform unzipFile, create images X/2, X/3 and encrypt file * * @param path * path of zip file * @param deckId * deckBeanId * @return */ public boolean unzipFile(String path, int deckId, int position) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; String pathFolderUnzip = path.replaceAll(".zip", ""); String pathX2 = pathFolderUnzip + "/X2"; String pathX3 = pathFolderUnzip + "/X3"; File dirX2 = new File(pathX2); File dirX3 = new File(pathX3); dirX2.mkdirs(); dirX3.mkdirs(); try { ZipFile zipFile = new ZipFile(path); // if Zip file is password protected then set the password if (zipFile.isEncrypted()) { zipFile.setPassword(ConstantValue.PASSWORD); } // Get a list of FileHeader. FileHeader is the header information // for all the files in the ZipFile List listFileHeader = zipFile.getFileHeaders(); int size = listFileHeader.size(); int cardNumber = 0; for (int i = 0; i < size; i++) { FileHeader fileHeader = (FileHeader) listFileHeader.get(i); if (fileHeader.isDirectory()) continue; String fileName = fileHeader.getFileName(); fileName = fileName.split("\\/")[1]; if (getFileType(fileName, strDeckId) == FILE_IMAGE_RESIZE) { cardNumber++; } } int numberFileFinished = 0; for (int i = 0; i < size; i++) { if (cancel) return false; FileHeader fileHeader = (FileHeader) listFileHeader.get(i); if (fileHeader.isDirectory()) { continue; } String fileName = fileHeader.getFileName(); fileName = fileName.split("\\/")[1]; int typeFile = getFileType(fileName, strDeckId); if (typeFile != FILE_IMAGE_RESIZE) { // Utils.DLog("File Type", "FILE_ONLY_UNZIP"); String pathFileJPG = pathFolderUnzip + "/en_" + fileName; ZipInputStream in = zipFile.getInputStream(fileHeader); FileOutputStream fosjpg = new FileOutputStream(pathFileJPG); // encypt file testEncryptInputStream(in, fosjpg); } else { // Utils.DLog("File Type", "FILE_IMAGE_RESIZE"); String pathFileX = pathFolderUnzip + "/en_" + fileName; String pathFileX2 = pathX2 + "/en_" + fileName; String pathFileX3 = pathX3 + "/en_" + fileName; Bitmap bmpX = BitmapFactory.decodeStream(zipFile .getInputStream(fileHeader)); ByteArrayOutputStream streamX = new ByteArrayOutputStream(); bmpX.compress(Bitmap.CompressFormat.PNG, 0, streamX); byte[] byteArrayX = streamX.toByteArray(); testEncryptInputStream(byteArrayX, pathFileX); // // Create image X2 Bitmap bmpX2 = resizeBitmap(bmpX, 2); bmpX.recycle(); ByteArrayOutputStream streamX2 = new ByteArrayOutputStream(); bmpX2.compress(Bitmap.CompressFormat.PNG, 0, streamX2); byte[] byteArrayX2 = streamX2.toByteArray(); testEncryptInputStream(byteArrayX2, pathFileX2); // Create image X3 Bitmap bmpX3 = resizeBitmap(bmpX2, 4); bmpX2.recycle(); ThreadCreateX3Image threadX3 = new ThreadCreateX3Image( bmpX3, pathFileX3); threadX3.start(); numberFileFinished++; // report percent download if (downloadUnzipObject != null) { int percent = (int) (((float) numberFileFinished / (float) cardNumber) * 49); this.setPercentDownload(50 + percent); } } } } catch (ZipException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } if (downloadUnzipObject != null) { this.setPercentDownload(100); } File fileRoot = new File(path); fileRoot.delete(); return true; } class ThreadCreateX3Image extends Thread { Bitmap bmp; String path; public ThreadCreateX3Image(Bitmap bmp, String path) { this.bmp = bmp; this.path = path; } @Override public void run() { // TODO Auto-generated method stub try { ByteArrayOutputStream arrayOs = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 0, arrayOs); bmp.recycle(); byte[] byteArray = arrayOs.toByteArray(); InputStream inStreamX = new ByteArrayInputStream(byteArray); FileOutputStream fosX = new FileOutputStream(path); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipherX = Cipher.getInstance("AES"); cipherX.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cosX = new CipherOutputStream(fosX, cipherX); // Writes bytes int b; byte[] d = new byte[4096]; // boolean firstByte = true; while ((b = inStreamX.read(d)) != -1) { cosX.write(d, 0, b); } cosX.flush(); cosX.close(); inStreamX.close(); ; } catch (Exception ex) { } } } /* * Sau khi download xong file zip ve thuc hien xu ly: - Load tu dau toi cuoi * file zip - Toi fileHeader nao: + Neu header la PNG: * Tao cac X2, X3 * Ma * hoa cac X, X3, X2 * Ghi X, X2, X3 ra sdcard + Neu header la TXT: * ma hoa * cac text file * ghi cac text file ra sdcard */ public boolean processFileZip(String pathFileZip) { String strDECKID = getDeckId(pathFileZip); String pathFolderUnzip = getFolder(pathFileZip) + "/Card_" + strDECKID; String pathFolderX2 = pathFolderUnzip + "/X2"; String pathFolderX3 = pathFolderUnzip + "/X3"; File dirX2 = new File(pathFolderX2); File dirX3 = new File(pathFolderX3); dirX2.mkdirs(); dirX3.mkdirs(); try { ZipFile zipFile = new ZipFile(pathFileZip); // if Zip file is password protected then set the password if (zipFile.isEncrypted()) { zipFile.setPassword(ConstantValue.PASSWORD); } // Get a list of FileHeader. FileHeader is the header information // for all the files in the ZipFile List listFileHeader = zipFile.getFileHeaders(); // Loop through all the fileHeaders for (int i = 0; i < listFileHeader.size(); i++) { FileHeader fileHeader = (FileHeader) listFileHeader.get(i); // Checks if the file is a directory if (fileHeader.isDirectory()) { continue; } /* * THUC HIEN XU LY FILE Background "*.jpg" */ boolean kJPG = filterFileHeader(fileHeader.getFileName(), "jpg"); if (kJPG) { String nameFile = fileHeader.getFileName().split("\\/")[1]; String pathFileJPG = pathFolderUnzip + "/en_" + nameFile; ZipInputStream in = zipFile.getInputStream(fileHeader); FileOutputStream fosjpg = new FileOutputStream(pathFileJPG); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fosjpg, cipher); // Write bytes int b; byte[] d = new byte[4096]; while ((b = in.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); in.close(); } /* * THUC HIEN XU LY CAC FILE *.txt */ boolean kTXT = filterFileHeader(fileHeader.getFileName(), "txt"); if (kTXT) { String nameFile = fileHeader.getFileName().split("\\/")[1]; String pathFileText = pathFolderUnzip + "/en_" + nameFile; ZipInputStream inputStream = zipFile .getInputStream(fileHeader); FileOutputStream fostext = new FileOutputStream( pathFileText); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fostext, cipher); // Write bytes int b; byte[] d = new byte[4096]; while ((b = inputStream.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); inputStream.close(); } /* * THUC HIEN XU LY CAC FILE *.png */ boolean kPNG = filterFileHeader(fileHeader.getFileName(), "png"); if (kPNG) { String nameFile = fileHeader.getFileName().split("\\/")[1]; String pathFileX = pathFolderUnzip + "/en_" + nameFile; String pathFileX2 = pathFolderX2 + "/en_" + nameFile; String pathFileX3 = pathFolderX3 + "/en_" + nameFile; // File fileX = new File("", // fileHeader.getFileName().split("\\/")[1]); Bitmap bmpX = BitmapFactory.decodeStream(zipFile .getInputStream(fileHeader)); Bitmap bmpX2 = resizeBitmap(bmpX, 2); Bitmap bmpX3 = resizeBitmap(bmpX, 3); // convert bitmap -> byte array ByteArrayOutputStream streamX = new ByteArrayOutputStream(); ByteArrayOutputStream streamX2 = new ByteArrayOutputStream(); ByteArrayOutputStream streamX3 = new ByteArrayOutputStream(); bmpX.compress(Bitmap.CompressFormat.PNG, 0, streamX); bmpX.recycle(); bmpX2.compress(Bitmap.CompressFormat.PNG, 0, streamX2); bmpX2.recycle(); bmpX3.compress(Bitmap.CompressFormat.PNG, 0, streamX3); bmpX3.recycle(); byte[] byteArrayX = streamX.toByteArray(); byte[] byteArrayX2 = streamX2.toByteArray(); byte[] byteArrayX3 = streamX3.toByteArray(); // convert byte array -> inputstream InputStream inStreamX = new ByteArrayInputStream(byteArrayX); InputStream inStreamX2 = new ByteArrayInputStream( byteArrayX2); InputStream inStreamX3 = new ByteArrayInputStream( byteArrayX3); FileOutputStream fosX = new FileOutputStream(pathFileX); FileOutputStream fosX2 = new FileOutputStream(pathFileX2); FileOutputStream fosX3 = new FileOutputStream(pathFileX3); // Length is 16 byte SecretKeySpec sks = new SecretKeySpec( ConstantValue.FILE_SECRET_KEY.getBytes(), "AES"); // Create cipher Cipher cipherX = Cipher.getInstance("AES"); Cipher cipherX2 = Cipher.getInstance("AES"); Cipher cipherX3 = Cipher.getInstance("AES"); cipherX.init(Cipher.ENCRYPT_MODE, sks); cipherX2.init(Cipher.ENCRYPT_MODE, sks); cipherX3.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cosX = new CipherOutputStream(fosX, cipherX); CipherOutputStream cosX2 = new CipherOutputStream(fosX2, cipherX2); CipherOutputStream cosX3 = new CipherOutputStream(fosX3, cipherX3); // Writes bytes int b; byte[] d = new byte[4096]; while ((b = inStreamX.read(d)) != -1) { cosX.write(d, 0, b); } cosX.flush(); cosX.close(); inStreamX.close(); while ((b = inStreamX2.read(d)) != -1) { cosX2.write(d, 0, b); } cosX2.flush(); cosX2.close(); inStreamX2.close(); while ((b = inStreamX3.read(d)) != -1) { cosX3.write(d, 0, b); } cosX3.flush(); cosX3.close(); inStreamX3.close(); } Log.d("Done extracting: ", fileHeader.getFileName()); } } catch (ZipException e) { Log.e("ZipException", e.toString()); return false; } catch (FileNotFoundException e) { Log.e("FileNotFoundException", e.toString()); return false; } catch (IOException e) { Log.e("IOException", e.toString()); return false; } catch (Exception e) { Log.e("Exception", e.toString()); return false; } // Xoa file zip sau khi xu ly hoan thanh File f = new File(pathFileZip); f.delete(); return true; } public boolean filterFileHeader(String fileHeader, String filter) { boolean check = false; String[] sub = fileHeader.split("\\."); String s = sub[1]; if (s.equalsIgnoreCase(filter)) check = true; return check; } // Nếu s = "/mnt/sdcard/testpass.zip" // Thì folderName = "/mnt/sdcard" public String getFolder(String s) { String folderName = ""; for (int i = s.length() - 1; i >= 0; i--) { if (s.charAt(i) == '/') { folderName = s.substring(0, i); break; } } return folderName; } // Lấy về tất cả các file trong folder ung voi bo loc "filter" public ArrayList<String> getListFile(String pathFolder, String filter) { ArrayList<String> tmpList = new ArrayList<String>(); ArrayList<String> list = new ArrayList<String>(); File f = new File(pathFolder); // Kiểm tra folder tồn tại hay không // Hoặc có phải là thư mục hay không if (!f.exists() || !f.isDirectory()) { return null; } String[] files = f.list(); if (files.length == 0) { // Không có file nào trong folder return null; } for (int i = 0; i < files.length; i++) { tmpList.add(files[i]); } for (int i = 0; i < tmpList.size(); i++) { String s = tmpList.get(i); String typeFile = s.substring(s.length() - 3, s.length()); if (typeFile.equalsIgnoreCase(filter)) list.add(s); } return list; } /* * Resize lai kich thuoc bitmap */ public Bitmap resizeBitmap(Bitmap bmp, int i) { int width = 0, height = 0; switch (i) { case 2: width = bmp.getWidth() / 2; height = bmp.getHeight() / 2; break; case 3: width = bmp.getWidth() / 3; height = bmp.getHeight() / 3; case 4: width = (int) (bmp.getWidth() / 1.5); height = (int) (bmp.getHeight() / 1.5); default: break; } Bitmap resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height, true); return resizedbitmap; } @SuppressWarnings("resource") public static byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); // Get the size of the file long length = file.length(); // You cannot create an array using a long type. // It needs to be an int type. // Before converting to an int type, check // to ensure that file is not larger than Integer.MAX_VALUE. if (length > Integer.MAX_VALUE) { // File is too large } // Create the byte array to hold the data byte[] bytes = new byte[(int) length]; // Read in the bytes int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, Math.min(bytes.length - offset, 512 * 1024))) >= 0) { offset += numRead; } // Ensure all the bytes have been read in if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } // Close the input stream and return bytes is.close(); return bytes; } // get deckId from path filezip public String getDeckId(String pathFileZip) { String subPath = ""; String[] arr = null; arr = pathFileZip.split("\\/"); subPath = arr[arr.length - 1]; arr = subPath.split("\\_"); subPath = arr[arr.length - 1]; arr = subPath.split("\\."); subPath = arr[0]; return subPath; } public static void CopyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes = new byte[buffer_size]; for (;;) { int count = is.read(bytes, 0, buffer_size); if (count == -1) break; os.write(bytes, 0, count); } } catch (Exception ex) { } } public static Bitmap createReflectedImage(Bitmap b) { final int reflectionGap = 10; Bitmap originalImage = b; int width = originalImage.getWidth(); int height = originalImage.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(1, -1); Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height / 2, width, height / 2, matrix, false); Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height / 2), Config.ARGB_8888); Canvas canvas = new Canvas(bitmapWithReflection); canvas.drawBitmap(originalImage, 0, 0, null); // Paint deafaultPaint = new Paint(); // canvas.drawRect(0, height, width, height + reflectionGap, // deafaultPaint); canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null); Paint paint = new Paint(); LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.CLAMP); paint.setShader(shader); paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint); return bitmapWithReflection; } /** * @param downloadsize * byte * @return true: SDCARD available * * <br> * false:SDCARD unvailable */ public static boolean availableDownload(double downloadsize) { StatFs stat = new StatFs(Environment.getExternalStorageDirectory() .getPath()); double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize(); return sdAvailSize > 3 * downloadsize; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/utils/FileUtils.java
Java
art
27,662
package net.cardgame.orcalecard.utils; import android.app.Activity; import android.view.inputmethod.InputMethodManager; public class KeyboardHelper { public static void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager) activity .getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus() .getWindowToken(), 0); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/utils/KeyboardHelper.java
Java
art
457
package net.cardgame.orcalecard.utils; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.HistoryBean; public class Sort { public static final Comparator<DeckBean> RELEASE_ORDER = new Comparator<DeckBean>() { public int compare(DeckBean d1, DeckBean d2) { return d1.releaseDate.compareTo(d2.releaseDate); } }; static final Comparator<DeckBean> BUY_ORDER = new Comparator<DeckBean>() { public int compare(DeckBean d1, DeckBean d2) { return d1.buyDate.compareTo(d2.buyDate); } }; static final Comparator<DeckBean> USED_ORDER = new Comparator<DeckBean>() { public int compare(DeckBean d1, DeckBean d2) { return d1.lastUsedDate.compareTo(d2.lastUsedDate); } }; static final Comparator<HistoryBean> DATE_ORDER = new Comparator<HistoryBean>() { public int compare(HistoryBean d1, HistoryBean d2) { return d1.datetime.compareTo(d2.datetime); } }; public static ArrayList<HistoryBean> sortHistoryByDate( ArrayList<HistoryBean> list) { Collections.sort(list, DATE_ORDER); Collections.reverse(list); return list; } public static ArrayList<DeckBean> sortByRelease(ArrayList<DeckBean> list) { Collections.sort(list, RELEASE_ORDER); Collections.reverse(list); return list; } public static ArrayList<DeckBean> sortByBuy(ArrayList<DeckBean> list) { Collections.sort(list, BUY_ORDER); Collections.reverse(list); return list; } public static ArrayList<DeckBean> sortByLastUsed(ArrayList<DeckBean> list) { Collections.sort(list, USED_ORDER); Collections.reverse(list); return list; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/utils/Sort.java
Java
art
1,722
package net.cardgame.orcalecard.utils; import java.lang.reflect.Type; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import android.content.Context; import android.os.Environment; import android.os.StatFs; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ConstantValue { public static final int RESULT_ACTIVITY = 7; public static final int SAVE_HISTORY_ACTIVITY = 8; public static final String CONFIG_DECKBEAN_KEY = "list_deckbean"; public static final int CURRENT_API_VERSION = android.os.Build.VERSION.SDK_INT; // base url cho API public static final String BASE_URL = "http://www.jma-inc.jp/appdata/OracleCard/"; // key history shared reference public static final String HISTORY_KEY = "history_sharedreference"; // key setting app shared reference public static final String SETTING_KEY = "setting_sharedreference"; // url của file chứa danh sách deck public static final String LIST_DECK_SUB_URL = "ConfigAndroid.xml"; // key sharedreference để kiểm tra đã load hết dữ liệu màn hình toppage chưa public static final String KEY_LOAD_FINISHED_TOPPAGE = "key_toppage_finished"; // key để mã hóa/giải mã File public static String FILE_SECRET_KEY = "MyDifficultPassw"; public static String PREFERENCES_SECRET_KEY = "runsystem"; // public static final String ACTION_DOWNLOAD = "download action"; // Cú pháp shared preferences public static String PREFERENCES_DECK_PREFIX = "DECK"; public static String PREFERENCES_CARD_PREFIX = "CARD"; // Name shared preferences public static String APP_PREFERENCES = "net.oraclecard"; // Key shared preferences public static String CONFIG_XML = "CONFIG_XML"; // public static String PASSWORD = "105af58a06470c1c0d686fdf0134485c"; public static String URL_XML_INFOAPP = "http://doreen.jp/apnews.xml"; public static SettingApp getSettingApp(Context context) { SettingApp setting = new SettingApp(); SecurePreferences appPreferences = new SecurePreferences(context, APP_PREFERENCES, PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); setting = gson.fromJson(strSetting, SettingAppType); } return setting; } public static String getBasePatchApp(Context context) { return context.getApplicationContext().getExternalFilesDir(null) .getPath(); } public static String getPatchCardData(Context context) { return getBasePatchApp(context) + "/Card_Data/"; } public static String getPathCard00(Context context, int deckId) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; return getPatchCardData(context) + "Card_" + strDeckId + "/en_c" + strDeckId + "d.png"; } public static String getPathDeckImage(Context context, int deckId, String prefix) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; return getPatchCardData(context) + "Card_" + strDeckId + "/en_c" + strDeckId + prefix + ".png"; } public static String getPathBackgroundByDeckId(Context context, int deckId) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; return getPatchCardData(context) + "Card_" + strDeckId + "/en_bg" + strDeckId + ".jpg"; } public static final int X1 = 1; public static final int X2 = 2; public static final int X3 = 3; public static String getPathCardDetail(Context context, int deckId, int cardId, int sizeType) { String strDeckId = deckId < 10 ? "0" + deckId : "" + deckId; String strCardId = cardId < 10 ? "0" + cardId : "" + cardId; String strSize = ""; switch (sizeType) { case X2: strSize = "/X2/"; break; case X3: strSize = "/X3/"; break; default: break; } String path = getPatchCardData(context) + "Card_" + strDeckId + strSize + "/en_c" + strDeckId + strCardId + ".png"; return path; } /** * Check available free space on SD card * * @return true if free space SD card > required size */ public static boolean isAvailableSpaceSDCard(int sizeRequiredMB) { StatFs stat = new StatFs(Environment.getExternalStorageDirectory() .getPath()); double sdAvailSize = (double) stat.getAvailableBlocks() * (double) stat.getBlockSize(); // One binary MB equals 1024*1024 bytes. double minSize = sizeRequiredMB * 1024 * 1024; if (sdAvailSize > minSize) return true; else return false; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/utils/ConstantValue.java
Java
art
4,704
package net.cardgame.orcalecard; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.MySwitch; import net.cardgame.orcalecard.bean.SettingApp; import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; public class SettingSortActivity extends Activity implements OnClickListener, OnCheckedChangeListener { int sortby = 0; MySwitch switchRelease, switchPayment, switchUsed; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.setting_sort_layout); findViewById(R.id.btn_back_setting_sort).setOnClickListener(this); Bundle bundle = this.getIntent().getExtras(); sortby = bundle.getInt("sort_by"); switchRelease = (MySwitch) findViewById(R.id.switch_by_release); switchPayment = (MySwitch) findViewById(R.id.switch_by_payment); switchUsed = (MySwitch) findViewById(R.id.switch_by_used); switchUsed.setOnCheckedChangeListener(this); switchRelease.setOnCheckedChangeListener(this); switchPayment.setOnCheckedChangeListener(this); switchUsed.setChecked(false); switchRelease.setChecked(false); switchPayment.setChecked(false); switch (sortby) { case SettingApp.SORT_BY_RELEASE: switchRelease.setChecked(true); break; case SettingApp.SORT_BY_USED: switchUsed.setChecked(true); break; case SettingApp.SORT_BY_BUY: switchPayment.setChecked(true); break; default: break; } } @Override public void onClick(View v) { // TODO Auto-generated method stub setResult(sortby); this.finish(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (!isChecked && !switchUsed.isChecked() && !switchRelease.isChecked() && !switchPayment.isChecked()) { sortby = SettingApp.SORT_BY_RELEASE; } switch (buttonView.getId()) { case R.id.switch_by_payment: if (isChecked) { sortby = SettingApp.SORT_BY_BUY; switchUsed.setChecked(false); switchRelease.setChecked(false); } break; case R.id.switch_by_release: if (isChecked) { sortby = SettingApp.SORT_BY_RELEASE; switchUsed.setChecked(false); switchPayment.setChecked(false); } break; case R.id.switch_by_used: if (isChecked) { sortby = SettingApp.SORT_BY_USED; switchRelease.setChecked(false); switchPayment.setChecked(false); } break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { setResult(sortby); this.finish(); } return super.onKeyDown(keyCode, event); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/SettingSortActivity.java
Java
art
3,065
package net.cardgame.orcalecard; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import android.graphics.Bitmap; import android.util.Log; public class GalleryMemoryCache { private static final String TAG = "MemoryCache"; // Last argument true for LRU ordering private Map<String, Bitmap> cache = Collections .synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true)); // current allocated size private long size = 0; // max memory in bytes private long limit = 1000000; public GalleryMemoryCache() { // use 25% of available heap size setLimit(Runtime.getRuntime().maxMemory() / 4); } public void setLimit(long new_limit) { limit = new_limit; Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB"); } public Bitmap get(String id) { try { if (!cache.containsKey(id)) return null; // NullPointerException sometimes happen here // http://code.google.com/p/osmdroid/issues/detail?id=78 return cache.get(id); } catch (NullPointerException ex) { ex.printStackTrace(); return null; } } public void put(String id, Bitmap bitmap) { try { if (cache.containsKey(id)) size -= getSizeInBytes(cache.get(id)); cache.put(id, bitmap); size += getSizeInBytes(bitmap); checkSize(); } catch (Throwable th) { th.printStackTrace(); } } private void checkSize() { Log.i(TAG, "cache size=" + size + " length=" + cache.size()); if (size > limit) { // Least recently accessed item will be the first one iterated Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator(); while (iter.hasNext()) { Entry<String, Bitmap> entry = iter.next(); size -= getSizeInBytes(entry.getValue()); iter.remove(); if (size <= limit) break; } Log.i(TAG, "Clean cache. New size " + cache.size()); } } public void clear() { try { // NullPointerException sometimes happen here // http://code.google.com/p/osmdroid/issues/detail?id=78 cache.clear(); size = 0; } catch (NullPointerException ex) { ex.printStackTrace(); } } long getSizeInBytes(Bitmap bitmap) { if (bitmap == null) return 0; return bitmap.getRowBytes() * bitmap.getHeight(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/GalleryMemoryCache.java
Java
art
2,380
package net.cardgame.orcalecard.pref; import java.util.Iterator; import java.util.Map; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class GalleryPreferences { public static final int MODE = Context.MODE_PRIVATE; public static final String PREF_GALLERY = "GALLERY_PREFERENCES"; public static void writeString(Context context, String key, String value) { getEditor(context).putString(key, value).commit(); } public static String readString(Context context, String key, String defValue) { return getPreferences(context).getString(key, defValue); } public static SharedPreferences getPreferences(Context context) { return context.getSharedPreferences(PREF_GALLERY, MODE); } public static Editor getEditor(Context context) { return getPreferences(context).edit(); } @SuppressWarnings("rawtypes") public static boolean checkKey(Context context, String key) { SharedPreferences sharedPreferences = getPreferences(context); Iterator iter = sharedPreferences.getAll().entrySet().iterator(); while (iter.hasNext()) { Map.Entry pair = (Map.Entry)iter.next(); if (pair.getKey().toString().equals(key)) return true; } return false; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/pref/GalleryPreferences.java
Java
art
1,329
package net.cardgame.orcalecard.pref; /* Copyright (C) 2012 Sveinung Kval Bakken, sveinung.bakken@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.content.Context; import android.content.SharedPreferences; import android.util.Base64; /** * Lớp share Preferences đã xử lý mã hóa Sử dụng hàm put, get String * */ public class SecurePreferences { public static class SecurePreferencesException extends RuntimeException { public SecurePreferencesException(Throwable e) { super(e); } } private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; private static final String KEY_TRANSFORMATION = "AES/ECB/PKCS5Padding"; private static final String SECRET_KEY_HASH_TRANSFORMATION = "SHA-256"; private static final String CHARSET = "UTF-8"; private final boolean encryptKeys; private final Cipher writer; private final Cipher reader; private final Cipher keyWriter; private final SharedPreferences preferences; /** * This will initialize an instance of the SecurePreferences class * * @param context * your current context. * @param preferenceName * name of preferences file (preferenceName.xml) * @param secureKey * the key used for encryption, finding a good key scheme is * hard. Hardcoding your key in the application is bad, but * better than plaintext preferences. Having the user enter the * key upon application launch is a safe(r) alternative, but * annoying to the user. * @param encryptKeys * settings this to false will only encrypt the values, true will * encrypt both values and keys. Keys can contain a lot of * information about the plaintext value of the value which can * be used to decipher the value. * @throws SecurePreferencesException */ public SecurePreferences(Context context, String preferenceName, String secureKey, boolean encryptKeys) throws SecurePreferencesException { try { this.writer = Cipher.getInstance(TRANSFORMATION); this.reader = Cipher.getInstance(TRANSFORMATION); this.keyWriter = Cipher.getInstance(KEY_TRANSFORMATION); initCiphers(secureKey); this.preferences = context.getSharedPreferences(preferenceName, Context.MODE_PRIVATE); this.encryptKeys = encryptKeys; } catch (GeneralSecurityException e) { throw new SecurePreferencesException(e); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } } protected void initCiphers(String secureKey) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException { IvParameterSpec ivSpec = getIv(); SecretKeySpec secretKey = getSecretKey(secureKey); writer.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); reader.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); keyWriter.init(Cipher.ENCRYPT_MODE, secretKey); } protected IvParameterSpec getIv() { byte[] iv = new byte[writer.getBlockSize()]; System.arraycopy("fldsjfodasjifudslfjdsaofshaufihadsf".getBytes(), 0, iv, 0, writer.getBlockSize()); return new IvParameterSpec(iv); } protected SecretKeySpec getSecretKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException { byte[] keyBytes = createKeyBytes(key); return new SecretKeySpec(keyBytes, TRANSFORMATION); } protected byte[] createKeyBytes(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest .getInstance(SECRET_KEY_HASH_TRANSFORMATION); md.reset(); byte[] keyBytes = md.digest(key.getBytes(CHARSET)); return keyBytes; } public void put(String key, String value) { if (value == null) { preferences.edit().remove(toKey(key)).commit(); } else { putValue(toKey(key), value); } } public boolean containsKey(String key) { return preferences.contains(toKey(key)); } public void removeValue(String key) { preferences.edit().remove(toKey(key)).commit(); } public String getString(String key) throws SecurePreferencesException { if (preferences.contains(toKey(key))) { String securedEncodedValue = preferences.getString(toKey(key), ""); return decrypt(securedEncodedValue); } return null; } public void clear() { preferences.edit().clear().commit(); } private String toKey(String key) { if (encryptKeys) return encrypt(key, keyWriter); else return key; } private void putValue(String key, String value) throws SecurePreferencesException { String secureValueEncoded = encrypt(value, writer); preferences.edit().putString(key, secureValueEncoded).commit(); } protected String encrypt(String value, Cipher writer) throws SecurePreferencesException { byte[] secureValue; try { secureValue = convert(writer, value.getBytes(CHARSET)); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } String secureValueEncoded = Base64.encodeToString(secureValue, Base64.NO_WRAP); return secureValueEncoded; } protected String decrypt(String securedEncodedValue) { byte[] securedValue = Base64 .decode(securedEncodedValue, Base64.NO_WRAP); byte[] value = convert(reader, securedValue); try { return new String(value, CHARSET); } catch (UnsupportedEncodingException e) { throw new SecurePreferencesException(e); } } private static byte[] convert(Cipher cipher, byte[] bs) throws SecurePreferencesException { try { return cipher.doFinal(bs); } catch (Exception e) { throw new SecurePreferencesException(e); } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/pref/SecurePreferences.java
Java
art
7,031
package net.cardgame.orcalecard; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.SelectedHistoryListener; import net.cardgame.orcalecard.bean.HistoryBean; import android.annotation.SuppressLint; import android.app.Activity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; @SuppressLint("ResourceAsColor") public class HistoryAdapter extends ArrayAdapter<HistoryBean> implements OnTouchListener, OnClickListener { ArrayList<HistoryBean> listHistory = new ArrayList<HistoryBean>(); Activity context; int x_old = 0, y_old = 0; int selectedId = 0; boolean ontouch = false; SelectedHistoryListener listener; boolean clear = false; public HistoryAdapter(Activity context, ArrayList<HistoryBean> objects) { super(context, R.layout.item_listview_history, objects); // TODO Auto-generated constructor stub this.listHistory = objects; this.context = context; this.listener = (SelectedHistoryListener) context; } static class ViewHolder { TextView txtDateTime; ImageView imgNumberOfCard; TextView txtDeckTitle; TextView txtQuestion; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.item_listview_history, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.txtDateTime = (TextView) rowView .findViewById(R.id.txtDatetime_history); viewHolder.txtDeckTitle = (TextView) rowView .findViewById(R.id.txtdecktitle_history); viewHolder.txtQuestion = (TextView) rowView .findViewById(R.id.txtQuestion_history); viewHolder.imgNumberOfCard = (ImageView) rowView .findViewById(R.id.img_numberofcard_history); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); HistoryBean history = listHistory.get(position); holder.txtDateTime.setText(history.strDateTime); holder.txtDeckTitle.setText(history.deckTitle); holder.txtQuestion.setText(history.question); rowView.setId(listHistory.get(position).id); int size = history.cardBeans.size(); switch (size) { case 1: holder.imgNumberOfCard.setImageResource(R.drawable.result_draw1); break; case 3: holder.imgNumberOfCard.setImageResource(R.drawable.result_draw3); break; case 4: holder.imgNumberOfCard.setImageResource(R.drawable.result_draw4); break; default: break; } rowView.findViewById(R.id.btnDelete_history).setVisibility( View.INVISIBLE); rowView.setOnTouchListener(this); return rowView; } @Override public boolean onTouch(View v, MotionEvent event) { int id = v.getId(); int x = (int) event.getRawX(); int y = (int) event.getRawY(); if (id != selectedId && selectedId != 0) { // clear all row focus this.notifyDataSetChanged(); selectedId = 0; } switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: x_old = x; y_old = y; v.setSelected(true); break; case MotionEvent.ACTION_MOVE: if (x - x_old > 10) { v.setSelected(true); selectedId = v.getId(); ImageView btnDelete = (ImageView) v .findViewById(R.id.btnDelete_history); btnDelete.setVisibility(View.VISIBLE); ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f); anim.setDuration(500); btnDelete.startAnimation(anim); btnDelete.setOnClickListener(this); return false; } break; case MotionEvent.ACTION_UP: if (selectedId == 0) v.setSelected(false); if (Math.abs(x - x_old) < 3 && Math.abs(y - y_old) < 3) { listener.onSelectedItemListener(v.getId()); v.setSelected(false); } break; case MotionEvent.ACTION_CANCEL: if (selectedId == 0) v.setSelected(false); break; default: break; } return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub for (HistoryBean history : listHistory) { if (history.id == selectedId) { selectedId = 0; listHistory.remove(history); this.notifyDataSetChanged(); listener.onDeleteHistory(history); return; } } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/HistoryAdapter.java
Java
art
4,799
package net.cardgame.orcalecard; import java.io.IOException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.NoSuchPaddingException; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.FileUtils; import net.cardgame.orcalecard.utils.Utils; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; public class CardDeckActivity extends Activity implements OnClickListener { int deckId; DeckBean deckBean; final static int SWITCH_1_3 = 99; SettingApp setting; ImageView img_bg_card_deck, img_csdt1_3; Intent intent; boolean flag = true; boolean continueFlow = false; int number_of_card = 0; final static int requestcodeInfoDeck = 10; int cardTotal = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setting = ConstantValue.getSettingApp(this); deckBean = new DeckBean(); Bundle bundle = this.getIntent().getExtras(); deckId = bundle.getInt("deckId"); deckBean.deckId = deckId; if (bundle.containsKey("deckName")) deckBean.deckName = bundle.getString("deckName"); if (bundle.containsKey("deckPrice")) deckBean.deckPrice = bundle.getInt("deckPrice"); if (bundle.containsKey("deckPathServer")) deckBean.pathServerDownload = bundle.getString("deckPathServer"); if (bundle.containsKey("cardTotal")) { cardTotal = bundle.getInt("cardTotal"); } setContentView(R.layout.card_deck_activity); img_csdt1_3 = (ImageView) findViewById(R.id.img_csdt1_3); img_bg_card_deck = (ImageView) findViewById(R.id.img_bg_card_deck); findViewById(R.id.btnhelp_card_deck).setOnClickListener(this); findViewById(R.id.btn_back_to_mypage).setOnClickListener(this); findViewById(R.id.btn_info_deck).setOnClickListener(this); findViewById(R.id.btn_goto_gallery).setOnClickListener(this); findViewById(R.id.btn_setting_card_deck).setOnClickListener(this); findViewById(R.id.btn_select_one_card).setOnClickListener(this); findViewById(R.id.btn_select_three_card).setOnClickListener(this); loadImage(); if (deckId != 999) { loadDataImageThread loadBitmap = new loadDataImageThread(); loadBitmap.start(); } else { continueFlow = true; } } void loadImage() { if (deckId == 999) { img_bg_card_deck.setImageResource(R.drawable.c999t); img_csdt1_3.setImageResource(R.drawable.c999t1_3); return; } new ThreadLoadImage(this, handler1, ConstantValue.getPathDeckImage( this, deckId, "t"), img_bg_card_deck, 1).start(); new ThreadLoadImage(this, handler1, ConstantValue.getPathDeckImage( this, deckId, "t1-3"), img_csdt1_3, 2).start(); } Handler handler1 = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case 1: img_bg_card_deck.setImageDrawable((Drawable) msg.obj); break; case 2: BitmapDrawable drawabe = (BitmapDrawable) msg.obj; if (drawabe != null && !drawabe.getBitmap().isRecycled()) { img_csdt1_3.setImageDrawable((Drawable) msg.obj); continueFlow = true; } break; case 10: gotoSplashActivity(); break; default: break; } } }; @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; else flag = false; switch (v.getId()) { case R.id.btnhelp_card_deck:// go to help Activity intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 4); startActivityForResult(intent, 4); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_back_to_mypage:// back to My Page if (bitmapBackImage != null) { bitmapBackImage.recycle(); } backtoToppageActivity(); break; case R.id.btn_info_deck:// go to deck bean information activity passDeck(deckBean); break; case R.id.btn_goto_gallery:// go to card gallery activity intent = new Intent(this, GalleryActivity.class); intent.putExtras(getIntent().getExtras()); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); break; case R.id.btn_setting_card_deck: // go to deck bean setting activity Intent intent2 = new Intent(this, SettingActiviy.class); startActivityForResult(intent2, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_select_three_card: // selected get three card number_of_card = setting.adviseCard ? 4 : 3; if (deckId == 999) { gotoSplashActivity(); } else new ThreadLoadImage(this, handler1, ConstantValue.getPathBackgroundByDeckId(this, deckId), null, 10).start(); break; case R.id.btn_select_one_card: // selected get one card number_of_card = 1; if (deckId == 999) { gotoSplashActivity(); } else new ThreadLoadImage(this, handler1, ConstantValue.getPathBackgroundByDeckId(this, deckId), null, 10).start(); break; default: break; } } private void gotoSplashActivity() { if (continueFlow) { intent = new Intent(this, SplashDeckBeanActivity.class); intent.putExtras(getIntent().getExtras()); intent.putExtra("number_of_card", number_of_card); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); if (bitmapBackImage != null) { bitmapBackImage.recycle(); } this.finish(); } } /** * @param dec * DeckBean pass to InfoDeckActivity */ public void passDeck(DeckBean dec) { Intent intent = new Intent(this, InfoDeckActivity.class); intent.putExtras(getIntent().getExtras()); intent.putExtra("requestCode", requestcodeInfoDeck); startActivityForResult(intent, requestcodeInfoDeck); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == requestcodeInfoDeck && resultCode == RESULT_FIRST_USER) { this.finish(); } else { setting = ConstantValue.getSettingApp(this); flag = true; overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } } public static Bitmap bitmapBackImage = null; public void loadBitmapToCache() { String strDeckId = (deckId < 10) ? ("0" + deckId) : ("" + deckId); String path = ConstantValue.getPatchCardData(this) + "Card_" + strDeckId + "/en_c" + strDeckId + "d.png"; byte[] bytes = null; try { bytes = FileUtils.decryptToByteArray(path, ""); bitmapBackImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bitmapBackImage != null) bitmapBackImage = FileUtils.createReflectedImage(bitmapBackImage); } Handler handler = new Handler(); class loadDataImageThread extends Thread { public void run() { handler.post(new Runnable() { @Override public void run() { loadBitmapToCache(); } }); } } private void clearCache() { if (deckId != 999) { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "s")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "p")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "m")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "d")); cache.removeFromMemory(ConstantValue.getPathBackgroundByDeckId( this, deckId)); } } @Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); backtoToppageActivity(); } void backtoToppageActivity() { clearCache(); Intent i = new Intent(this, TopPageActivity.class); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/CardDeckActivity.java
Java
art
9,293
package net.cardgame.orcalecard; import java.util.ArrayList; import java.util.HashMap; import jp.jma.oraclecard.R; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.XmlParserInfoApp; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; 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.ListView; public class InfoAppActivity extends Activity implements OnClickListener, OnItemClickListener { // XML node keys private static final String KEY_ENTRY = "entry"; private static final String KEY_TITLE = "title"; private static final String KEY_LINK = "link"; private static final String KEY_SUMMARY = "summary"; private static final String KEY_POSTED = "posted"; private ArrayList<HashMap<String, String>> entrysList; private XmlParserInfoApp parser; private String xml = ""; private String url = ConstantValue.URL_XML_INFOAPP; private ListView listView; private Button btnBack; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.info_app_layout); btnBack = (Button) findViewById(R.id.btnBack); btnBack.setOnClickListener(this); if (NetworkUtils.isNetworkConnected(InfoAppActivity.this)) new LoadDataAsyncTask().execute(); else { showAlertDialog(InfoAppActivity.this, "No Internet Connection", "You don't have internet connection."); } } private class LoadDataAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { dialog = ProgressDialog.show(InfoAppActivity.this, "", "Loading..Wait..", true); dialog.show(); super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { processData(); return null; } @Override protected void onPostExecute(Void result) { dialog.dismiss(); listView = (ListView) findViewById(R.id.listView); AdapterInfoApp adapter = new AdapterInfoApp(InfoAppActivity.this, entrysList); listView.setAdapter(adapter); listView.setOnItemClickListener(InfoAppActivity.this); super.onPostExecute(result); } } public void processData() { entrysList = new ArrayList<HashMap<String, String>>(); parser = new XmlParserInfoApp(); xml = parser.getXmlFromUrl(url); if (xml != null) { xml = xml.substring(xml.indexOf("<entry>"), xml.length()); // Chen tag "<root>" va "</root>" vao dau va cuoi xml xml = "<root>" + xml + "</root>"; Document doc = parser.getDomElement(xml); NodeList nl = doc.getElementsByTagName(KEY_ENTRY); // looping through all song nodes <song> for (int i = 0; i < nl.getLength(); i++) { // creating new HashMap HashMap<String, String> map = new HashMap<String, String>(); Element e = (Element) nl.item(i); // adding each child node to HashMap key => value map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE)); map.put(KEY_LINK, parser.getValue(e, KEY_LINK)); map.put(KEY_SUMMARY, parser.getValue(e, KEY_SUMMARY)); map.put(KEY_POSTED, parser.getValue(e, KEY_POSTED)); // adding HashList to ArrayList entrysList.add(map); } } } @Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) { String url = entrysList.get(position).get(KEY_LINK); if (url != null && url != "") { Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(myIntent); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnBack: finish(); break; default: break; } } // Show dialog alert no internet connection public void showAlertDialog(Context context, String title, String message) { AlertDialog alertDialog = new AlertDialog.Builder(context).create(); // Setting Dialog Title alertDialog.setTitle(title); // Setting Dialog Message alertDialog.setMessage(message); // Setting alert dialog icon alertDialog.setIcon(R.drawable.fail_connect_internet); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); // Showing Alert Message alertDialog.show(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/InfoAppActivity.java
Java
art
4,979
package net.cardgame.orcalecard; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.onDeleteNewsBeanListener; import net.cardgame.orcalecard.bean.NewsBean; import android.annotation.SuppressLint; import android.app.Activity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; class NewsBeanAdapter extends ArrayAdapter<NewsBean> implements OnTouchListener, OnClickListener { ArrayList<NewsBean> listNewsBean = new ArrayList<NewsBean>(); Activity context; boolean ontouch; int x_old; int selectedId = 0; onDeleteNewsBeanListener listener; public NewsBeanAdapter(Activity context, ArrayList<NewsBean> objects) { super(context, R.layout.item_listview_newsbean, objects); // TODO Auto-generated constructor stub listener = (onDeleteNewsBeanListener) context; this.listNewsBean = objects; this.context = context; } static class ViewHolder { TextView txtMemory; TextView txtDatetime; ImageView btnDelete; } public void addNewsBean(NewsBean newsbean) { listNewsBean.add(newsbean); this.notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.item_listview_newsbean, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.txtMemory = (TextView) rowView .findViewById(R.id.txtmemory_item_listnewsbean); viewHolder.txtDatetime = (TextView) rowView .findViewById(R.id.txtDatetime_edit_history); viewHolder.btnDelete = (ImageView) rowView .findViewById(R.id.btnDelete_edit_history); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); NewsBean newsbean = listNewsBean.get(position); holder.txtMemory.setText(newsbean.sumary); holder.txtDatetime.setText(newsbean.datetime); holder.btnDelete.setVisibility(View.INVISIBLE); rowView.setId(newsbean.id); rowView.setOnTouchListener(this); return rowView; } @Override public void onClick(View v) { // TODO Auto-generated method stub for (NewsBean newsBean : listNewsBean) { if (newsBean.id == selectedId) { // delete NewsBean listener.onDeleted(newsBean); listNewsBean.remove(newsBean); notifyDataSetChanged(); return; } } } @SuppressLint("ResourceAsColor") @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: x_old = (int) event.getRawX(); if (ontouch) { selectedId = 0; notifyDataSetChanged(); ontouch = false; return false; } break; case MotionEvent.ACTION_MOVE: int x = (int) event.getRawX(); if (Math.abs(x - x_old) > 5) { ontouch = true; ImageView btnDelete = (ImageView) v .findViewById(R.id.btnDelete_edit_history); btnDelete.setVisibility(View.VISIBLE); selectedId = v.getId(); btnDelete.setOnClickListener(this); ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 1.0f, 1.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f); anim.setDuration(500); btnDelete.startAnimation(anim); } break; case MotionEvent.ACTION_UP: break; default: break; } return true; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/NewsBeanAdapter.java
Java
art
3,887
package net.cardgame.orcalecard; import java.io.ByteArrayInputStream; 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.util.Collections; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jp.jma.oraclecard.R; import net.cardgame.orcalecard.utils.FileUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.widget.ImageView; public class GalleryLoader { GalleryMemoryCache memoryCache = new GalleryMemoryCache(); GalleryFileCache fileCache; private Map<ImageView, String> imageViews = Collections .synchronizedMap(new WeakHashMap<ImageView, String>()); ExecutorService executorService; Handler handler = new Handler();// handler to display images in UI thread private Context mContext; // Ảnh phía sau đối với quân bài thông thường private Bitmap bmpNormalBehind; // Ảnh phía sau của quân bài special private Bitmap bmpSpecialBehind; private int bmpSpecialId = R.drawable.c999d; private boolean isSpecial; public GalleryLoader(Context context, boolean isSpecial) { this.mContext = context; this.isSpecial = isSpecial; fileCache = new GalleryFileCache(context); executorService = Executors.newFixedThreadPool(5); initBitmap(); } private void initBitmap() { bmpSpecialBehind = BitmapFactory.decodeResource( mContext.getResources(), bmpSpecialId); bmpSpecialBehind = Bitmap.createScaledBitmap(bmpSpecialBehind, 280, 400, true); bmpSpecialBehind = FileUtils.createReflectedImage(bmpSpecialBehind); bmpNormalBehind = CardDeckActivity.bitmapBackImage; } public void DisplayImage(String url, ImageView imageView) { imageViews.put(imageView, url); Bitmap bitmap = memoryCache.get(url); if (bitmap != null && !bitmap.isRecycled()) // if (bitmap != null) imageView.setImageBitmap(bitmap); else { // Neu bitmap ma null thi load ảnh phía sau quân bài queuePhoto(url, imageView); // Nếu là bộ deck bình thường if (!isSpecial) { if (bmpNormalBehind != null) { imageView.setImageBitmap(bmpNormalBehind); } } else { // nếu là deck Special if (bmpSpecialBehind != null) { imageView.setImageBitmap(bmpSpecialBehind); } } } } private void queuePhoto(String url, ImageView imageView) { PhotoToLoad p = new PhotoToLoad(url, imageView); executorService.submit(new PhotosLoader(p)); } private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); // from Cache Bitmap b = decodeFile(f); if (b != null) return b; // from SDCard try { Bitmap bitmap = null; byte[] bytes = FileUtils.decryptToByteArray(url, ""); InputStream is = new ByteArrayInputStream(bytes); OutputStream os = new FileOutputStream(f); FileUtils.CopyStream(is, os); is.close(); os.close(); bytes = null; bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } } // decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream stream1 = new FileInputStream(f); BitmapFactory.decodeStream(stream1, null, o); stream1.close(); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 100; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; FileInputStream stream2 = new FileInputStream(f); Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); stream2.close(); return bitmap; } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } return null; } // Task for the queue private class PhotoToLoad { public String url; public ImageView imageView; public PhotoToLoad(String u, ImageView i) { url = u; imageView = i; } } class PhotosLoader implements Runnable { PhotoToLoad photoToLoad; PhotosLoader(PhotoToLoad photoToLoad) { this.photoToLoad = photoToLoad; } @Override public void run() { try { if (imageViewReused(photoToLoad)) return; Bitmap bmp = FileUtils .createReflectedImage(getBitmap(photoToLoad.url)); memoryCache.put(photoToLoad.url, bmp); if (imageViewReused(photoToLoad)) return; BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); handler.post(bd); } catch (Throwable th) { th.printStackTrace(); } } } boolean imageViewReused(PhotoToLoad photoToLoad) { String tag = imageViews.get(photoToLoad.imageView); if (tag == null || !tag.equals(photoToLoad.url)) return true; return false; } // Used to display bitmap in the UI thread class BitmapDisplayer implements Runnable { Bitmap bitmap; PhotoToLoad photoToLoad; public BitmapDisplayer(Bitmap b, PhotoToLoad p) { bitmap = b; photoToLoad = p; } public void run() { if (imageViewReused(photoToLoad)) return; if (bitmap != null) photoToLoad.imageView.setImageBitmap(bitmap); else { if (!isSpecial) { if (bmpNormalBehind != null) { photoToLoad.imageView.setImageBitmap(bmpNormalBehind); } } else { if (bmpSpecialBehind != null) { photoToLoad.imageView.setImageBitmap(bmpSpecialBehind); } } } } } public void clearCache() { memoryCache.clear(); fileCache.clear(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/GalleryLoader.java
Java
art
6,287
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import java.util.Random; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.oraclecard.service.DownloadUnzipObject; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.oraclecard.service.ServiceDownloadListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.Sort; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Top Page Screen */ public class TopPageActivity extends Activity implements OnClickListener, OnItemClickListener, ServiceDownloadListener { private static final int HELP_REQUESTCODE = 0; private static final int RANDOM_REQUESTCODE = 1; private static final int INFO_DECK_REQUESTCODE = 2; private static final int SETTING_REQUESTCODE = 3; private static final int HISTORY_REQUESTCODE = 4; GridView gridView; Intent _i; boolean cancel; ArrayList<DeckBean> listDeckBean; GridViewAdapter adapter; int selectedPosition = 1000; SettingApp setting; SecurePreferences appPreferences; boolean flag = true; private ProgressDialog pDialog; // public final static String KEY_TOPPAGE = "toppage"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.top_activity_layout); gridView = (GridView) findViewById(R.id.grid_view_flash); findViewById(R.id.icon_help_top).setOnClickListener(this); findViewById(R.id.btn_home_toppage).setOnClickListener(this); findViewById(R.id.btn_history_toppage).setOnClickListener(this); findViewById(R.id.btn_setting_toppage).setOnClickListener(this); // init shared reference appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); getStatus(); loadSettingApp(); adapter = new GridViewAdapter(this, listDeckBean); adapter.registryBroadcast(); gridView.setAdapter(adapter); gridView.setOnItemClickListener(this); if (NetworkUtils.isNetworkConnected(this) && getIntent().getExtras() != null) { handlerLoadImage.postDelayed(resumeDownload, 1000); // resumeDownload(); } } Runnable resumeDownload = new Runnable() { @Override public void run() { // TODO Auto-generated method stub resumeDownload(); } }; void getStatus() { Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); listDeckBean = gson.fromJson(listSaved, listOfDeckBean); } private void startDownloadService(DeckBean deckBean, int position) { String id = deckBean.deckId < 10 ? "0" + deckBean.deckId : "" + deckBean.deckId; Intent intentService = new Intent(this, ServiceDownload.class); intentService.putExtra(ServiceDownload.KEY_DECK_ID, deckBean.deckId); intentService.putExtra(ServiceDownload.KEY_PATH_SERVER, deckBean.pathServerDownload + ".zip"); intentService.putExtra(ServiceDownload.KEY_POSITION, position); intentService.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_" + id + ".zip"); startService(intentService); } void resumeDownload() { int i = 0; for (DeckBean deckBean : listDeckBean) { if (deckBean.percentDownloaded >= 0 && deckBean.percentDownloaded < 100) { adapter.setPercentDownloaded(i, deckBean.percentDownloaded); startDownloadService(deckBean, i); showDialogDownload(); return; } i++; } } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); setting = gson.fromJson(strSetting, SettingAppType); } switch (setting.sortToppage) { case SettingApp.SORT_BY_BUY: listDeckBean = Sort.sortByBuy(listDeckBean); break; case SettingApp.SORT_BY_RELEASE: listDeckBean = Sort.sortByRelease(listDeckBean); break; case SettingApp.SORT_BY_USED: listDeckBean = Sort.sortByLastUsed(listDeckBean); break; default: break; } } /** * goto InfoDeck activity * * @param dec */ public void passDeck(DeckBean dec) { if (dec.deckId == 999 || dec.deckId == 998 || appPreferences.containsKey("content_" + dec.deckId) || NetworkUtils.isNetworkConnected(this)) { Intent i = new Intent(this, InfoDeckActivity.class); i.putExtra("deckId", dec.deckId); i.putExtra("deckName", dec.deckName); i.putExtra("deckPrice", dec.deckPrice); i.putExtra("deckPathServer", dec.pathServerDownload); i.putExtra("position", selectedPosition); i.putExtra("isUnlock", dec.isUnlock); i.putExtra("isFree", dec.isFree); i.putExtra("inAppPurchaseId", dec.inAppPurchaseId); i.putExtra("releaseDate", dec.releaseDate.getTime()); startActivityForResult(i, INFO_DECK_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } else { flag = true; showDialogSetting(); } } public void passDeckToCardDeckActivity(DeckBean dec) { _i = new Intent(this, CardDeckActivity.class); _i.putExtra("deckId", dec.deckId); _i.putExtra("deckName", dec.deckName); _i.putExtra("deckPrice", dec.deckPrice); _i.putExtra("deckPathServer", dec.pathServerDownload); _i.putExtra("position", selectedPosition); _i.putExtra("isUnlock", dec.isUnlock); _i.putExtra("cardTotal", dec.cardNumber); if (dec.deckId == 999) { startActivity(_i); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); return; } String tt = dec.deckId < 10 ? "0" + dec.deckId : "" + dec.deckId; new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPatchCardData(this) + "Card_" + tt + "/en_c" + tt + "t.png", null, 1).start(); } private Handler handlerLoadImage = new Handler() { public void handleMessage(Message msg) { startActivity(_i); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); TopPageActivity.this.finish(); }; }; public void passHelpType(int iType) { Intent i = new Intent(this, HelpActivity.class); i.putExtra("indexTypeHelp", iType); startActivityForResult(i, HELP_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } /* * Receive result from another activity */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); switch (requestCode) { case HISTORY_REQUESTCODE: break; case HELP_REQUESTCODE: break; case SETTING_REQUESTCODE: if (resultCode == RESULT_OK) { getStatus(); adapter.updateStatus(listDeckBean); } break; case INFO_DECK_REQUESTCODE: if (resultCode == RESULT_OK) { int positionDownload = data.getExtras().getInt("position"); if (data.getExtras().containsKey("isUnlock")) { Utils.ELog("unlock deckbeans", "ok"); boolean isUnlock = data.getExtras().getBoolean("isUnlock"); listDeckBean.get(positionDownload).isUnlock = isUnlock; adapter.updateStatus(listDeckBean); saveStatus(); } else { Utils.ELog("unlock deckbeans", "no"); if (!listDeckBean.get(positionDownload).isFree) { listDeckBean.get(positionDownload).isUnlock = true; } listDeckBean.get(positionDownload).percentDownloaded = 0; listDeckBean.get(positionDownload).buyDate = new Date(); adapter.setPercentDownloaded(positionDownload, 0); adapter.unlockDeckBean(positionDownload); saveStatus(); showDialogDownload(); } } break; default: break; } } @Override protected void onDestroy() { // TODO Auto-generated method stub adapter.unRegistryBroadcast(); super.onDestroy(); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; switch (v.getId()) { case R.id.icon_help_top: passHelpType(0); flag = false; break; case R.id.btn_home_toppage: backtoMainActivity(); break; case R.id.btn_setting_toppage: Intent intent2 = new Intent(this, SettingActiviy.class); startActivityForResult(intent2, SETTING_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); flag = false; break; case R.id.btn_history_toppage: Intent intent = new Intent(this, HistoryActivity.class); startActivityForResult(intent, HISTORY_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); flag = false; break; default: break; } } /** * Save status downloading DeckBean */ private void saveStatus() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String save = gson.toJson(listDeckBean, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) { // TODO Auto-generated method stub if (flag == false) return; flag = false; selectedPosition = position; DeckBean deckBean; try { deckBean = listDeckBean.get(position); } catch (Exception ex) { flag = true; return; } switch (deckBean.deckId) { // case Special Deck case 999: if (deckBean.isUnlock) { if (setting.listSpecial == null || setting.listSpecial.isEmpty()) { // goto setting special deck startActivityForResult(new Intent(this, SettingSpecialActivity.class), SETTING_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } else { listDeckBean.get(position).lastUsedDate = new Date(); saveStatus(); passDeckToCardDeckActivity(deckBean);// goto card deck } // activity } else passDeck(deckBean); // go to info deck activity return; // case Random Deck case 998: if (deckBean.isUnlock) { // goto random card deck listDeckBean.get(position).lastUsedDate = new Date(); saveStatus(); // gotoRandomDeck(); } else { // go to info deck passDeck(deckBean); } return; default: if (deckBean.percentDownloaded == -2) { listDeckBean.get(position).lastUsedDate = new Date(); saveStatus(); passDeckToCardDeckActivity(deckBean); } else passDeck(deckBean); break; } } void gotoRandomDeck() { ArrayList<DeckBean> list = new ArrayList<DeckBean>(); for (DeckBean deck : listDeckBean) { if (deck.percentDownloaded == -2 || deck.deckId == 999) list.add(deck); } int size = list.size(); Random random = new Random(); DeckBean deckBean = list.get(random.nextInt(size)); Intent intent = new Intent(this, RandomActivity.class); intent.putExtra("deckId", deckBean.deckId); intent.putExtra("deckName", deckBean.deckName); intent.putExtra("deckPrice", deckBean.deckPrice); intent.putExtra("deckPathServer", deckBean.pathServerDownload); intent.putExtra("position", selectedPosition); intent.putExtra("isUnlock", deckBean.isUnlock); intent.putExtra("cardTotal", deckBean.cardNumber); startActivityForResult(intent, RANDOM_REQUESTCODE); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); } @Override protected void onPrepareDialog(int id, Dialog dialog) { // TODO Auto-generated method stub super.onPrepareDialog(id, dialog); } void showDialogDownloadError() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString(R.string.download_error); String message = getResources().getString(R.string.message_redownload); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.show(); } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString( R.string.dialog_errornetwork_title); String message = getResources().getString( R.string.dialog_errornetwork_message); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); builder.show(); } void backtoMainActivity() { Intent i = new Intent(this, MainActivity.class); startActivity(i); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); getStatus(); flag = true; // Load new setting setting = ConstantValue.getSettingApp(this); listDeckBean = adapter.sortDeckBean(setting.sortToppage); } @Override public void onUpdateProgressListener(int percent, int position, int deckId) { // TODO Auto-generated method stub if (pDialog == null || !pDialog.isShowing()) showDialogDownload(); pDialog.setProgress(percent); } @Override public void onDownloadFailListener(DownloadUnzipObject object, String message) { // TODO Auto-generated method stub if (pDialog != null && pDialog.isShowing()) pDialog.dismiss(); if (message != null && message != "") { showDialog(message); return; } if (!NetworkUtils.isNetworkConnected(this)) { showDialogSetting(); } } private void showDialog(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.show(); } @Override public void onFinishedListener(DownloadUnzipObject object) { // TODO Auto-generated method stub getStatus(); if (pDialog != null && pDialog.isShowing()) pDialog.dismiss(); if (adapter != null) adapter.updateStatus(listDeckBean); } private void stopDownload() { Intent intentService = new Intent(this, ServiceDownload.class); intentService.putExtra("cancel", true); startService(intentService); } void showDialogDownload() { pDialog = new ProgressDialog(this); String message = getResources().getString(R.string.downloading_message); String button_cancle = getResources().getString( R.string.btn_cancle_download); pDialog.setMessage(message); pDialog.setIndeterminate(false); pDialog.setMax(100); pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pDialog.setCancelable(false); pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, button_cancle, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); stopDownload(); } }); pDialog.setProgress(0); pDialog.show(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/TopPageActivity.java
Java
art
17,559
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.billingutils.IabHelper; import net.cardgame.oraclecard.billingutils.IabResult; import net.cardgame.oraclecard.billingutils.Inventory; import net.cardgame.oraclecard.billingutils.Purchase; import net.cardgame.oraclecard.common.MySwitch; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class SettingActiviy extends Activity implements OnClickListener, OnCheckedChangeListener { SettingApp setting; SecurePreferences appPreferences; ArrayList<DeckBean> listDeckBean; LinearLayout wait_layout; // / BILLING static final String BILLING_TAG = "DECK BILLING"; static final int PURCHASE_REQUEST = 10001; // The helper object IabHelper mHelper; // public key in developer console String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; boolean isBillingSupport = false; boolean isWait = false; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.setting_app_layout); appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); getStatus(); loadSettingApp(); MySwitch switchJumpCard = (MySwitch) findViewById(R.id.switchJumcard); MySwitch switchAdvise = (MySwitch) findViewById(R.id.switchAdviseCard); MySwitch switchSound = (MySwitch) findViewById(R.id.switchSound); switchJumpCard.setOnCheckedChangeListener(this); switchAdvise.setOnCheckedChangeListener(this); switchSound.setOnCheckedChangeListener(this); switchJumpCard.setChecked(setting.jumCard); switchAdvise.setChecked(setting.adviseCard); switchSound.setChecked(setting.sound); findViewById(R.id.btn_help_setting).setOnClickListener(this); findViewById(R.id.btn_back_setting).setOnClickListener(this); findViewById(R.id.layout_confirm_restore).setOnClickListener(this); findViewById(R.id.layout_sortTop).setOnClickListener(this); findViewById(R.id.layout_special).setOnClickListener(this); wait_layout = (LinearLayout) findViewById(R.id.layout_wait_restore); // / INIT BILLING base64EncodedPublicKey = this.getResources().getString( R.string.app_public_key); // Create the helper, passing it our context and the public key to // verify signatures with Utils.ELog(BILLING_TAG, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); // enable debug logging (for a production application, you should set // this to false). mHelper.enableDebugLogging(true); } void getStatus() { // get config app string Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); listDeckBean = gson.fromJson(listSaved, listOfDeckBean); } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); // Utils.ELog("str_History", strHistory); setting = gson.fromJson(strSetting, SettingAppType); } } /** * Save status DeckBean */ private void saveStatus() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String save = gson.toJson(listDeckBean, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (isWait) { return; } switch (v.getId()) { case R.id.btn_help_setting: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 3); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_back_setting: this.finish(); break; case R.id.layout_confirm_restore: dialogRestore(); break; case R.id.layout_sortTop: Intent intentSort = new Intent(this, SettingSortActivity.class); intentSort.putExtra("sort_by", setting.sortToppage); startActivityForResult(intentSort, 1); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.layout_special: startActivityForResult(new Intent(this, SettingSpecialActivity.class), 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; default: break; } } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub switch (buttonView.getId()) { case R.id.switchJumcard: setting.jumCard = isChecked; saveSetting(); break; case R.id.switchAdviseCard: setting.adviseCard = isChecked; saveSetting(); break; case R.id.switchSound: setting.sound = isChecked; saveSetting(); break; default: break; } } void saveSetting() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); String save = gson.toJson(setting, SettingAppType); appPreferences.put(ConstantValue.SETTING_KEY, save); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); if (requestCode == 1) { setting.sortToppage = resultCode; saveSetting(); } } private void dialogRestore() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle("hỏi thoát chương trình"); String message = getResources().getString( R.string.dialog_restore_message); builder.setMessage(message); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { billingRestore(); // finish(); } }); builder.setCancelable(false); builder.create().show(); } private void billingRestore() { setWaitScreen(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Utils.ELog(BILLING_TAG, "Starting setup."); if (!isBillingSupport) { mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Utils.ELog(BILLING_TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. Utils.ELog(BILLING_TAG, "Problem setting up in-app billing: " + result); setWaitScreen(false); return; } // Hooray, IAB is fully set up. Now, let's get an inventory // of // stuff we own. Utils.ELog(BILLING_TAG, "Setup successful. Querying inventory."); isBillingSupport = true; mHelper.queryInventoryAsync(mGotInventoryListener); } }); } else { Utils.ELog(BILLING_TAG, "billing support. Querying inventory."); mHelper.queryInventoryAsync(mGotInventoryListener); } } // Listener that's called when we finish querying the items and // subscriptions we own // Lấy thông tin các item mà user đã mua (sở hữu) IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Utils.ELog(BILLING_TAG, "Query inventory finished."); if (result.isFailure()) { Utils.ELog(BILLING_TAG, "Failed to query inventory: " + result); setWaitScreen(false); return; } Utils.ELog(BILLING_TAG, "Query inventory was successful."); Utils.ELog(BILLING_TAG, "Query inventory info: " + inventory.toString()); for (int i = 0; i < listDeckBean.size(); i++) { Purchase testPurchase = inventory.getPurchase(listDeckBean .get(i).inAppPurchaseId); Utils.ELog(BILLING_TAG, "item inventory info: " + listDeckBean.get(i).inAppPurchaseId); if (testPurchase != null && verifyDeveloperPayload(testPurchase)) { Utils.ELog(BILLING_TAG, " deck already bought id: " + listDeckBean.get(i).inAppPurchaseId); listDeckBean.get(i).isUnlock = true; Date purchaseDate = new Date(testPurchase.getPurchaseTime()); listDeckBean.get(i).buyDate = purchaseDate; } } saveStatus(); setWaitScreen(false); setResult(RESULT_OK); } }; /** Verifies the developer payload of a purchase. */ // Xác thực đoạn pay load trả về boolean verifyDeveloperPayload(Purchase p) { String payloadReturn = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. * It will be the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase * and verifying it here might seem like a good approach, but this will * fail in the case where the user purchases an item on one device and * then uses your app on a different device, because on the other device * you will not have access to the random string you originally * generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different * between them, so that one user's purchase can't be replayed to * another user. * * 2. The payload must be such that you can verify it even when the app * wasn't the one who initiated the purchase flow (so that items * purchased by the user on one device work on other devices owned by * the user). * * Using your own server to store and verify developer payloads across * app installations is recommended. */ return true; } // Tắt/Bật màn hình chờ void setWaitScreen(boolean set) { wait_layout.setVisibility(set ? View.VISIBLE : View.GONE); isWait = set ? true : false; } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); // very important: Utils.ELog(BILLING_TAG, "Destroying helper."); if (mHelper != null) mHelper.dispose(); mHelper = null; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/SettingActiviy.java
Java
art
11,747
package net.cardgame.orcalecard; import java.io.File; import java.lang.reflect.Type; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.service.ServiceUpdateFileConfig; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Màn hình Splash khi khởi động app */ public class SplashActivity extends Activity { private static String TAG = SplashActivity.class.getName(); private static long SLEEP_TIME = 2000; // Sleep for some time /** * The thread to process splash screen events */ private Thread mSplashThread; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_layout); startService(new Intent(this, ServiceUpdateFileConfig.class)); // The thread to wait for splash screen events mSplashThread = new Thread() { @Override public void run() { try { synchronized (this) { // Wait given period of time or exit on touch wait(SLEEP_TIME); } } catch (InterruptedException ex) { } handler.sendMessage(handler.obtainMessage()); } }; mSplashThread.start(); createAppFolder(); loadSettingApp(); } void loadSettingApp() { SettingApp setting = new SettingApp(); setting.setDefault(); Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (!appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String save = gson.toJson(setting, SettingAppType); appPreferences.put(ConstantValue.SETTING_KEY, save); } } Handler handler = new Handler() { public void handleMessage(Message msg) { Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); finish(); }; }; private void createAppFolder() { File file = new File(ConstantValue.getBasePatchApp(this)); if (!file.exists()) file.mkdirs(); } /** * Processes splash screen touch events */ @Override public boolean onTouchEvent(MotionEvent evt) { if (evt.getAction() == MotionEvent.ACTION_DOWN) { synchronized (mSplashThread) { mSplashThread.notifyAll(); } } return true; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/SplashActivity.java
Java
art
2,777
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.CustomAnimationListener; import net.cardgame.oraclecard.common.CustomImageView; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.KeyboardHelper; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.SoundPool; import android.media.SoundPool.OnLoadCompleteListener; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.TranslateAnimation; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.nineoldandroids.animation.ObjectAnimator; public class GetCardActivity extends Activity implements OnClickListener, OnTouchListener, CustomAnimationListener { final static int JUMCARD_STATE = 5, GETCARD_STATE = 4, DEFAULT_STATE = 0; ImageView img_Jump, img_bg, img_number_getcard, card0; CustomImageView card1, card2, card3, img_ef_ring_getcard; RelativeLayout.LayoutParams paramsFront, paramsBehind, paramsCard3; ViewGroup parent; int deckId, numcards, numberOfCard, state_machine = 0, y_old = 0, x_old = 0, _yDelta, state, top_margin; SettingApp setting; boolean flag = true; final int DURATION = 700; SoundPool soundPool; int height_getcard; CardBean cardBean1, cardBean2, cardBean3, cardBean4; int cardTotal = 0; HashMap<Integer, Integer> mapCardNumber = new HashMap<Integer, Integer>(); int sound_getcard, sound_jumcard, sound_getcard1, sound_getcard2; boolean loaded = false; float volume; Bitmap mBitmapTemp; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.get_card_activity); height_getcard = getResources().getInteger(R.integer.height_getcard); parent = (ViewGroup) findViewById(R.id.card_parent); setupUI((ViewGroup) findViewById(R.id.parent)); state_machine = DEFAULT_STATE; Bundle bundle = getIntent().getExtras(); deckId = bundle.getInt("deckId"); numberOfCard = bundle.getInt("number_of_card"); if (bundle.containsKey("cardTotal")) { cardTotal = bundle.getInt("cardTotal"); } numcards = numberOfCard; setting = ConstantValue.getSettingApp(this); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub loadCardBean(); } }).start(); initView(); loadImage(); loadMedia(); } void initView() { findViewById(R.id.btnBack_getcard).setOnClickListener(this); findViewById(R.id.txtquestion_getcard).clearFocus(); img_number_getcard = (ImageView) findViewById(R.id.img_number_getcard); ImageView btnHelp = (ImageView) findViewById(R.id.btnhelp_getcard); btnHelp.setOnClickListener(this); img_ef_ring_getcard = (CustomImageView) findViewById(R.id.img_ef_ring_getcard); img_ef_ring_getcard.registryListener(this); card1 = (CustomImageView) findViewById(R.id.card1_getcard); card2 = (CustomImageView) findViewById(R.id.card2_getcard); card3 = (CustomImageView) findViewById(R.id.card3_getcard); card3.registryListener(this); card1.registryListener(this); card2.registryListener(this); card0 = (ImageView) findViewById(R.id.card0_getcard); img_Jump = (ImageView) findViewById(R.id.img_jumpcard_getcard); img_bg = (ImageView) findViewById(R.id.img_bg_getcard); paramsFront = (RelativeLayout.LayoutParams) card2.getLayoutParams(); paramsBehind = (RelativeLayout.LayoutParams) card1.getLayoutParams(); paramsCard3 = (LayoutParams) card3.getLayoutParams(); top_margin = paramsCard3.topMargin; card3.setOnTouchListener(this); } /** * Setting CardBean1,2,3,4 */ void loadCardBean() { // create card bean cardBean1 = new CardBean(); cardBean2 = new CardBean(); cardBean3 = new CardBean(); cardBean4 = new CardBean(); if (deckId == 999) { ranDomCardSpecialDeck(); } else { cardBean4.deckId = cardBean3.deckId = cardBean2.deckId = cardBean1.deckId = deckId; // Set random cardId if (cardTotal == 0) cardTotal = 44; Random random1 = new Random(); cardBean1.cardId = random1.nextInt(cardTotal - 1) + 1; do { Random random = new Random(); cardBean2.cardId = random.nextInt(cardTotal - 1) + 1; } while (cardBean2.cardId == cardBean1.cardId); do { Random random = new Random(); cardBean3.cardId = random.nextInt(cardTotal - 1) + 1; } while (cardBean3.cardId == cardBean1.cardId || cardBean3.cardId == cardBean2.cardId); do { Random random = new Random(); cardBean4.cardId = random.nextInt(cardTotal - 1) + 1; } while (cardBean4.cardId == cardBean1.cardId || cardBean4.cardId == cardBean2.cardId || cardBean4.cardId == cardBean3.cardId); } // Utils.ELog("CardBean1", cardBean1.toString()); // Utils.ELog("CardBean2", cardBean2.toString()); // Utils.ELog("CardBean3", cardBean3.toString()); // Utils.ELog("CardBean4", cardBean4.toString()); } private void ranDomCardSpecialDeck() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); for (int decId : setting.listSpecial) { for (DeckBean deckBean : listDeckBean) { if (decId == deckBean.deckId) { mapCardNumber.put(decId, deckBean.cardNumber); break; } } } cardBean1 = randomCardBean(); cardBean2 = randomCardBean(); cardBean3 = randomCardBean(); cardBean4 = randomCardBean(); mapCardNumber.clear(); } private CardBean randomCardBean() { CardBean cardBean = new CardBean(); int size, index, cardNumber; size = setting.listSpecial.size(); do { Random random = new Random(); index = random.nextInt(size); cardBean.deckId = setting.listSpecial.get(index); cardNumber = mapCardNumber.get(cardBean.deckId); cardBean.cardId = random.nextInt(cardNumber - 1) + 1; } while ((cardBean.deckId == cardBean1.deckId && cardBean.cardId == cardBean1.cardId) || (cardBean.deckId == cardBean2.deckId && cardBean.cardId == cardBean2.cardId) || (cardBean.deckId == cardBean3.deckId && cardBean.cardId == cardBean3.cardId) || (cardBean.deckId == cardBean4.deckId && cardBean.cardId == cardBean4.cardId)); return cardBean; } void getVolume() { // Getting the user sound settings AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); float actualVolume = (float) audioManager .getStreamVolume(AudioManager.STREAM_MUSIC); float maxVolume = (float) audioManager .getStreamMaxVolume(AudioManager.STREAM_MUSIC); volume = actualVolume / maxVolume; } void playSound(int soundId) { getVolume(); if (setting.sound) { soundPool.play(soundId, volume, volume, 1, 0, 1f); } } void loadMedia() { this.setVolumeControlStream(AudioManager.STREAM_MUSIC); soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { loaded = true; } }); sound_getcard = soundPool.load(this, R.raw.se_draw_card, 1); sound_jumcard = soundPool.load(this, R.raw.se_jump_card, 1); sound_getcard1 = soundPool.load(this, R.raw.get_card_001, 1); sound_getcard2 = soundPool.load(this, R.raw.get_card_002, 1); } /** * // * Set encrypt image from SD card to Image View */ private void loadImage() { notifyCardNumber(); if (deckId == 999) { img_bg.setImageResource(R.drawable.bg999); card1.setImageResource(R.drawable.c999s); card0.setImageResource(R.drawable.c999s); card2.setImageResource(R.drawable.c999s); mBitmapTemp = BitmapFactory.decodeResource(getResources(), R.drawable.c999d); img_Jump.setImageResource(R.drawable.c999j); return; } new ThreadLoadImage(this, mHandler, ConstantValue.getPathBackgroundByDeckId(this, deckId), img_bg, 1).start(); new ThreadLoadImage(this, mHandler, ConstantValue.getPathDeckImage( this, deckId, "s"), card1, 2).start(); new ThreadLoadImage(this, mHandler, ConstantValue.getPathDeckImage( this, deckId, "d"), card3, 3).start(); new ThreadLoadImage(this, mHandler, ConstantValue.getPathDeckImage( this, deckId, "j"), img_Jump, 4).start(); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: img_bg.setImageDrawable((Drawable) msg.obj); break; case 2: card0.setImageDrawable((Drawable) msg.obj); card1.setImageDrawable((Drawable) msg.obj); card2.setImageDrawable((Drawable) msg.obj); break; case 3: BitmapDrawable drawable = (BitmapDrawable) msg.obj; if (drawable != null) { mBitmapTemp = drawable.getBitmap(); } break; case 4: img_Jump.setImageDrawable((Drawable) msg.obj); break; case 5: img_Jump.setVisibility(View.INVISIBLE); break; case 6: ringGetCardAnimation(); break; case 10: ImageView imageview = (ImageView) msg.obj; if (imageview != null && paramsBehind != null) { imageview.setLayoutParams(paramsBehind); if (imageview.getId() == R.id.card1_getcard) { card2.setLayoutParams(paramsFront); parent.bringChildToFront(card2); } else { card1.setLayoutParams(paramsFront); parent.bringChildToFront(card1); } } default: break; } }; }; /** * Change number of cards haven't gotten */ private void notifyCardNumber() { if (numberOfCard <= 0) { img_number_getcard.setImageResource(R.drawable.draw_this); } else switch (numberOfCard) { case 1: img_number_getcard.setImageResource(R.drawable.draw_1); break; case 2: img_number_getcard.setImageResource(R.drawable.draw_2); break; case 3: img_number_getcard.setImageResource(R.drawable.draw_3); break; case 4: img_number_getcard.setImageResource(R.drawable.draw_4); break; default: break; } } Runnable mRunableSleep = new Runnable() { @Override public void run() { // TODO Auto-generated method stub mHandler.sendEmptyMessage(6); } }; class ThreadCardCut extends Thread { ImageView imageView; public ThreadCardCut(ImageView imageview) { imageView = imageview; }; @Override public void run() { // TODO Auto-generated method stub super.run(); try { Thread.sleep(DURATION / 2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Message msg = mHandler.obtainMessage(10); msg.obj = imageView; mHandler.sendMessage(msg); } } private void putListJump() { // for (int i = 0; i < 4; i++) { // if (listJumcard[i] == 0) { // listJumcard[i] = numcards - numberOfCard; // break; // } // } int card = numcards - numberOfCard; switch (card) { case 1: cardBean1.isJump = true; break; case 2: cardBean2.isJump = true; break; case 3: cardBean3.isJump = true; break; case 4: cardBean4.isJump = true; break; default: break; } } public void CustomOnclick(View v) { if (numberOfCard <= 0) { return; } ringCutCardAnimation(); if (setting.jumCard) { Random random = new Random(); int i = random.nextInt(20); if (i == 5) { // Jump card numberOfCard--; putListJump(); state_machine = JUMCARD_STATE; playSound(sound_jumcard); if (mBitmapTemp != null && !mBitmapTemp.isRecycled()) { card3.setImageBitmap(mBitmapTemp); Animation jump_animation = AnimationUtils.loadAnimation( this, R.anim.jumcard_animation); card3.startAnimation(jump_animation); card3.registryListener(this); img_Jump.setVisibility(View.VISIBLE); } defaultSetupCard(); notifyCardNumber(); if (numberOfCard <= 0) { gotoResultActivity(); } Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub mHandler.sendEmptyMessage(5); } }, 1500); return; } else { // Flip card playSound(sound_getcard1); } } else playSound(sound_getcard1); card3.setImageDrawable(null); ((CustomImageView) v).registryListener(this); new ThreadCardCut((ImageView) v).start(); ObjectAnimator.ofFloat(v, "translationY", 0, -height_getcard, 0) .setDuration(DURATION).start(); } @Override public void onClick(View view) { // TODO Auto-generated method stub if (!flag) return; switch (view.getId()) { case R.id.btnBack_getcard: goBack(); break; case R.id.btnhelp_getcard: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 9); startActivityForResult(intent, 6); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; default: break; } } private void ringCutCardAnimation() { Animation ef_ring = AnimationUtils.loadAnimation(this, R.anim.ring_cutcard_animation); img_ef_ring_getcard.setImageResource(R.drawable.ef_ring); img_ef_ring_getcard.startAnimation(ef_ring); } private void ringGetCardAnimation() { Animation ef_ring = AnimationUtils.loadAnimation(this, R.anim.ring_getcard_animation); img_ef_ring_getcard.setImageResource(R.drawable.ef_ring); img_ef_ring_getcard.startAnimation(ef_ring); } void defaultSetupCard() { state = 2; card2.setLayoutParams(paramsFront); card1.setLayoutParams(paramsBehind); parent.bringChildToFront(card2); } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub if (numberOfCard <= 0) return false; final int Y = (int) event.getRawY(); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: KeyboardHelper.hideSoftKeyboard(this); findViewById(R.id.txtquestion_getcard).clearFocus(); RelativeLayout.LayoutParams lParams2 = (RelativeLayout.LayoutParams) v .getLayoutParams(); _yDelta = Y - lParams2.topMargin; y_old = Y; x_old = (int) event.getRawX(); break; case MotionEvent.ACTION_UP: notifyCardNumber(); int x = (int) event.getRawX(); if (Math.abs(Y - y_old) < 10 && Math.abs(x - x_old) < 10) { if (state == 1) { state = 2; CustomOnclick(card1); } else { state = 1; CustomOnclick(card2); } } else { v.setLayoutParams(paramsCard3); int s = Y - y_old; int speed = 50; int t = Math.abs(100 * s / speed); TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -s); animation.setDuration(t); card3.startAnimation(animation); } if (y_old - Y >= paramsCard3.height / 2) {// perform get Card if (numberOfCard <= 0) return true; numberOfCard--; if (numberOfCard <= 0) { gotoResultActivity(); } notifyCardNumber(); Animation getcard_animation = AnimationUtils.loadAnimation( this, R.anim.getcard_animation); card3.startAnimation(getcard_animation); mHandler.postDelayed(mRunableSleep, 150); state_machine = GETCARD_STATE; playSound(sound_getcard); } break; case MotionEvent.ACTION_MOVE: if (mBitmapTemp != null && !mBitmapTemp.isRecycled() && card3.getDrawable() == null) { card3.setImageBitmap(mBitmapTemp); } RelativeLayout.LayoutParams layoutParams = (LayoutParams) v .getLayoutParams(); layoutParams.topMargin = Y - _yDelta; layoutParams.leftMargin = -250; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; v.setLayoutParams(layoutParams); if (y_old - Y >= paramsCard3.height / 2) { img_number_getcard.setImageResource(R.drawable.draw_this); } else { notifyCardNumber(); } break; default: break; } return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { flag = true; overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } public void setupUI(View view) { // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { view.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { v.requestFocus(); KeyboardHelper.hideSoftKeyboard(GetCardActivity.this); return false; } }); } // If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } void gotoResultActivity() { EditText textInput = (EditText) findViewById(R.id.txtquestion_getcard); final String text = textInput.getText().toString(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub Intent intent = new Intent(GetCardActivity.this, ResultActivity.class); Bundle bundle = getIntent().getExtras(); intent.putExtra("cardBean1", cardBean1); intent.putExtra("cardBean2", cardBean2); intent.putExtra("cardBean3", cardBean3); intent.putExtra("cardBean4", cardBean4); bundle.putString("text_input", text); intent.putExtras(bundle); startActivity(intent); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); GetCardActivity.this.finish(); } }, 1000); } @Override public synchronized void onEndAnimation(ImageView imageview) { // TODO Auto-generated method stub if (imageview.getId() == R.id.img_ef_ring_getcard) { imageview.setImageDrawable(null); return; } if (imageview.getId() == R.id.card1_getcard || imageview.getId() == R.id.card2_getcard) { playSound(sound_getcard2); } switch (state_machine) { case JUMCARD_STATE: imageview.setImageDrawable(null); state_machine = DEFAULT_STATE; img_Jump.setVisibility(View.INVISIBLE); notifyCardNumber(); break; case DEFAULT_STATE: if (imageview.getId() == R.id.card3_getcard) { imageview.setImageDrawable(null); RelativeLayout.LayoutParams layoutParams = (LayoutParams) imageview .getLayoutParams(); layoutParams.topMargin = top_margin; layoutParams.leftMargin = -250; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; imageview.setLayoutParams(layoutParams); return; } imageview.setLayoutParams(paramsBehind); break; case GETCARD_STATE: state_machine = DEFAULT_STATE; if (imageview.getId() == R.id.card3_getcard) { imageview.setImageDrawable(null); RelativeLayout.LayoutParams layoutParams = (LayoutParams) imageview .getLayoutParams(); layoutParams.topMargin = top_margin; layoutParams.leftMargin = -250; layoutParams.rightMargin = -250; layoutParams.bottomMargin = -250; imageview.setLayoutParams(layoutParams); imageview.setImageDrawable(null); // ringGetCardAnimation(); return; } break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { goBack(); return true; } return super.onKeyDown(keyCode, event); } private void goBack() { if (mBitmapTemp != null && !mBitmapTemp.isRecycled()) { mBitmapTemp.recycle(); } Intent intent = new Intent(this, SplashDeckBeanActivity.class); intent.putExtras(getIntent().getExtras()); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/GetCardActivity.java
Java
art
21,665
package net.cardgame.orcalecard; import java.util.ArrayList; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.MySwitch; import net.cardgame.oraclecard.common.SavedListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.TextView; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; public class ListSpecialAdapter extends ArrayAdapter<DeckBean> implements OnCheckedChangeListener { ArrayList<DeckBean> listDeck; Activity context; List<Integer> special; SavedListener listener; private ImageManager imageManager; private ImageTagFactory imageTagFactory; boolean flag = true; SecurePreferences contentPreferences; public ListSpecialAdapter(Activity context, int textViewResourceId, ArrayList<DeckBean> objects, List<Integer> listSpecial) { super(context, textViewResourceId, objects); // TODO Auto-generated constructor stub this.listDeck = objects; listener = (SavedListener) context; this.context = context; this.special = listSpecial; if (special == null) special = new ArrayList<Integer>(); contentPreferences = new SecurePreferences(context, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); initImageLoader(); } public void setFlag(boolean flag) { this.flag = flag; } static class ViewHolder { TextView txtTitle; ImageView img_deck; MySwitch switch_button; } public List<Integer> getSpecialList() { return special; } private String getDeckName(DeckBean deckbean) { String deckName = ""; String key = "content_" + deckbean.deckId; if (contentPreferences.containsKey(key)) { String content = contentPreferences.getString(key); String[] arr = content.split("---"); deckName = arr[0]; if (deckName.contains("←")) deckName = deckName.substring(0, deckName.indexOf("←")); } return deckName; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.item_listview_setting_special, null); ViewHolder viewHolder = new ViewHolder(); viewHolder.txtTitle = (TextView) rowView .findViewById(R.id.txt_deck_title); viewHolder.img_deck = (ImageView) rowView .findViewById(R.id.img_deck); viewHolder.switch_button = (MySwitch) rowView .findViewById(R.id.switch_on_off); rowView.setTag(viewHolder); } ViewHolder holder = (ViewHolder) rowView.getTag(); DeckBean deck = listDeck.get(position); holder.txtTitle.setText(getDeckName(deck)); if (special.contains(deck.deckId)) { holder.switch_button.setChecked(true); } else { holder.switch_button.setChecked(false); } String tt = deck.deckId < 10 ? "0" + deck.deckId : "" + deck.deckId; holder.switch_button.setTag(deck.deckId); holder.switch_button.setOnCheckedChangeListener(this); String strDeck = deck.pathServerDownload + "/c" + tt + "i.png"; setImageTag(holder.img_deck, strDeck); loadImage(holder.img_deck); return rowView; } String convertIdtoString(int id) { return id < 10 ? "0" + id : "" + id; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (!flag) return; int deckId = (Integer) buttonView.getTag(); // Utils.ELog("OnCheckedChanged", "DeckId:" + deckId + " ischeck:" // + isChecked); if (isChecked) special.add(deckId); else if (special.contains((Integer) deckId)) special.remove((Integer) deckId); if (special.isEmpty()) listener.onSave(false); else listener.onSave(true); // this.notifyDataSetChanged(); } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(248); imageTagFactory.setWidth(188); imageTagFactory.setDefaultImageResId(R.drawable.transparent_image); imageTagFactory.setErrorImageId(R.drawable.no_image); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, context)); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/ListSpecialAdapter.java
Java
art
5,140
package net.cardgame.orcalecard; import java.util.Random; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; public class TestActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.result_activity_layout); startServiceDownload(); Random random = new Random(); if (random.nextBoolean()) { startServiceDownload(); } else { startServiceDownload2(); } } private void startServiceDownload() { Intent intent = new Intent(this, ServiceDownload.class); intent.putExtra(ServiceDownload.KEY_PATH_SERVER, "http://www.jma-inc.jp/appdata/OracleCard/Card_03.zip"); intent.putExtra(ServiceDownload.KEY_DECK_ID, 3); intent.putExtra(ServiceDownload.KEY_POSITION, 13); intent.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_03.zip"); startService(intent); } private void startServiceDownload2() { Intent intent = new Intent(this, ServiceDownload.class); intent.putExtra(ServiceDownload.KEY_PATH_SERVER, "http://www.jma-inc.jp/appdata/OracleCard/Card_04.zip"); intent.putExtra(ServiceDownload.KEY_DECK_ID, 4); intent.putExtra(ServiceDownload.KEY_POSITION, 12); intent.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_04.zip"); startService(intent); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // Register mMessageReceiver to receive messages. LocalBroadcastManager.getInstance(this).registerReceiver( mBroadcastReceiver, new IntentFilter(ConstantValue.ACTION_DOWNLOAD)); } @Override protected void onPause() { // TODO Auto-generated method stub LocalBroadcastManager.getInstance(this).unregisterReceiver( mBroadcastReceiver); super.onPause(); } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle bundle = intent.getExtras(); int deckID = bundle.getInt(ServiceDownload.KEY_DECK_ID); int position = bundle.getInt(ServiceDownload.KEY_POSITION); int percent = bundle.getInt(ServiceDownload.KEY_PERCENT); if (bundle.containsKey(ServiceDownload.KEY_STATUS)) { boolean finished = bundle .getBoolean(ServiceDownload.KEY_STATUS); Utils.ELog("Download and Unzip status", finished ? "finished" : "unfinished"); } Utils.ELog("receiver", "deckId:" + deckID + " position:" + position + " percent:" + percent); } }; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/TestActivity.java
Java
art
3,117
package net.cardgame.orcalecard; import java.io.File; import java.io.IOException; import java.lang.reflect.Type; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; import javax.crypto.NoSuchPaddingException; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.BitmapCacheableImageView; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.FileUtils; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; 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.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class GalleryActivity extends Activity implements OnItemClickListener, OnItemSelectedListener, OnClickListener { int indexTypeHelp = 7; // List path các ảnh đã mã hóa public List<String> listPaths = new ArrayList<String>(); private int deckID = 10; private String deckName = ""; private String key = ""; // Text mo ta bo bai String strDescriptionDeck = ""; BitmapCacheableImageView iv_bg; TextView tvlabel_gallery; Button btnHelp; Button btnBack; private GalleryFlow gallery; private GalleryAdapter adapter; ArrayList<DeckBean> listSpecial; Handler handler = new Handler(); TextView tv_name; public static String pathCardBackImage = ""; SecurePreferences appPreferences; private SecurePreferences contentPreferences; SettingApp setting; int deckId = 0; int cardId = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_gallery); iv_bg = (BitmapCacheableImageView) findViewById(R.id.iv_bg); gallery = (GalleryFlow) findViewById(R.id.gallery); tv_name = (TextView) findViewById(R.id.tv_name); tvlabel_gallery = (TextView) findViewById(R.id.tvlabel_gallery); // getListSpecial(); // Bundle bundle = this.getIntent().getExtras(); deckID = bundle.getInt("deckId"); // deckName = bundle.getString("deckName"); // tvlabel_gallery.setText(deckName); contentPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); threadLoadTitleGallery loadTitle = new threadLoadTitleGallery(); loadTitle.start(); // Neu khong phai bo Special if (deckID != 999) { String strDECKID = (deckID < 10) ? ("0" + deckID) : ("" + deckID); pathCardBackImage = ConstantValue.APP_PREFERENCES + "/Card_" + strDECKID + "/en_c" + strDECKID + "d.png"; } else { // Neu la bo Special if (!listSpecial.isEmpty()) { iv_bg.setImageResource(R.drawable.bg999); tvlabel_gallery.setText(R.string.name_special_deck); } } new loadPathsAsyncTask().execute(); gallery.setOnItemClickListener(this); gallery.setOnItemSelectedListener(this); btnHelp = (Button) findViewById(R.id.btnHelp); btnBack = (Button) findViewById(R.id.btnBack); btnHelp.setOnClickListener(this); btnBack.setOnClickListener(this); } class threadLoadTitleGallery extends Thread { public void run() { handler.post(new Runnable() { @Override public void run() { key = "content_" + deckID; if (contentPreferences.containsKey(key)) { deckName = contentPreferences.getString(key); String[] arr = deckName.split("---"); deckName = arr[0]; if (deckName.contains("←")) deckName = deckName.substring(0, deckName.indexOf("←")); tvlabel_gallery.setText(deckName); } } }); } } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); setting = gson.fromJson(strSetting, SettingAppType); } } ArrayList<DeckBean> getListSpecial() { appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); loadSettingApp(); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); listSpecial = new ArrayList<DeckBean>(); for (DeckBean deckBean : listDeckBean) { if (deckBean.percentDownloaded == -2 && deckBean.deckId != 999 && deckBean.deckId != 998 && setting.listSpecial.contains((Integer) deckBean.deckId)) { listSpecial.add(deckBean); } } return listSpecial; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent i = new Intent(this, CardDetailActivity.class); deckId = dId; cardId = cId; i.putExtra("cardId", cardId); i.putExtra("deckId", deckId); startActivityForResult(i, 1); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); clearCacheCardDetail(); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String[] content = getContentCard(position).split("---"); String title = content[0]; for (int i = 0; i < title.length() - 1; i++) { if (title.charAt(i) == '←') { title = title.substring(0, i - 1); break; } } tv_name.setText(title); } @Override public void onNothingSelected(AdapterView<?> arg0) { } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnBack: goBack(); break; case R.id.btnHelp: onClickButtonHelp(); default: break; } } public void onClickButtonHelp() { Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class); i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp); startActivity(i); } public String getContentCard(int pos) { String fullPath = listPaths.get(pos); Detect_DeckId_CardId_FromPath(fullPath); int deckId = dId; int cardId = cId; byte[] bytes; String strDECKID = (deckId < 10) ? ("0" + deckId) : ("" + deckId); String strCARDID = (cardId < 10) ? ("0" + cardId) : ("" + cardId); String content = ""; String pathTextFile = ConstantValue.getPatchCardData(this) + "/Card_" + strDECKID + "/en_t" + strDECKID + strCARDID + ".txt"; try { bytes = FileUtils.decryptToByteArray(pathTextFile, ""); content = new String(bytes, "UTF-8"); // Va ma hoa ve utf-8 } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return content; } public void loadImageBackground(int _deckID) { String strDECKID = (_deckID < 10) ? ("0" + _deckID) : ("" + _deckID); // Path toi file anh background String pathImageBackground = ConstantValue.getPatchCardData(this) + "Card_" + strDECKID + "/en_bg" + strDECKID + ".jpg"; iv_bg = (BitmapCacheableImageView) findViewById(R.id.iv_bg); iv_bg.loadImage(pathImageBackground, this, 0); } private class loadPathsAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { // Neu khong phai deck Special if (deckID != 999) { listPaths = loadPaths(deckID, "png"); } else { // Neu la deck Special for (DeckBean dec : listSpecial) { List<String> temp = new ArrayList<String>(); temp = loadPaths(dec.deckId, "png"); if (temp.size() > 0) { for (String p : temp) { listPaths.add(p); } } } } return null; } @Override protected void onPostExecute(Void result) { if (deckID != 999) { loadImageBackground(deckID); adapter = new GalleryAdapter(GalleryActivity.this, listPaths, false); } else adapter = new GalleryAdapter(GalleryActivity.this, listPaths, true); gallery.setAdapter(adapter); gallery.setSpacing(-100); super.onPostExecute(result); } } public List<String> loadPaths(int deckId, String strFilter) { String strDECKID = (deckId < 10) ? "0" + deckId : "" + deckId; String _pathDirectory = ConstantValue.getPatchCardData(this) + "Card_" + strDECKID + "/X2/"; String strFilter1 = "c" + strDECKID + "t1-3"; String strFilter2 = "c" + strDECKID + "t"; String strFilter3 = "c" + strDECKID + "s"; String strFilter4 = "c" + strDECKID + "p"; String strFilter5 = "c" + strDECKID + "m"; String strFilter6 = "c" + strDECKID + "n"; String strFilter7 = "c" + strDECKID + "i"; String strFilter8 = "c" + strDECKID + "j"; String strFilter9 = "c" + strDECKID + "d"; String strFilter10 = "copyright"; String strFilter11 = "c" + strDECKID + "00"; List<String> listPaths = new ArrayList<String>(); File targetDirector = new File(_pathDirectory); File[] listFiles = targetDirector.listFiles(); if (listFiles.length > 0) { for (File f : listFiles) { String[] arr = null; String sub = ""; String s = ""; arr = f.getPath().split("\\/"); sub = arr[arr.length - 1]; arr = sub.split("\\."); sub = arr[arr.length - 1]; s = arr[0]; arr = s.split("\\_"); s = arr[arr.length - 1]; if (sub.equalsIgnoreCase(strFilter)) if (!s.equalsIgnoreCase(strFilter1) && !s.equalsIgnoreCase(strFilter2) && !s.equalsIgnoreCase(strFilter3) && !s.equalsIgnoreCase(strFilter4) && !s.equalsIgnoreCase(strFilter5) && !s.equalsIgnoreCase(strFilter6) && !s.equalsIgnoreCase(strFilter7) && !s.equalsIgnoreCase(strFilter8) && !s.equalsIgnoreCase(strFilter9) && !s.equalsIgnoreCase(strFilter10) && !s.equalsIgnoreCase(strFilter11)) listPaths.add(f.getPath()); } java.util.Collections.sort(listPaths); } return listPaths; } private int dId = -1; private int cId = -1; public void Detect_DeckId_CardId_FromPath(String path) { String[] arrPath = null; String subPath1 = ""; String subPath2 = ""; arrPath = path.split("\\/"); subPath1 = arrPath[arrPath.length - 3]; subPath2 = arrPath[arrPath.length - 1]; arrPath = subPath1.split("\\_"); subPath1 = arrPath[arrPath.length - 1]; subPath2 = subPath2.substring(6, 8); dId = Integer.parseInt(subPath1); cId = Integer.parseInt(subPath2); } @Override public void onBackPressed() { // TODO Auto-generated method stub goBack(); } void goBack() { Intent intent = new Intent(this, CardDeckActivity.class); intent.putExtras(getIntent().getExtras()); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } void clearCacheCardDetail() { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, deckId, cardId, ConstantValue.X1)); } void setFontTextView(TextView tv, String patch) { Typeface type = Typeface.createFromAsset(getAssets(), patch); tv.setTypeface(type); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/GalleryActivity.java
Java
art
12,513
package net.cardgame.orcalecard; import java.util.ArrayList; import java.util.Date; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.service.DownloadUnzipObject; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.oraclecard.service.ServiceDownloadListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Sort; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.OnImageLoadedListener; import com.novoda.imageloader.core.model.ImageTagFactory; public class GridViewAdapter extends ArrayAdapter<DeckBean> implements OnImageLoadedListener { private ImageManager imageManager; private ImageTagFactory imageTagFactory; Activity activity; ArrayList<DeckBean> listDeckBean; LinearLayout.LayoutParams paramsHeader, paramsFooter; int size = 0, loaded = 0; Date dateNow; private boolean image_load_finished = false; private ServiceDownloadListener downloadListener; public GridViewAdapter(Activity context, ArrayList<DeckBean> listDeckBean) { super(context, 0); downloadListener = (ServiceDownloadListener) context; activity = context; this.listDeckBean = listDeckBean; this.size = listDeckBean.size(); dateNow = new Date(); initImageLoader(); checkLoadFinished(); } private void checkLoadFinished() { SecurePreferences appPreferences = new SecurePreferences(activity, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) image_load_finished = true; } public ArrayList<DeckBean> sortDeckBean(int type) { switch (type) { case SettingApp.SORT_BY_BUY: listDeckBean = Sort.sortByBuy(listDeckBean); break; case SettingApp.SORT_BY_RELEASE: listDeckBean = Sort.sortByRelease(listDeckBean); break; case SettingApp.SORT_BY_USED: listDeckBean = Sort.sortByLastUsed(listDeckBean); break; default: break; } this.notifyDataSetChanged(); return listDeckBean; } /* Function display percent downloading of a DeckBean */ public void setPercentDownloaded(int position, int percentDownloaded) { listDeckBean.get(position).percentDownloaded = percentDownloaded; this.notifyDataSetChanged(); } public void updateStatus(ArrayList<DeckBean> listDeck) { this.listDeckBean = listDeck; this.notifyDataSetChanged(); } public void setPercent(int decId, int percent) { for (DeckBean deckBean : listDeckBean) { if (deckBean.deckId == decId) { deckBean.percentDownloaded = percent; this.notifyDataSetChanged(); downloadListener.onUpdateProgressListener(percent, 0, decId); if (percent == 100) { downloadListener .onFinishedListener(new DownloadUnzipObject( deckBean.deckId, 0, "", "")); } return; } } } /* Function unlock a DeckBean by position */ public void unlockDeckBean(int position) { listDeckBean.get(position).isUnlock = true; this.notifyDataSetChanged(); } public void unlockDeckBeanById(int deckId) { for (DeckBean dec : listDeckBean) { if (dec.deckId == deckId) { dec.isUnlock = true; return; } } } /* get GridView item total */ @Override public int getCount() { // TODO Auto-generated method stub if (size % 3 == 0) return size; else return size + (3 - size % 3); } /* Get item gridview by position */ @Override public DeckBean getItem(int position) { // TODO Auto-generated method stub return listDeckBean.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } private String idToString(int id) { return id < 10 ? "0" + id : "" + id; } /* * (non-Javadoc) * * @see android.widget.ArrayAdapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View row = convertView; ViewHolder holder; /* * inflate layout */ if (row == null) { LayoutInflater inflator = activity.getLayoutInflater(); row = inflator.inflate(R.layout.item_gridview_top_header, null); holder = new ViewHolder(); holder.progressbar = (ProgressBar) row .findViewById(R.id.progressbar); holder.progressbar.setMax(100); holder.imgViewCategory = (ImageView) row .findViewById(R.id.image_category_option_gridview); holder.imgTitle = (ImageView) row .findViewById(R.id.image_title_option_gridview); holder.imgNew = (ImageView) row .findViewById(R.id.image_new_option_gridview); holder.imgLock = (ImageView) row .findViewById(R.id.image_lock_option_gridview); holder.imgBackground = (ImageView) row .findViewById(R.id.image_bg_option_gridview); holder.txtHeader = (TextView) row.findViewById(R.id.txt_header); paramsHeader = (LinearLayout.LayoutParams) holder.txtHeader .getLayoutParams(); holder.txtFooter = (TextView) row.findViewById(R.id.txt_footer); paramsFooter = (LinearLayout.LayoutParams) holder.txtFooter .getLayoutParams(); row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } /* * Set bacground resource */ if (position % 3 == 0) { holder.imgBackground.setImageResource(R.drawable.left_bg); } else if (position % 3 == 1) { holder.imgBackground.setImageResource(R.drawable.center_bg); } else holder.imgBackground.setImageResource(R.drawable.right_bg); /* * set image resource */ if (position < 3) holder.txtHeader.setLayoutParams(paramsHeader); else holder.txtHeader.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0)); if (position > getCount() - 4) holder.txtFooter.setLayoutParams(paramsFooter); else { holder.txtFooter.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0)); } DeckBean deckBean = new DeckBean(); try { deckBean = listDeckBean.get(position); } catch (Exception ex) { holder.imgTitle.setImageDrawable(null); holder.imgViewCategory.setImageDrawable(null); holder.imgLock.setImageDrawable(null); holder.imgNew.setImageDrawable(null); holder.progressbar.setVisibility(View.INVISIBLE); return row; } if (deckBean.isUnlock || deckBean.isFree) holder.imgLock.setImageDrawable(null); else { holder.imgLock.setImageResource(R.drawable.mypage_lock); } if (deckBean.releaseDate != null) holder.imgNew.setImageResource(R.drawable.new_release); else { holder.imgNew.setImageDrawable(null); } String tt = idToString(deckBean.deckId); String title = deckBean.pathServerDownload + "/c" + tt + "n.png"; String strDeck = deckBean.pathServerDownload + "/c" + tt + "i.png"; setImageTag(holder.imgTitle, title); loadImage(holder.imgTitle); setImageTag(holder.imgViewCategory, strDeck); loadImage(holder.imgViewCategory); /* Set percent downloading */ int percent = deckBean.percentDownloaded; if (percent >= 0 && percent < 100) { holder.progressbar.setVisibility(View.VISIBLE); holder.progressbar.setProgress(percent); holder.progressbar.setIndeterminate(false); } else { holder.progressbar.setVisibility(View.INVISIBLE); } long diff = dateNow.getTime() - deckBean.releaseDate.getTime(); int numberOfDay = (int) (diff / 1000 / 60 / 60 / 24); // Set is New if (deckBean.percentDownloaded == -2 || numberOfDay > 30) { holder.imgNew.setVisibility(View.INVISIBLE); } else holder.imgNew.setVisibility(View.VISIBLE); return row; } static class ViewHolder { ImageView imgTitle; ImageView imgBackground; ImageView imgViewCategory; ImageView imgLock; ImageView imgNew; TextView txtHeader, txtFooter; ProgressBar progressbar; } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(248); imageTagFactory.setWidth(188); imageTagFactory.setDefaultImageResId(R.drawable.cardi_tranparent); imageTagFactory.setErrorImageId(R.drawable.cardi_tranparent); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, activity)); // view.setContentDescription(url); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); if (!image_load_finished) imageManager.setOnImageLoadedListener(this); } @Override public synchronized void onImageLoaded(ImageView imageview) { // TODO Auto-generated method stub // Utils.ELog("loaded", imageview.getContentDescription().toString()); loaded++; if (loaded >= 2 * size - 4) { // Save sharedreference SecurePreferences appPreferences = new SecurePreferences(activity, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); appPreferences.put(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE, "true"); } } private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle bundle = intent.getExtras(); if (bundle.containsKey(ServiceDownload.KEY_MESSAGE_FULL_MEMORY)) { downloadListener.onDownloadFailListener(null, bundle .getString(ServiceDownload.KEY_MESSAGE_FULL_MEMORY)); return; } int deckID = bundle.getInt(ServiceDownload.KEY_DECK_ID); int position = bundle.getInt(ServiceDownload.KEY_POSITION); int percent = bundle.getInt(ServiceDownload.KEY_PERCENT); setPercent(deckID, percent); if (bundle.containsKey(ServiceDownload.KEY_STATUS)) { boolean finished = bundle .getBoolean(ServiceDownload.KEY_STATUS); if (!finished) { downloadListener.onDownloadFailListener( new DownloadUnzipObject(deckID, position, "", ""), null); } } } }; public void registryBroadcast() { LocalBroadcastManager.getInstance(activity).registerReceiver( mBroadcastReceiver, new IntentFilter(ConstantValue.ACTION_DOWNLOAD)); } public void unRegistryBroadcast() { LocalBroadcastManager.getInstance(activity).unregisterReceiver( mBroadcastReceiver); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/GridViewAdapter.java
Java
art
11,614
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.animation.FlakeView; import net.cardgame.orcalecard.asynctask.DownloadListener; import net.cardgame.orcalecard.asynctask.GetListDeckTask; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.XmlParser; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; /** * Màn hình Home * */ public class MainActivity extends Activity implements OnClickListener, DownloadListener { String config = ""; ProgressDialog dialog; boolean gotoTopPage = false; boolean load_toppage_finished = false; FlakeView flakeView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout container = (LinearLayout) findViewById(R.id.container); flakeView = new FlakeView(this); container.addView(flakeView); getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK)); findViewById(R.id.btnMyPage).setOnClickListener(this); findViewById(R.id.btnInformation).setOnClickListener(this); getStatus(); } /** * */ void getStatus() { SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) { load_toppage_finished = true; } if (appPreferences.containsKey(ConstantValue.CONFIG_DECKBEAN_KEY)) { config = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); } else { if (NetworkUtils.isNetworkConnected(this)) { dialog = ProgressDialog.show(this, "", "Loading..Wait..", true); dialog.show(); GetListDeckTask task = new GetListDeckTask(this); task.setDownloadListener(this); task.execute(""); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.KEY_LOAD_FINISHED_TOPPAGE)) { load_toppage_finished = true; } } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btnMyPage: // go to my page activity if (config != null && config != "") { gotoToppage(); } else { if (NetworkUtils.isNetworkConnected(this)) { gotoTopPage = true; dialog = ProgressDialog.show(this, "", "Loading..Wait..", true); dialog.show(); GetListDeckTask task = new GetListDeckTask(this); task.setDownloadListener(this); task.execute(""); } else showDialogSetting(); } break; case R.id.btnInformation:// go to app information activity if (NetworkUtils.isNetworkConnected(this)) { Intent intent = new Intent(this, InfoAppActivity.class); startActivityForResult(intent, 1); } else showDialogSetting(); break; default: break; } } void gotoToppage() { if (!load_toppage_finished && !NetworkUtils.isNetworkConnected(this)) { showDialogSetting(); return; } Intent intent = new Intent(this, TopPageActivity.class); intent.putExtra("continue_download", 1); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); this.finish(); } @Override public void onDownloadSuccessListener(String result) { // TODO Auto-generated method stub new saveXMLtoJson().execute(result); } @Override public void onDownloadFailListener(String result) { // TODO Auto-generated method stub if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } @Override public void onProgressUpdateListener(Integer update) { // TODO Auto-generated method stub } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString( R.string.dialog_errornetwork_title); String message = getResources().getString( R.string.dialog_errornetwork_message); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); AlertDialog dialog = builder.show(); } class saveXMLtoJson extends AsyncTask<String, Void, ArrayList<DeckBean>> { @Override protected ArrayList<DeckBean> doInBackground(String... params) { // TODO Auto-generated method stub return new XmlParser().getDeckBeans(params[0]); } @Override protected void onPostExecute(ArrayList<DeckBean> result) { // TODO Auto-generated method stub super.onPostExecute(result); SecurePreferences appPreferences = new SecurePreferences( MainActivity.this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String save = gson.toJson(result, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); config = save; if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } if (gotoTopPage) { gotoToppage(); } } } @Override protected void onPause() { super.onPause(); if (flakeView != null) flakeView.pause(); } @Override protected void onResume() { super.onResume(); if (flakeView != null) flakeView.resume(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/MainActivity.java
Java
art
7,050
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.SelectedHistoryListener; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.HistoryBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.Sort; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class HistoryActivity extends Activity implements SelectedHistoryListener, OnClickListener { ArrayList<HistoryBean> listHistory = new ArrayList<HistoryBean>(); HistoryAdapter adapter; ArrayList<CardBean> listCardBean = new ArrayList<CardBean>(); @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.history_activity); ListView listView = (ListView) findViewById(R.id.listView_history); findViewById(R.id.btnhelp_history).setOnClickListener(this); findViewById(R.id.btnBack_history).setOnClickListener(this); getListHistory(); if (!listHistory.isEmpty()) { adapter = new HistoryAdapter(this, listHistory); listView.setAdapter(adapter); } } void getListHistory() { Gson gson = new Gson(); Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); if (appPreferences.containsKey(ConstantValue.HISTORY_KEY)) { String strHistory = appPreferences .getString(ConstantValue.HISTORY_KEY); listHistory = gson.fromJson(strHistory, listOfHistoryBean); listHistory = Sort.sortHistoryByDate(listHistory); } } @Override public void onSelectedItemListener(int id) { // TODO Auto-generated method stub for (HistoryBean historyBean : listHistory) { if (historyBean.id == id) for (CardBean card : historyBean.cardBeans) { listCardBean.add(card); } } Intent intent = new Intent(this, EditHistoryActivity.class); intent.putExtra("historyId", id); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override public void onDeleteHistory(HistoryBean history) { // TODO Auto-generated method stub listHistory.remove(history); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfHistoryBean = new TypeToken<List<HistoryBean>>() { }.getType(); ArrayList<HistoryBean> listSave = listHistory; Collections.reverse(listSave); String save = gson.toJson(listSave, listOfHistoryBean); appPreferences.put(ConstantValue.HISTORY_KEY, save); } @Override public void onClick(View v) { // TODO Auto-generated method stub findViewById(R.id.btnhelp_history).setOnClickListener(this); findViewById(R.id.btnBack_history).setOnClickListener(this); switch (v.getId()) { case R.id.btnhelp_history: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 1); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btnBack_history: this.finish(); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); if (adapter != null) { adapter.notifyDataSetChanged(); } } private void clearCache() { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); for (CardBean card : listCardBean) { cache.removeFromMemory(ConstantValue.getPathCardDetail(this, card.deckId, card.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, card.deckId, card.cardId, ConstantValue.X1)); } } @Override protected void onDestroy() { // TODO Auto-generated method stub clearCache(); super.onDestroy(); } @Override public void onFinished() { // TODO Auto-generated method stub } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/HistoryActivity.java
Java
art
4,761
package net.cardgame.orcalecard; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Date; import java.util.List; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.billingutils.IabHelper; import net.cardgame.oraclecard.billingutils.IabResult; import net.cardgame.oraclecard.billingutils.Inventory; import net.cardgame.oraclecard.billingutils.Purchase; import net.cardgame.oraclecard.service.ServiceDownload; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.Utils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.novoda.imageloader.core.ImageManager; import com.novoda.imageloader.core.model.ImageTagFactory; /* * Màn hình Deck Lock * * */ public class InfoDeckActivity extends Activity implements OnClickListener { TextView tvDeckName; TextView tvPrice; TextView tvContentInfo; private ImageView ivLogo; private ImageView ivBackground; LinearLayout wait_layout; Button btnBack; Button btnHelp; Button btnBuy; Button btnRestore; private ImageManager imageManager; private ImageTagFactory imageTagFactory; private String pathDeckInfo = ""; // Duong dan den file info int indexTypeHelp = 6; DeckBean deckBean; int selectedPosition; Handler handler = new Handler(); private String key = ""; private SecurePreferences contentPreferences; // / BILLING static final String BILLING_TAG = "DECK BILLING"; static final int PURCHASE_REQUEST = 10001; // The helper object IabHelper mHelper; // public key in developer console String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; boolean isBillingSupport = false; // String payload để kiểm tra tính xác thực của việc mua bán. String payload = ""; // static final String SKU_TEST = "android.test.purchased"; boolean flag = true; int mRequestCode; long releaseDate = 0; // / @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_info_deck); initImageLoader(); // / INIT BILLING base64EncodedPublicKey = this.getResources().getString( R.string.app_public_key); // Create the helper, passing it our context and the public key to // verify signatures with Utils.ELog(BILLING_TAG, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); // enable debug logging (for a production application, you should set // this to false). mHelper.enableDebugLogging(false); wait_layout = (LinearLayout) findViewById(R.id.layout_wait_billing); btnBuy = (Button) findViewById(R.id.btn_buy); btnRestore = (Button) findViewById(R.id.btn_restore); btnBuy.setOnClickListener(this); btnRestore.setOnClickListener(this); // /----------------------------- // Tạo scrollBar cho TextContent tvContentInfo = (TextView) findViewById(R.id.tvContentInfo); tvDeckName = (TextView) findViewById(R.id.tvDeckName); tvPrice = (TextView) findViewById(R.id.tvPrice); ivLogo = (ImageView) findViewById(R.id.ivLogo); ivBackground = (ImageView) findViewById(R.id.ivBackground); btnBack = (Button) findViewById(R.id.btnBack); btnHelp = (Button) findViewById(R.id.btnHelp); btnBack.setOnClickListener(this); btnHelp.setOnClickListener(this); // Nhận DeckBean từ "TopPageActivity" về deckBean = new DeckBean(); Bundle bundle = this.getIntent().getExtras(); deckBean.deckId = bundle.getInt("deckId"); deckBean.deckName = bundle.getString("deckName"); Utils.ELog("Deck Name", deckBean.deckName); deckBean.deckPrice = bundle.getInt("deckPrice"); deckBean.pathServerDownload = bundle.getString("deckPathServer"); deckBean.isUnlock = bundle.getBoolean("isUnlock"); deckBean.isFree = bundle.getBoolean("isFree"); deckBean.inAppPurchaseId = bundle.getString("inAppPurchaseId"); if (bundle.containsKey("position")) selectedPosition = bundle.getInt("position"); if (bundle.containsKey("releaseDate")) { releaseDate = bundle.getLong("releaseDate"); } if (bundle.containsKey("requestCode")) mRequestCode = bundle.getInt("requestCode"); key = "content_" + deckBean.deckId; contentPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); switch (deckBean.deckId) { case 999: btnBuy.setVisibility(View.INVISIBLE); btnRestore.setVisibility(View.INVISIBLE); ivBackground.setImageResource(R.drawable.bg999); ivLogo.setImageResource(R.drawable.c999i); tvContentInfo.setText(R.string.special_sumary); tvDeckName.setText(R.string.name_special_deck); return; case 998: btnBuy.setVisibility(View.INVISIBLE); btnRestore.setVisibility(View.INVISIBLE); ivBackground.setImageResource(R.drawable.bg998); ivLogo.setImageResource(R.drawable.c998i); tvContentInfo.setText(R.string.random_sumary); tvDeckName.setText(R.string.name_random_deck); return; default: String strDeckId = (deckBean.deckId < 10) ? ("0" + deckBean.deckId) : ("" + deckBean.deckId); pathDeckInfo = deckBean.pathServerDownload + "/t" + strDeckId + ".txt"; loadDataText(pathDeckInfo); break; } /* * 1. Nếu deck isUnlock = true: Deck đã được mua - Button Buy ở trạng * thái unactive. Đồng thời string của button là "購入済" - Button Restore * ở trạng thái active. * * 2. Nếu deck isUnlock = false: Deck chưa được mua - Button Buy ở trạng * thái active. Đồng thời string của button là "購入する" - Button Restore ở * trạng thái unactive. */ if (deckBean.isUnlock) { btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); } else { btnBuy.setEnabled(true); btnBuy.setText(R.string.string_btnBuy_no); btnRestore.setEnabled(false); // Khởi tạo billing nếu deck chưa được mua setWaitScreen(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Utils.ELog(BILLING_TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Utils.ELog(BILLING_TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. Utils.ELog(BILLING_TAG, "Problem setting up in-app billing: " + result); setWaitScreen(false); return; } // Hooray, IAB is fully set up. Now, let's get an inventory // of // stuff we own. Utils.ELog(BILLING_TAG, "Setup successful. Querying inventory."); isBillingSupport = true; // mHelper.queryInventoryAsync(mGotInventoryListener); List<String> skulist = new ArrayList<String>(); skulist.add(deckBean.inAppPurchaseId); mHelper.queryInventoryAsync(true, skulist, mGotInventoryListener); } }); } loadDataImageThread loadImage = new loadDataImageThread(); loadImage.start(); tvPrice.setText(" ¥ " + deckBean.deckPrice); } private void initImageLoader() { imageManager = MyApplication.getInstance().getImageLoader(); imageTagFactory = createImageTagFactory(); } public void loadDataText(String path) { String content = ""; // Kiem tra da co key nay trong SharedReferences chua // Neu co roi thi lay noi dung content ve if (contentPreferences.containsKey(key)) { content = contentPreferences.getString(key); String[] arr = content.split("---"); String nameDeck = arr[0]; String contentDeck = arr[1]; contentDeck = insertNewLine(contentDeck); for (int i = 0; i < nameDeck.length() - 1; i++) { if (nameDeck.charAt(i) == '←') { nameDeck = nameDeck.substring(0, i - 1); break; } } tvDeckName.setText(nameDeck); tvContentInfo.setText(contentDeck); } // Neu chua co trong SharedReferenced thi load tu internet. // Sau do luu vao SharedReferenced else { // Neu co mang internet if (NetworkUtils.isNetworkConnected(InfoDeckActivity.this)) { new loadDataTextAsyncTask().execute(path); } else { // Nguoc lai khong co internet showDialogSetting(); } } } private class loadDataTextAsyncTask extends AsyncTask<String, Void, String> { String content = ""; @Override protected String doInBackground(String... params) { String path = params[0]; try { URL urlContent = new URL(path); BufferedReader in = new BufferedReader(new InputStreamReader( urlContent.openStream())); String str = ""; while ((str = in.readLine()) != null) { content += str; } in.close(); } catch (MalformedURLException e) { Log.e("Error: ", e.getMessage()); } catch (Exception e) { Log.e("Error: ", e.getMessage()); } return content; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result != "") { String _content = result; String[] arr = _content.split("---"); String nameDeck = arr[0]; String contentDeck = arr[1]; contentDeck = insertNewLine(contentDeck); for (int i = 0; i < nameDeck.length() - 1; i++) { if (nameDeck.charAt(i) == '←') { nameDeck = nameDeck.substring(0, i - 1); break; } } tvDeckName.setText(nameDeck); tvContentInfo.setText(contentDeck); // Nhet content vao trong sharedReferenced contentPreferences.put(key, _content); } } } @Override public void onClick(View v) { if (!flag) return; switch (v.getId()) { case R.id.btnBack: goBack(); break; case R.id.btnHelp: flag = false; onClickButtonHelp(); break; case R.id.btn_buy: { // Date date = new Date(releaseDate); // Utils.ELog("releaseDate", date.toGMTString()); // testReleaseDate(); if (!isRelease()) { String message = getResources().getString( R.string.message_not_release); Toast.makeText(this, message, Toast.LENGTH_LONG).show(); return; } flag = false; onClickButtonBuy(); // onClickButtonRestore(); break; } case R.id.btn_restore: flag = false; onClickButtonRestore(); break; default: break; } } // private void testReleaseDate() { // Date date = new Date(); // date.setDate(19); // date.setMonth(8); // date.setYear(2013 - 1900); // releaseDate = date.getTime(); // } private boolean isRelease() { Date dateNow = new Date(); long diff = dateNow.getTime() - releaseDate; if (diff >= 0) return true; else return false; } public void onClickButtonBuy() { // Neu co mang internet if (NetworkUtils.isNetworkConnected(this)) { // Nếu deck là free if (deckBean.isFree) { flag = true; deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); return; } // Nếu device có hỗ trợ billing hoặc billing khới tạo thành công if (isBillingSupport) { // Test Only deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); onClickButtonRestore(); // // setWaitScreen(true); // Utils.ELog(BILLING_TAG, "Launching purchase flow for deck."); // Utils.ELog(BILLING_TAG, " product id: " // + deckBean.inAppPurchaseId); // // /* // // * TODO: for security, generate your payload here for // // * verification. See the comments on verifyDeveloperPayload() // // * for more info. Since this is a SAMPLE, we just use an empty // // * string, but on a production app you should carefully // // generate // // * this. // // */ // payload = ""; // mHelper.launchPurchaseFlow(this, deckBean.inAppPurchaseId, // PURCHASE_REQUEST, mPurchaseFinishedListener, payload); } else { Toast.makeText(this, "Billing is not initialization", Toast.LENGTH_LONG).show(); flag = true; } } else { // Neu khong co mang thi khong lam gi flag = true; showDialogSetting(); } } private void startDownloadService() { if (NetworkUtils.isNetworkConnected(this)) { Intent intentService = new Intent(this, ServiceDownload.class); String id = deckBean.deckId < 10 ? "0" + deckBean.deckId : "" + deckBean.deckId; intentService .putExtra(ServiceDownload.KEY_DECK_ID, deckBean.deckId); intentService.putExtra(ServiceDownload.KEY_PATH_SERVER, deckBean.pathServerDownload + ".zip"); intentService.putExtra(ServiceDownload.KEY_POSITION, selectedPosition); intentService.putExtra(ServiceDownload.KEY_PATH_SAVE, ConstantValue.getPatchCardData(this) + "Card_" + id + ".zip"); startService(intentService); } } public synchronized void onClickButtonRestore() { // Neu co mang internet if (NetworkUtils.isNetworkConnected(InfoDeckActivity.this)) { // perform download and unzip // contentPreferences.removeValue(key); startDownloadService(); if (mRequestCode == CardDeckActivity.requestcodeInfoDeck) { setResult(RESULT_FIRST_USER); Intent intent1 = new Intent(this, TopPageActivity.class); // intent1.putExtra("deckId", deckBean.deckId); // intent1.putExtra("position", selectedPosition); startActivity(intent1); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } else { Intent intent = new Intent(); intent.putExtra("position", selectedPosition); setResult(RESULT_OK, intent); this.finish(); } } else { showDialogSetting(); } } public void onClickButtonHelp() { Intent i = new Intent(this, net.cardgame.orcalecard.HelpActivity.class); i.putExtra(HelpActivity.KEY_HELP_INDEX, indexTypeHelp); startActivityForResult(i, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } class loadDataImageThread extends Thread { public void run() { handler.post(new Runnable() { @Override public void run() { loadDataImage(); } }); } } private ImageTagFactory createImageTagFactory() { ImageTagFactory imageTagFactory = ImageTagFactory.newInstance(); imageTagFactory.setHeight(1000); imageTagFactory.setWidth(1000); imageTagFactory.setDefaultImageResId(R.drawable.transparent_image); imageTagFactory.setErrorImageId(R.drawable.transparent_image); imageTagFactory.setSaveThumbnail(true); return imageTagFactory; } private void setImageTag(ImageView view, String url) { view.setTag(imageTagFactory.build(url, this)); } private void loadImage(ImageView view) { imageManager.getLoader().load(view); } // Load du lieu anh Image public void loadDataImage() { int deckId = deckBean.deckId; String strDeckId = (deckId < 10) ? ("0" + deckId) : ("" + deckId); String pathImageBackground = deckBean.pathServerDownload + "/bg" + strDeckId + ".jpg"; String pathImageLogoDeck = deckBean.pathServerDownload + "/c" + strDeckId + "i.png"; setImageTag(ivBackground, pathImageBackground); loadImage(ivBackground); setImageTag(ivLogo, pathImageLogoDeck); loadImage(ivLogo); } // Chèn ký tự xuống dòng khi gặp dấu chấm public String insertNewLine(String str) { String tmp = ""; for (int i = 0; i < str.length(); i++) { tmp += str.charAt(i) + ""; if (str.charAt(i) == '。') tmp += "\n"; } return tmp; } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); String title = getResources().getString( R.string.dialog_errornetwork_title); String message = getResources().getString( R.string.dialog_errornetwork_message); myMsg.setText(title); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage(message); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); flag = true; } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { flag = true; dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); builder.show(); } // // CÁC BILLING FUNCTION. CHỈ DÙNG PURCHASE FUNCTION, CÁC FUNCTION KHÁC ĐỂ // DỰ PHÒNG // Tắt/bật màn hình chờ void setWaitScreen(boolean set) { wait_layout.setVisibility(set ? View.VISIBLE : View.GONE); btnBuy.setClickable(set ? false : true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Utils.ELog(BILLING_TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); flag = true; overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); // Pass on the activity result to the helper for handling if (isBillingSupport && !mHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } else { Utils.ELog(BILLING_TAG, "onActivityResult handled by IABUtil."); } } // Listener that's called when we finish querying the items and // subscriptions we own // Lấy thông tin các item mà user đã mua (sở hữu) IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Utils.ELog(BILLING_TAG, "Query inventory finished."); if (result.isFailure()) { Utils.ELog(BILLING_TAG, "Failed to query inventory: " + result); setWaitScreen(false); return; } Utils.ELog(BILLING_TAG, "Query inventory was successful."); Purchase testPurchase = inventory .getPurchase(deckBean.inAppPurchaseId); if (testPurchase != null && verifyDeveloperPayload(testPurchase)) { deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); Utils.ELog(BILLING_TAG, "Query inventory sku: " + testPurchase.getSku()); // Utils.ELog(BILLING_TAG, " Consuming test item "); // setWaitScreen(true); // mHelper.consumeAsync(testPurchase, mConsumeFinishedListener); } setWaitScreen(false); } }; /** Verifies the developer payload of a purchase. */ // xác thực đoạn payload string trả về boolean verifyDeveloperPayload(Purchase p) { String payloadReturn = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. * It will be the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase * and verifying it here might seem like a good approach, but this will * fail in the case where the user purchases an item on one device and * then uses your app on a different device, because on the other device * you will not have access to the random string you originally * generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different * between them, so that one user's purchase can't be replayed to * another user. * * 2. The payload must be such that you can verify it even when the app * wasn't the one who initiated the purchase flow (so that items * purchased by the user on one device work on other devices owned by * the user). * * Using your own server to store and verify developer payloads across * app installations is recommended. */ return true; } // Callback for when a purchase is finished IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Utils.ELog(BILLING_TAG, "Purchase finished: " + result + ", purchase: " + purchase); flag = true; if (result.isFailure()) { Utils.ELog(BILLING_TAG, "Error purchasing: " + result); if (result.getResponse() == 7) { // Utils.ELog(BILLING_TAG, "START CONSUME ITEM"); // mHelper.consumeAsync(purchase, mConsumeFinishedListener); deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); setWaitScreen(false); return; } else { setWaitScreen(false); return; } } if (!verifyDeveloperPayload(purchase)) { Utils.ELog(BILLING_TAG, "Error purchasing. Authenticity verification failed."); setWaitScreen(false); return; } Utils.ELog(BILLING_TAG, "Purchase successful."); if (purchase.getSku().equals(deckBean.inAppPurchaseId)) { Utils.ELog(BILLING_TAG, "Purchase test success!"); // dùng luôn để lần sau còn test // mHelper.consumeAsync(purchase, mConsumeFinishedListener); deckBean.isUnlock = true; btnBuy.setEnabled(false); btnBuy.setText(R.string.string_btnBuy_yes); btnRestore.setEnabled(true); onClickButtonRestore(); } setWaitScreen(false); } }; // Called when consumption is complete // IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new // IabHelper.OnConsumeFinishedListener() { // public void onConsumeFinished(Purchase purchase, IabResult result) { // Utils.ELog(BILLING_TAG, "Consumption finished. Purchase: " // + purchase + ", result: " + result); // // // We know this is the "gas" sku because it's the only one we // // consume, // // so we don't check which sku was consumed. If you have more than // // one // // sku, you probably should check... // if (result.isSuccess()) { // // successfully consumed // Utils.ELog(BILLING_TAG, "Consumption successful. Provisioning."); // // } else { // Utils.ELog(BILLING_TAG, "Error while consuming: " + result); // } // setWaitScreen(false); // } // }; // We're being destroyed. It's important to dispose of the helper here! @Override public void onDestroy() { super.onDestroy(); // very important: Utils.ELog(BILLING_TAG, "Destroying helper."); if (mHelper != null) mHelper.dispose(); mHelper = null; } @Override public void onBackPressed() { // TODO Auto-generated method stub goBack(); super.onBackPressed(); } private void goBack() { Intent intent = new Intent(); intent.putExtra("position", selectedPosition); Utils.ELog("isUnlock", deckBean.isUnlock + ""); intent.putExtra("isUnlock", deckBean.isUnlock); setResult(RESULT_OK, intent); this.finish(); } @Override protected void onResume() { flag = true; super.onResume(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/InfoDeckActivity.java
Java
art
24,556
package net.cardgame.orcalecard; import java.lang.reflect.Type; import java.util.ArrayList; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.SavedListener; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ImageView; import android.widget.ListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class SettingSpecialActivity extends Activity implements OnClickListener, SavedListener, OnScrollListener { ListSpecialAdapter adapter; SecurePreferences appPreferences; SettingApp setting; boolean save = true; ImageView button_save; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.setting_special_deck_layout); appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); loadSettingApp(); findViewById(R.id.btnBack_setting_special).setOnClickListener(this); findViewById(R.id.btnhelp_setting_special).setOnClickListener(this); button_save = (ImageView) findViewById(R.id.btn_save_setting_special); button_save.setOnClickListener(this); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); ListView listView = (ListView) findViewById(R.id.listView_setting_special); adapter = new ListSpecialAdapter(this, R.layout.item_listview_setting_special, getListSpecial(listDeckBean), setting.listSpecial); listView.setFadingEdgeLength(0); listView.setAdapter(adapter); listView.setOnScrollListener(this); } void loadSettingApp() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); if (appPreferences.containsKey(ConstantValue.SETTING_KEY)) { String strSetting = appPreferences .getString(ConstantValue.SETTING_KEY); // Utils.ELog("str_History", strHistory); setting = gson.fromJson(strSetting, SettingAppType); } } ArrayList<DeckBean> getListSpecial(ArrayList<DeckBean> list) { ArrayList<DeckBean> listtemp = new ArrayList<DeckBean>(); for (DeckBean deckBean : list) { if (deckBean.percentDownloaded == -2 && deckBean.deckId != 999 && deckBean.deckId != 998) { listtemp.add(deckBean); } } return listtemp; } @Override public void onClick(View v) { // TODO Auto-generated method stub findViewById(R.id.btnBack_setting_special).setOnClickListener(this); findViewById(R.id.btnhelp_setting_special).setOnClickListener(this); findViewById(R.id.btn_save_setting_special).setOnClickListener(this); switch (v.getId()) { case R.id.btnBack_setting_special: this.finish(); break; case R.id.btnhelp_setting_special: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 3); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_save_setting_special: if (save) { setting.listSpecial = adapter.getSpecialList(); saveSetting(); this.finish(); } break; default: break; } } void saveSetting() { Gson gson = new Gson(); Type SettingAppType = new TypeToken<SettingApp>() { }.getType(); String save = gson.toJson(setting, SettingAppType); appPreferences.put(ConstantValue.SETTING_KEY, save); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); } @Override public void onSave(boolean save) { // TODO Auto-generated method stub this.save = save; if (!save) { button_save.setSelected(true); } else button_save.setSelected(false); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub if (scrollState != SCROLL_STATE_IDLE) adapter.setFlag(false); else adapter.setFlag(true); // adapter.notifyDataSetChanged(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/SettingSpecialActivity.java
Java
art
5,007
package net.cardgame.orcalecard; import java.util.Arrays; import java.util.Collection; import java.util.List; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.KeyboardHelper; import net.cardgame.orcalecard.utils.NetworkUtils; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.facebook.LoggingBehavior; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.Session.StatusCallback; import com.facebook.SessionLoginBehavior; import com.facebook.SessionState; import com.facebook.Settings; public class PostFacebookActivity extends Activity implements OnClickListener { ImageView card1; ImageView card2; ImageView card3; ImageView card4; ImageView jumpCard; ImageView btn_share; ImageView bg_layout; LinearLayout wait_layout; ImageView btn_back; ImageView btn_help; EditText edit_status; CardBean cardBean1; CardBean cardBean2; CardBean cardBean3; CardBean cardBean4; Bitmap postBitmap = null; int number_of_card; int deckId; // phiên kết nối facebook private Session session; private static final List<String> PERMISSIONS = Arrays .asList("publish_actions"); private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization"; private boolean pendingPublishReauthorization = false; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.postfacebook_layout); // connect facebook function this.session = createSession(); Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS); Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_RAW_RESPONSES); Settings.addLoggingBehavior(LoggingBehavior.DEVELOPER_ERRORS); // / initView(); getExtra(); loadImage(); } private void initView() { card1 = (ImageView) findViewById(R.id.img_card1_save); card2 = (ImageView) findViewById(R.id.img_card2_save); card3 = (ImageView) findViewById(R.id.img_card3_save); card4 = (ImageView) findViewById(R.id.img_card4_save); card1.setClickable(false); card2.setClickable(false); card3.setClickable(false); card4.setClickable(false); btn_back = (ImageView) findViewById(R.id.btnBack_postfacebook); btn_help = (ImageView) findViewById(R.id.btnhelp_postfacebook); edit_status = (EditText) findViewById(R.id.edit_postfacebook); btn_share = (ImageView) findViewById(R.id.btn_postfacebook); bg_layout = (ImageView) findViewById(R.id.img_bg_postfacebook); wait_layout = (LinearLayout) findViewById(R.id.layout_wait); jumpCard = (ImageView) findViewById(R.id.img_jump_card1_save); btn_share.setOnClickListener(this); btn_back.setOnClickListener(this); btn_help.setOnClickListener(this); } void getExtra() { Intent intent = getIntent(); Bundle bundle = intent.getExtras(); deckId = bundle.getInt("deckId"); number_of_card = bundle.getInt("number_of_card"); cardBean1 = bundle.getParcelable("cardBean1"); cardBean2 = bundle.getParcelable("cardBean2"); cardBean3 = bundle.getParcelable("cardBean3"); cardBean4 = bundle.getParcelable("cardBean4"); } private Handler handlerLoadImage = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: card1.setImageDrawable((Drawable) msg.obj); break; case 2: card2.setImageDrawable((Drawable) msg.obj); break; case 3: card3.setImageDrawable((Drawable) msg.obj); break; case 4: card4.setImageDrawable((Drawable) msg.obj); break; case 5: bg_layout.setBackgroundDrawable((Drawable) msg.obj); break; default: break; } }; }; void loadImage() { if (deckId == 999) { bg_layout.setImageResource(R.drawable.bg999); } else // Load BackGround image new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(deckId) + "/en_bg" + convertIdToStringId(deckId) + ".jpg", bg_layout, 5).start(); // load card1 loadCard1(); // Load card 2,3,4 switch (number_of_card) { case 3: loadCard2(); loadCard3(); break; case 4: loadCard2(); loadCard3(); loadCard4(); break; default: break; } // Load Jump Card findViewById(R.id.img_jump_card1_save).setVisibility( cardBean1.isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card2_save).setVisibility( cardBean2.isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card3_save).setVisibility( cardBean3.isJump ? View.VISIBLE : View.INVISIBLE); findViewById(R.id.img_jump_card4_save).setVisibility( cardBean4.isJump ? View.VISIBLE : View.INVISIBLE); } // Load card1 void loadCard1() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean1), card1, 1).start(); } void loadCard2() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean2), card2, 2).start(); card2.setVisibility(View.VISIBLE); } void loadCard3() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean3), card3, 3).start(); card3.setVisibility(View.VISIBLE); } void loadCard4() { new ThreadLoadImage(this, handlerLoadImage, getCardPatchByCardId(cardBean4), card4, 4).start(); card4.setVisibility(View.VISIBLE); } String getCardPatchByCardId(CardBean cardBean) { return ConstantValue.getPatchCardData(this) + "Card_" + convertIdToStringId(cardBean.deckId) + "/X3/en_c" + convertIdToStringId(cardBean.deckId) + convertIdToStringId(cardBean.cardId) + ".png"; } String convertIdToStringId(int id) { return id < 10 ? "0" + id : "" + id; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn_postfacebook: KeyboardHelper.hideSoftKeyboard(this); String status = edit_status.getText().toString(); if (status.matches("")) { showDialogCancelPost(); return; } if (NetworkUtils.isNetworkConnected(this)) { if (this.session.isOpened()) { postToFacebook(); } else { this.session = createSession(); StatusCallback callback = new StatusCallback() { public void call(Session session, SessionState state, Exception exception) { if (state.isOpened()) { postToFacebook(); } else { if (state.isClosed()) { Log.e("StatusCallback", session.toString()); } } } }; this.session .openForPublish(new Session.OpenRequest(this) .setCallback(callback) .setPermissions(PERMISSIONS) .setLoginBehavior( SessionLoginBehavior.SUPPRESS_SSO)); } } else { showDialogSetting(); } break; case R.id.btnBack_postfacebook: if (postBitmap != null) { postBitmap.recycle(); } setResult(RESULT_CANCELED); finish(); break; case R.id.btnhelp_postfacebook: Intent intent = new Intent(this, HelpActivity.class); intent.putExtra(HelpActivity.KEY_HELP_INDEX, 11); startActivityForResult(intent, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; default: break; } } void gotoCardDetail(CardBean cardBean) { Intent intent = new Intent(this, CardDetailActivity.class); intent.putExtra("deckId", cardBean.deckId); intent.putExtra("cardId", cardBean.cardId); startActivityForResult(intent, ConstantValue.SAVE_HISTORY_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } /** * Lấy phiên kết nối của facebook * * @return */ private Session createSession() { Session activeSession = Session.getActiveSession(); if (activeSession == null || activeSession.getState().isClosed()) { activeSession = new Session.Builder(this).setApplicationId( this.getResources().getString(R.string.app_id)).build(); Session.setActiveSession(activeSession); } return activeSession; } void showDialogCancelPost() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView txtTitle = new TextView(this); txtTitle.setGravity(Gravity.CENTER); txtTitle.setTextColor(Color.WHITE); txtTitle.setText("Error"); txtTitle.setTextSize(20); builder.setCustomTitle(txtTitle); builder.setMessage("Please input some caption for image"); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.show(); } /** * post history lên facebook */ private void postToFacebook() { if (session != null) { // Check for publish permissions List<String> permissions = session.getPermissions(); if (!isSubsetOf(PERMISSIONS, permissions)) { pendingPublishReauthorization = true; Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest( this, PERMISSIONS); session.requestNewPublishPermissions(newPermissionsRequest); return; } Request.Callback postPhotoCallback = new Request.Callback() { @Override public void onCompleted(Response response) { // TODO Auto-generated method stub Log.e("postToFacebook", response.toString()); if (response.getError() == null) { // Tell the user success! Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); } setWaitScreen(false); } }; setWaitScreen(true); if (postBitmap == null) { postBitmap = createPostImage(); } Request postPhoto = Request.newUploadPhotoRequest(session, postBitmap, postPhotoCallback); Bundle params = postPhoto.getParameters(); params.putString("message", edit_status.getText().toString()); postPhoto.executeAsync(); } } /** * kiểm tra quyền login facebook * * @param subset * @param superset * @return */ private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) { for (String string : subset) { if (!superset.contains(string)) { return false; } } return true; } private static final int IMAGE_SPACE = 15; private Bitmap createPostImage() { if (number_of_card >= 1) { int itemWidth = ((BitmapDrawable) card1.getDrawable()).getBitmap() .getWidth(); int itemHeight = ((BitmapDrawable) card1.getDrawable()).getBitmap() .getHeight(); int bitmapWidth = itemWidth * number_of_card + IMAGE_SPACE * (number_of_card + 1); Bitmap postBitmap = Bitmap.createBitmap(bitmapWidth, itemHeight + IMAGE_SPACE, Bitmap.Config.RGB_565); Canvas canvas = new Canvas(postBitmap); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setDither(true); canvas.drawColor(Color.WHITE); if (number_of_card == 1) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); } else if (number_of_card == 2) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card2.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } else if (number_of_card == 3) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card2.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card3.getDrawable()).getBitmap(), itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } else if (number_of_card == 4) { canvas.drawBitmap( ((BitmapDrawable) card1.getDrawable()).getBitmap(), IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card2.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card3.getDrawable()).getBitmap(), itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); canvas.drawBitmap( ((BitmapDrawable) card4.getDrawable()).getBitmap(), itemWidth + itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } if (cardBean1.isJump) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), 0, 0, paint); } if (cardBean2.isJump && number_of_card > 1) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), itemWidth + IMAGE_SPACE, 0, paint); } if (cardBean3.isJump && number_of_card > 2) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } if (cardBean4.isJump && number_of_card > 3) { canvas.drawBitmap( ((BitmapDrawable) jumpCard.getDrawable()).getBitmap(), itemWidth + itemWidth + itemWidth + IMAGE_SPACE + IMAGE_SPACE + IMAGE_SPACE, 0, paint); } return postBitmap; } else { return null; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); } // Tắt/bật màn hình chờ void setWaitScreen(boolean set) { wait_layout.setVisibility(set ? View.VISIBLE : View.GONE); edit_status.setEnabled(set ? false : true); btn_back.setClickable(set ? false : true); btn_help.setClickable(set ? false : true); btn_share.setClickable(set ? false : true); } void showDialogSetting() { AlertDialog.Builder builder = new AlertDialog.Builder(this); // Creates textview for centre title TextView myMsg = new TextView(this); myMsg.setText("No internet connection"); myMsg.setGravity(Gravity.CENTER_HORIZONTAL); myMsg.setTextSize(20); myMsg.setTextColor(Color.WHITE); // set custom title builder.setCustomTitle(myMsg); builder.setMessage("Please check your setting network"); builder.setNegativeButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); builder.setPositiveButton("Setting", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); startActivity(new Intent( android.provider.Settings.ACTION_SETTINGS)); } }); AlertDialog dialog = builder.show(); } @Override public void onBackPressed() { // TODO Auto-generated method stub overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); if (postBitmap != null) { postBitmap.recycle(); } super.onBackPressed(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/PostFacebookActivity.java
Java
art
16,528
package net.cardgame.orcalecard; import java.util.List; import android.app.Activity; import android.util.DisplayMetrics; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class GalleryAdapter extends BaseAdapter { private Activity activity; private List<String> listPaths; public GalleryLoader imageLoader; int index = 0; private int width = 0; public GalleryAdapter(Activity a, List<String> list, boolean isSpecial) { activity = a; listPaths = list; imageLoader = new GalleryLoader(activity.getApplicationContext(), isSpecial); DisplayMetrics displaymetrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay() .getMetrics(displaymetrics); width = displaymetrics.widthPixels; } public int getCount() { return listPaths.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } static class ViewHolder { TextView textView; ImageView imageview; } public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView = new ImageView(activity); imageLoader.DisplayImage(listPaths.get(position), imageView); if (width < 500) // Galaxy S2 imageView.setLayoutParams(new GalleryFlow.LayoutParams(280, 440)); else { // Galaxy Nexus imageView.setLayoutParams(new GalleryFlow.LayoutParams(350, 620)); } return imageView; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/GalleryAdapter.java
Java
art
1,587
package net.cardgame.orcalecard; import java.io.IOException; import jp.jma.oraclecard.MyApplication; import jp.jma.oraclecard.R; import net.cardgame.oraclecard.animation.AnimationFactory; import net.cardgame.oraclecard.animation.AnimationFactory.FlipDirection; import net.cardgame.oraclecard.common.ImageClickable; import net.cardgame.oraclecard.common.ThreadLoadImage; import net.cardgame.orcalecard.bean.CardBean; import net.cardgame.orcalecard.bean.SettingApp; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.KeyboardHelper; import uk.co.senab.bitmapcache.BitmapLruCache; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; import android.media.MediaPlayer.OnSeekCompleteListener; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.ViewFlipper; public class ResultActivity extends Activity implements OnClickListener { int deckId, number_of_card; ImageView img_card1_bg, img_card2_bg, img_card3_bg, img_card4_bg, img_bg, btnSaveHistory; ViewFlipper fliper1, fliper2, fliper3, fliper4; EditText txtQuestion; SettingApp setting; boolean flag = false; CardBean cardBean1, cardBean2, cardBean3, cardBean4; ImageClickable img_card1, img_card2, img_card3, img_card4; boolean performFlipCard = true; String strQuestion; MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); if (savedInstanceState != null) { performFlipCard = false; flag = true; } getData(); if (number_of_card == 1) setContentView(R.layout.result_one_card); else setContentView(R.layout.result_activity_layout); initView(); loadImageResource(); } void getData() { // get bundle setting = ConstantValue.getSettingApp(this); Bundle bundle = getIntent().getExtras(); number_of_card = bundle.getInt("number_of_card"); cardBean1 = bundle.getParcelable("cardBean1"); cardBean2 = bundle.getParcelable("cardBean2"); cardBean3 = bundle.getParcelable("cardBean3"); cardBean4 = bundle.getParcelable("cardBean4"); deckId = bundle.getInt("deckId"); strQuestion = bundle.getString("text_input"); } void initView() { setupUI(findViewById(R.id.parent)); findViewById(R.id.btnreplay_result).setOnClickListener(this); findViewById(R.id.btn_replace_1_3_result).setOnClickListener(this); findViewById(R.id.btn_goto_toppage_result).setOnClickListener(this); btnSaveHistory = (ImageView) findViewById(R.id.btn_share_facebook_result); btnSaveHistory.setOnClickListener(ResultActivity.this); findViewById(R.id.btnsetting_result).setOnClickListener(this); img_card1 = (ImageClickable) findViewById(R.id.img_card1_result); img_card2 = (ImageClickable) findViewById(R.id.img_card2_result); img_card3 = (ImageClickable) findViewById(R.id.img_card3_result); img_card4 = (ImageClickable) findViewById(R.id.img_card4_result); img_card1_bg = (ImageView) findViewById(R.id.img_card100_result); img_card2_bg = (ImageView) findViewById(R.id.img_card200_result); img_card3_bg = (ImageView) findViewById(R.id.img_card300_result); img_card4_bg = (ImageView) findViewById(R.id.img_card400_result); img_bg = (ImageView) findViewById(R.id.bg_result); fliper1 = (ViewFlipper) findViewById(R.id.viewFlipper1); fliper2 = (ViewFlipper) findViewById(R.id.viewFlipper2); fliper3 = (ViewFlipper) findViewById(R.id.viewFlipper3); fliper4 = (ViewFlipper) findViewById(R.id.viewFlipper4); txtQuestion = (EditText) findViewById(R.id.txtquestion_result); if (strQuestion != null) txtQuestion.setText(strQuestion); } /** * Load all image resource */ void loadImageResource() { // Load background image if (deckId == 999) { img_bg.setImageResource(R.drawable.bg999); img_card1_bg.setImageResource(R.drawable.c99900); switch (number_of_card) { case 3: img_card2_bg.setImageResource(R.drawable.c99900); img_card3_bg.setImageResource(R.drawable.c99900); break; case 4: img_card2_bg.setImageResource(R.drawable.c99900); img_card3_bg.setImageResource(R.drawable.c99900); img_card4_bg.setImageResource(R.drawable.c99900); break; default: break; } } else { new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPathBackgroundByDeckId(this, deckId), img_bg, 5).start(); String path = ConstantValue.getPathDeckImage(this, deckId, "d"); // Load card background (card00) new ThreadLoadImage(this, handlerLoadImage, ConstantValue.getPathDeckImage(this, deckId, "d"), img_card1_bg, 6).start(); } // Load card1,2,3,4 switch (number_of_card) { case 1: loadCard1(); break; case 3: loadCard1(); loadCard2(); loadCard3(); break; case 4: loadCard1(); loadCard2(); loadCard3(); loadCard4(); break; default: break; } } private Handler handlerLoadImage = new Handler() { private boolean finished1 = false, finished2 = false, finished3 = false, finished4 = false, finished5 = false, finished6 = false; public void handleMessage(Message msg) { if (msg.obj == null) return; if (deckId == 999) { finished5 = true; finished6 = true; } switch (msg.what) { case 1: finished1 = true; Drawable result1 = ((Drawable) msg.obj); Bitmap bitmap1 = ((BitmapDrawable) result1).getBitmap(); if (!bitmap1.isRecycled()) img_card1.setImageBitmap(bitmap1); fliper1.setDisplayedChild(0); break; case 2: finished2 = true; Drawable result2 = ((Drawable) msg.obj); Bitmap bitmap2 = ((BitmapDrawable) result2).getBitmap(); if (!bitmap2.isRecycled()) img_card2.setImageBitmap(bitmap2); fliper2.setDisplayedChild(0); break; case 3: finished3 = true; Drawable result3 = ((Drawable) msg.obj); Bitmap bitmap3 = ((BitmapDrawable) result3).getBitmap(); if (!bitmap3.isRecycled()) img_card3.setImageBitmap(bitmap3); fliper3.setDisplayedChild(0); break; case 4: finished4 = true; Drawable result4 = ((Drawable) msg.obj); Bitmap bitmap4 = ((BitmapDrawable) result4).getBitmap(); if (!bitmap4.isRecycled()) img_card4.setImageBitmap(bitmap4); fliper4.setDisplayedChild(0); break; case 5: finished5 = true; Drawable result5 = ((Drawable) msg.obj); Bitmap bitmap5 = ((BitmapDrawable) result5).getBitmap(); if (!bitmap5.isRecycled()) img_bg.setImageBitmap(bitmap5); break; case 6: finished6 = true; Drawable result6 = ((Drawable) msg.obj); Bitmap bitmap6 = ((BitmapDrawable) result6).getBitmap(); if (!bitmap6.isRecycled()) { if (number_of_card == 4) { img_card2_bg.setImageBitmap(bitmap6); img_card3_bg.setImageBitmap(bitmap6); img_card4_bg.setImageBitmap(bitmap6); } else if (number_of_card == 3) { img_card2_bg.setImageBitmap(bitmap6); img_card3_bg.setImageBitmap(bitmap6); } img_card1_bg.setImageBitmap(bitmap6); } break; default: break; } boolean loadFinished = false; if (number_of_card == 1) loadFinished = finished1 && finished5 && finished6; else if (number_of_card == 3) loadFinished = finished1 && finished2 && finished3 && finished5 && finished6; else if (number_of_card == 4) loadFinished = finished1 && finished2 && finished3 && finished4 && finished5 && finished6; if (loadFinished) { // perform Flip card if (performFlipCard) { if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper1, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(1).start(); } else { fliper1.setDisplayedChild(1); fliper2.setDisplayedChild(1); fliper3.setDisplayedChild(1); fliper4.setDisplayedChild(1); img_card1.setOnClickListener(ResultActivity.this); img_card2.setOnClickListener(ResultActivity.this); img_card3.setOnClickListener(ResultActivity.this); img_card4.setOnClickListener(ResultActivity.this); } } }; }; class ThreadFlipCard extends Thread { int what; ThreadFlipCard(int what) { this.what = what; } @Override public void run() { // TODO Auto-generated method stub super.run(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } handlerFlipCard.sendEmptyMessage(what); } } Handler handlerFlipCard = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: img_card1.setOnClickListener(ResultActivity.this); img_card1.setBackgroundResource(R.drawable.shadow_card); if (number_of_card > 1) { if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper2, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(2).start(); } else { flag = true; if (mediaPlayer != null) mediaPlayer.release(); } break; case 2: img_card2.setOnClickListener(ResultActivity.this); img_card2.setBackgroundResource(R.drawable.shadow_card); if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper3, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(3).start(); break; case 3: img_card3.setOnClickListener(ResultActivity.this); img_card3.setBackgroundResource(R.drawable.shadow_card); if (number_of_card > 3) { if (setting.sound) playMusic(); AnimationFactory.flipTransition(fliper4, FlipDirection.RIGHT_LEFT); new ThreadFlipCard(4).start(); } else { flag = true; if (mediaPlayer != null) mediaPlayer.release(); } break; case 4: img_card4.setOnClickListener(ResultActivity.this); img_card4.setBackgroundResource(R.drawable.shadow_card); flag = true; if (mediaPlayer != null) mediaPlayer.release(); break; default: break; } }; }; void loadCard1() { String path = ConstantValue.getPathCardDetail(this, cardBean1.deckId, cardBean1.cardId, number_of_card == 1 ? ConstantValue.X2 : ConstantValue.X3); img_card1.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card1, 1).start(); img_card1_bg.setVisibility(View.VISIBLE); img_card1.setVisibility(View.VISIBLE); if (cardBean1.isJump) findViewById(R.id.img_jump_card1_result) .setVisibility(View.VISIBLE); if (number_of_card != 1) findViewById(R.id.img_title_card1_result).setVisibility( View.VISIBLE); } void loadCard2() { String path = ConstantValue.getPathCardDetail(this, cardBean2.deckId, cardBean2.cardId, ConstantValue.X3); img_card2.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card2, 2).start(); img_card2_bg.setVisibility(View.VISIBLE); img_card2.setVisibility(View.VISIBLE); findViewById(R.id.img_title_card2_result).setVisibility(View.VISIBLE); if (cardBean2.isJump) { findViewById(R.id.img_jump_card2_result) .setVisibility(View.VISIBLE); } } void loadCard3() { String path = ConstantValue.getPathCardDetail(this, cardBean3.deckId, cardBean3.cardId, ConstantValue.X3); img_card3.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card3, 3).start(); img_card3_bg.setVisibility(View.VISIBLE); img_card3.setVisibility(View.VISIBLE); findViewById(R.id.img_title_card3_result).setVisibility(View.VISIBLE); if (cardBean3.isJump) findViewById(R.id.img_jump_card3_result) .setVisibility(View.VISIBLE); } void loadCard4() { String path = ConstantValue.getPathCardDetail(this, cardBean4.deckId, cardBean4.cardId, ConstantValue.X3); img_card4.setPath(path); new ThreadLoadImage(this, handlerLoadImage, path, img_card4, 4).start(); img_card4_bg.setVisibility(View.VISIBLE); img_card4.setVisibility(View.VISIBLE); findViewById(R.id.img_title_card4_result).setVisibility(View.VISIBLE); if (cardBean4.isJump) findViewById(R.id.img_jump_card4_result) .setVisibility(View.VISIBLE); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (!flag) return; switch (v.getId()) { case R.id.img_card1_result: flag = false; gotoCardDetail(cardBean1); break; case R.id.img_card2_result: flag = false; gotoCardDetail(cardBean2); break; case R.id.img_card3_result: flag = false; gotoCardDetail(cardBean3); break; case R.id.img_card4_result: flag = false; gotoCardDetail(cardBean4); break; case R.id.btnreplay_result: goBack(); break; case R.id.btn_replace_1_3_result: // go to card deck activity goCardDeck(); break; case R.id.btn_goto_toppage_result: clearCacheBefore(); goToppage(); break; case R.id.btnsetting_result: flag = false; Intent intent2 = new Intent(this, SettingActiviy.class); startActivityForResult(intent2, 0); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); break; case R.id.btn_share_facebook_result: flag = false; gotoSaveHistory(); break; default: break; } } void gotoSaveHistory() { Intent intent = new Intent(this, SaveHistoryActivity.class); intent.putExtra("number_of_card", number_of_card); intent.putExtra("deckId", deckId); intent.putExtra("cardBean1", cardBean1); intent.putExtra("cardBean2", cardBean2); intent.putExtra("cardBean3", cardBean3); intent.putExtra("cardBean4", cardBean4); intent.putExtra("question", txtQuestion.getText().toString()); startActivityForResult(intent, ConstantValue.RESULT_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } void gotoCardDetail(CardBean cardBean) { Intent intentGotoCardDetail = new Intent(this, CardDetailActivity.class); intentGotoCardDetail.putExtra("deckId", cardBean.deckId); intentGotoCardDetail.putExtra("cardId", cardBean.cardId); startActivityForResult(intentGotoCardDetail, ConstantValue.RESULT_ACTIVITY); overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); flag = true; setting = ConstantValue.getSettingApp(this); } public void setupUI(View view) { // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { view.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { v.requestFocus(); KeyboardHelper.hideSoftKeyboard(ResultActivity.this); return false; } }); } // If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupUI(innerView); } } } private void playMusic() { if (mediaPlayer == null) { mediaPlayer = MediaPlayer.create(this, R.raw.se_card_flip); mediaPlayer.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub mp.start(); } }); } else { mediaPlayer.seekTo(0); mediaPlayer.start(); } } @Override protected void onDestroy() { // TODO Auto-generated method stub if (mediaPlayer != null) { mediaPlayer.release(); } ClearCache(); super.onDestroy(); } private void ClearCache() { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean1.deckId, cardBean1.cardId, number_of_card == 1 ? ConstantValue.X2 : ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean2.deckId, cardBean2.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean3.deckId, cardBean3.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean4.deckId, cardBean4.cardId, ConstantValue.X3)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean1.deckId, cardBean1.cardId, ConstantValue.X1)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean2.deckId, cardBean2.cardId, ConstantValue.X1)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean3.deckId, cardBean3.cardId, ConstantValue.X1)); cache.removeFromMemory(ConstantValue.getPathCardDetail(this, cardBean4.deckId, cardBean4.cardId, ConstantValue.X1)); if (deckId == 999) { String backgoundCard1 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); String backgoundCard2 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); String backgoundCard3 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); String backgoundCard4 = ConstantValue.getPathBackgroundByDeckId( this, cardBean1.deckId); cache.removeFromMemory(backgoundCard1); cache.removeFromMemory(backgoundCard2); cache.removeFromMemory(backgoundCard3); cache.removeFromMemory(backgoundCard4); } } @Override public void onBackPressed() { // TODO Auto-generated method stub goBack(); } void goBack() { Intent intent = new Intent(this, GetCardActivity.class); Bundle bundle = getIntent().getExtras(); if (number_of_card != 1) { number_of_card = setting.adviseCard ? 4 : 3; bundle.putInt("number_of_card", number_of_card); } bundle.remove("cardBean1"); bundle.remove("cardBean2"); bundle.remove("cardBean3"); bundle.remove("cardBean4"); bundle.remove("text_input"); intent.putExtras(bundle); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } void goToppage() { Intent intent = new Intent(this, TopPageActivity.class); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } void goCardDeck() { Intent intent = new Intent(this, CardDeckActivity.class); Bundle bundle = getIntent().getExtras(); bundle.remove("cardBean1"); bundle.remove("cardBean2"); bundle.remove("cardBean3"); bundle.remove("cardBean4"); bundle.remove("text_input"); intent.putExtras(bundle); startActivity(intent); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right); this.finish(); } private void clearCacheBefore() { if (deckId != 999) { BitmapLruCache cache = MyApplication.getInstance().getBitmapCache(); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "s")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "p")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "m")); cache.removeFromMemory(ConstantValue.getPathDeckImage(this, deckId, "d")); cache.removeFromMemory(ConstantValue.getPathBackgroundByDeckId( this, deckId)); } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/orcalecard/ResultActivity.java
Java
art
20,116
/* * Copyright (C) 2011 The Android Open Source Project * * 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 net.cardgame.oraclecard.animation; import java.util.HashMap; import java.util.Random; import android.graphics.Bitmap; /** * This class represents a single Droidflake, with properties representing its * size, rotation, location, and speed. */ public class Flake { // These are the unique properties of any flake: its size, rotation, speed, // location, and its underlying Bitmap object float x, y; float rotation; float speed; float rotationSpeed; int width, height; Bitmap bitmap; int move; boolean moveLeft; // This map stores pre-scaled bitmaps according to the width. No reason to // create // new bitmaps for sizes we've already seen. static HashMap<Integer, Bitmap> bitmapMap = new HashMap<Integer, Bitmap>(); /** * Creates a new droidflake in the given xRange and with the given bitmap. * Parameters of location, size, rotation, and speed are randomly * determined. */ static Flake createFlake(float xRange, Bitmap originalBitmap, int width, int x) { Flake flake = new Flake(); // Size each flake with a width between 5 and 55 and a proportional // height flake.width = width; flake.height = width; // Position the flake horizontally between the left and right of the // range Random random = new Random(); flake.x = random.nextInt((int) xRange - flake.width); if (flake.x > xRange / 2) flake.moveLeft = true; else flake.moveLeft = false; // Position the flake vertically slightly off the top of the display flake.y = 0 - (flake.height); // Each flake travels at 50-200 pixels per second flake.speed = 50; // Flakes start at -90 to 90 degrees rotation, and rotate between -45 // and 45 // degrees per second flake.rotation = (float) Math.random() * 180 - 90; flake.rotationSpeed = (float) Math.random() * 90 - 45; // Get the cached bitmap for this size if it exists, otherwise create // and cache one flake.bitmap = bitmapMap.get(x); if (flake.bitmap == null) { flake.bitmap = Bitmap.createScaledBitmap(originalBitmap, (int) flake.width, (int) flake.height, true); bitmapMap.put(x, flake.bitmap); } return flake; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/animation/Flake.java
Java
art
2,761
/** * Copyright (c) 2012 Ephraim Tekle genzeb@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Ephraim A. Tekle * */ package net.cardgame.oraclecard.animation; import android.graphics.Camera; import android.graphics.Matrix; import android.view.animation.Animation; import android.view.animation.Transformation; /** * This class extends Animation to support a 3D flip view transition animation. Two instances of this class is * required: one for the "from" view and another for the "to" view. * * NOTE: use {@link AnimationFactory} to use this class. * * @author Ephraim A. Tekle * */ public class FlipAnimation extends Animation { private final float mFromDegrees; private final float mToDegrees; private final float mCenterX; private final float mCenterY; private Camera mCamera; private final ScaleUpDownEnum scaleType; /** * How much to scale up/down. The default scale of 75% of full size seems optimal based on testing. Feel free to experiment away, however. */ public static final float SCALE_DEFAULT = 0.75f; private float scale; /** * Constructs a new {@code FlipAnimation} object.Two {@code FlipAnimation} objects are needed for a complete transition b/n two views. * * @param fromDegrees the start angle in degrees for a rotation along the y-axis, i.e. in-and-out of the screen, i.e. 3D flip. This should really be multiple of 90 degrees. * @param toDegrees the end angle in degrees for a rotation along the y-axis, i.e. in-and-out of the screen, i.e. 3D flip. This should really be multiple of 90 degrees. * @param centerX the x-axis value of the center of rotation * @param centerY the y-axis value of the center of rotation * @param scale to get a 3D effect, the transition views need to be zoomed (scaled). This value must be b/n (0,1) or else the default scale {@link #SCALE_DEFAULT} is used. * @param scaleType flip view transition is broken down into two: the zoom-out of the "from" view and the zoom-in of the "to" view. This parameter is used to determine which is being done. See {@link ScaleUpDownEnum}. */ public FlipAnimation(float fromDegrees, float toDegrees, float centerX, float centerY, float scale, ScaleUpDownEnum scaleType) { mFromDegrees = fromDegrees; mToDegrees = toDegrees; mCenterX = centerX; mCenterY = centerY; this.scale = (scale<=0||scale>=1)?SCALE_DEFAULT:scale; this.scaleType = scaleType==null?ScaleUpDownEnum.SCALE_CYCLE:scaleType; } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); mCamera = new Camera(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { final float fromDegrees = mFromDegrees; float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime); final float centerX = mCenterX; final float centerY = mCenterY; final Camera camera = mCamera; final Matrix matrix = t.getMatrix(); camera.save(); camera.rotateY(degrees); camera.getMatrix(matrix); camera.restore(); matrix.preTranslate(-centerX, -centerY); matrix.postTranslate(centerX, centerY); matrix.preScale(scaleType.getScale(scale, interpolatedTime), scaleType.getScale(scale, interpolatedTime), centerX, centerY); } /** * This enumeration is used to determine the zoom (or scale) behavior of a {@link FlipAnimation}. * * @author Ephraim A. Tekle * */ public static enum ScaleUpDownEnum { /** * The view will be scaled up from the scale value until it's at 100% zoom level (i.e. no zoom). */ SCALE_UP, /** * The view will be scaled down starting at no zoom (100% zoom level) until it's at a specified zoom level. */ SCALE_DOWN, /** * The view will cycle through a zoom down and then zoom up. */ SCALE_CYCLE, /** * No zoom effect is applied. */ SCALE_NONE; /** * The intermittent zoom level given the current or desired maximum zoom level for the specified iteration * * @param max the maximum desired or current zoom level * @param iter the iteration (from 0..1). * @return the current zoom level */ public float getScale(float max, float iter) { switch(this) { case SCALE_UP: return max + (1-max)*iter; case SCALE_DOWN: return 1 - (1-max)*iter; case SCALE_CYCLE: { final boolean halfWay = (iter > 0.5); if (halfWay) { return max + (1-max)*(iter-0.5f)*2; } else { return 1 - (1-max)*(iter*2); } } default: return 1; } } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/animation/FlipAnimation.java
Java
art
5,649
/* * Copyright (C) 2011 The Android Open Source Project * * 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 net.cardgame.oraclecard.animation; import java.util.ArrayList; import java.util.Random; import jp.jma.oraclecard.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.view.View; import com.nineoldandroids.animation.ValueAnimator; import com.nineoldandroids.animation.ValueAnimator.AnimatorUpdateListener; /** * This class is the custom view where all of the Droidflakes are drawn. This * class has all of the logic for adding, subtracting, and rendering * Droidflakes. */ public class FlakeView extends View { Bitmap droid; // The bitmap that all flakes use Bitmap droid2; int numFlakes = 0; // Current number of flakes ArrayList<Flake> flakes = new ArrayList<Flake>(); // List of current flakes // Animator used to drive all separate flake animations. Rather than have // potentially // hundreds of separate animators, we just use one and then update all // flakes for each // frame of that single animation. ValueAnimator animator = ValueAnimator.ofFloat(0, 1); long startTime, prevTime; // Used to track elapsed time for animations and // fps int frames = 0; // Used to track frames per second Matrix m = new Matrix(); // Matrix used to translate/rotate each flake // during rendering /** * Constructor. Create objects used throughout the life of the View: the * Paint and the animator */ public FlakeView(Context context) { super(context); // This listener is where the action is for the flak animations. Every // frame of the // animation, we calculate the elapsed time and update every flake's // position and rotation // according to its speed. animator.addUpdateListener(new AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator arg0) { long nowTime = System.currentTimeMillis(); float secs = (float) (nowTime - prevTime) / 1000f; prevTime = nowTime; for (Flake flake : flakes) { if (flake.move == 1000) { flake.moveLeft = !flake.moveLeft; flake.move = 0; } else { flake.move++; } if (flake.moveLeft) { flake.x -= (flake.speed * secs); } else { flake.x += (flake.speed * secs); } if (flake.x < 0 - flake.width / 2) { // If a flake falls off the bottom, send it back to the // top flake.move = 0; flake.moveLeft = false; } else if (flake.x > getWidth() - flake.width / 2) { flake.move = 0; flake.moveLeft = true; } flake.y += Math.random() * (flake.speed * secs); if (flake.y > getHeight()) { // If a flake falls off the bottom, send it back to the // top flake.y = 0 - flake.height; Random random = new Random(); flake.x = random .nextInt((int) getWidth() - flake.width); } flake.rotation = flake.rotation + (flake.rotationSpeed * secs); } // Force a redraw to see the flakes in their new positions and // orientations invalidate(); } }); animator.setRepeatCount(ValueAnimator.INFINITE); animator.setDuration(2000); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Reset list of droidflakes, then restart it with 8 flakes flakes.clear(); numFlakes = 2; final int widthFeather = getResources().getInteger( R.integer.width_feather); droid = BitmapFactory.decodeResource(getResources(), R.drawable.feather01); flakes.add(Flake.createFlake(getWidth(), droid, widthFeather, getWidth() + widthFeather)); Thread thread = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { Thread.sleep(4000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } droid2 = BitmapFactory.decodeResource(getResources(), R.drawable.feather02); flakes.add(Flake.createFlake(getWidth(), droid2, widthFeather, -widthFeather)); } }); thread.start(); // Cancel animator in case it was already running animator.cancel(); // Set up fps tracking and start the animation startTime = System.currentTimeMillis(); prevTime = startTime; frames = 0; animator.start(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // For each flake: back-translate by half its size (this allows it to // rotate around its center), // rotate by its current rotation, translate by its location, then draw // its bitmap for (Flake flake : flakes) { m.setTranslate(-flake.width / 2, -flake.height / 2); m.postRotate(flake.rotation); m.postTranslate(flake.width / 2 + flake.x, flake.height / 2 + flake.y); canvas.drawBitmap(flake.bitmap, m, null); } } public void pause() { // Make sure the animator's not spinning in the background when the // activity is paused. animator.cancel(); } public void resume() { animator.start(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/animation/FlakeView.java
Java
art
5,696
/** * Copyright (c) 2012 Ephraim Tekle genzeb@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Ephraim A. Tekle * */ package net.cardgame.oraclecard.animation; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.TranslateAnimation; import android.widget.ViewAnimator; /** * This class contains methods for creating {@link Animation} objects for some of the most common animation, including a 3D flip animation, {@link FlipAnimation}. * Furthermore, utility methods are provided for initiating fade-in-then-out and flip animations. * * @author Ephraim A. Tekle * */ public class AnimationFactory { /** * The {@code FlipDirection} enumeration defines the most typical flip view transitions: left-to-right and right-to-left. {@code FlipDirection} is used during the creation of {@link FlipAnimation} animations. * * @author Ephraim A. Tekle * */ public static enum FlipDirection { LEFT_RIGHT, RIGHT_LEFT; public float getStartDegreeForFirstView() { return 0; } public float getStartDegreeForSecondView() { switch(this) { case LEFT_RIGHT: return -90; case RIGHT_LEFT: return 90; default: return 0; } } public float getEndDegreeForFirstView() { switch(this) { case LEFT_RIGHT: return 90; case RIGHT_LEFT: return -90; default: return 0; } } public float getEndDegreeForSecondView() { return 0; } public FlipDirection theOtherDirection() { switch(this) { case LEFT_RIGHT: return RIGHT_LEFT; case RIGHT_LEFT: return LEFT_RIGHT; default: return null; } } }; /** * Create a pair of {@link FlipAnimation} that can be used to flip 3D transition from {@code fromView} to {@code toView}. A typical use case is with {@link ViewAnimator} as an out and in transition. * * NOTE: Avoid using this method. Instead, use {@link #flipTransition}. * * @param fromView the view transition away from * @param toView the view transition to * @param dir the flip direction * @param duration the transition duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return */ public static Animation[] flipAnimation(final View fromView, final View toView, FlipDirection dir, long duration, Interpolator interpolator) { Animation[] result = new Animation[2]; float centerX; float centerY; centerX = fromView.getWidth() / 2.0f; centerY = fromView.getHeight() / 2.0f; Animation outFlip= new FlipAnimation(dir.getStartDegreeForFirstView(), dir.getEndDegreeForFirstView(), centerX, centerY, FlipAnimation.SCALE_DEFAULT, FlipAnimation.ScaleUpDownEnum.SCALE_DOWN); outFlip.setDuration(duration); outFlip.setFillAfter(true); outFlip.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); AnimationSet outAnimation = new AnimationSet(true); outAnimation.addAnimation(outFlip); result[0] = outAnimation; // Uncomment the following if toView has its layout established (not the case if using ViewFlipper and on first show) //centerX = toView.getWidth() / 2.0f; //centerY = toView.getHeight() / 2.0f; Animation inFlip = new FlipAnimation(dir.getStartDegreeForSecondView(), dir.getEndDegreeForSecondView(), centerX, centerY, FlipAnimation.SCALE_DEFAULT, FlipAnimation.ScaleUpDownEnum.SCALE_UP); inFlip.setDuration(duration); inFlip.setFillAfter(true); inFlip.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); inFlip.setStartOffset(duration); AnimationSet inAnimation = new AnimationSet(true); inAnimation.addAnimation(inFlip); result[1] = inAnimation; return result; } /** * Flip to the next view of the {@code ViewAnimator}'s subviews. A call to this method will initiate a {@link FlipAnimation} to show the next View. * If the currently visible view is the last view, flip direction will be reversed for this transition. * * @param viewAnimator the {@code ViewAnimator} * @param dir the direction of flip */ public static void flipTransition(final ViewAnimator viewAnimator, FlipDirection dir) { final View fromView = viewAnimator.getCurrentView(); final int currentIndex = viewAnimator.getDisplayedChild(); final int nextIndex = (currentIndex + 1)%viewAnimator.getChildCount(); final View toView = viewAnimator.getChildAt(nextIndex); Animation[] animc = AnimationFactory.flipAnimation(fromView, toView, (nextIndex < currentIndex?dir.theOtherDirection():dir), 500, null); viewAnimator.setOutAnimation(animc[0]); viewAnimator.setInAnimation(animc[1]); viewAnimator.showNext(); } ////////////// /** * Slide animations to enter a view from left. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation inFromLeftAnimation(long duration, Interpolator interpolator) { Animation inFromLeft = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); inFromLeft.setDuration(duration); inFromLeft.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); //AccelerateInterpolator return inFromLeft; } /** * Slide animations to hide a view by sliding it to the right * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation outToRightAnimation(long duration, Interpolator interpolator) { Animation outtoRight = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); outtoRight.setDuration(duration); outtoRight.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return outtoRight; } /** * Slide animations to enter a view from right. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation inFromRightAnimation(long duration, Interpolator interpolator) { Animation inFromRight = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); inFromRight.setDuration(duration); inFromRight.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return inFromRight; } /** * Slide animations to hide a view by sliding it to the left. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation outToLeftAnimation(long duration, Interpolator interpolator) { Animation outtoLeft = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); outtoLeft.setDuration(duration); outtoLeft.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return outtoLeft; } /** * Slide animations to enter a view from top. * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation inFromTopAnimation(long duration, Interpolator interpolator) { Animation infromtop = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f ); infromtop.setDuration(duration); infromtop.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return infromtop; } /** * Slide animations to hide a view by sliding it to the top * * @param duration the animation duration in milliseconds * @param interpolator the interpolator to use (pass {@code null} to use the {@link AccelerateInterpolator} interpolator) * @return a slide transition animation */ public static Animation outToTopAnimation(long duration, Interpolator interpolator) { Animation outtotop = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f ); outtotop.setDuration(duration); outtotop.setInterpolator(interpolator==null?new AccelerateInterpolator():interpolator); return outtotop; } /** * A fade animation that will fade the subject in by changing alpha from 0 to 1. * * @param duration the animation duration in milliseconds * @param delay how long to wait before starting the animation, in milliseconds * @return a fade animation * @see #fadeInAnimation(View, long) */ public static Animation fadeInAnimation(long duration, long delay) { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); fadeIn.setDuration(duration); fadeIn.setStartOffset(delay); return fadeIn; } /** * A fade animation that will fade the subject out by changing alpha from 1 to 0. * * @param duration the animation duration in milliseconds * @param delay how long to wait before starting the animation, in milliseconds * @return a fade animation * @see #fadeOutAnimation(View, long) */ public static Animation fadeOutAnimation(long duration, long delay) { Animation fadeOut = new AlphaAnimation(1, 0); fadeOut.setInterpolator(new AccelerateInterpolator()); fadeOut.setStartOffset(delay); fadeOut.setDuration(duration); return fadeOut; } /** * A fade animation that will ensure the View starts and ends with the correct visibility * @param view the View to be faded in * @param duration the animation duration in milliseconds * @return a fade animation that will set the visibility of the view at the start and end of animation */ public static Animation fadeInAnimation(long duration, final View view) { Animation animation = fadeInAnimation(500, 0); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { view.setVisibility(View.GONE); } }); return animation; } /** * A fade animation that will ensure the View starts and ends with the correct visibility * @param view the View to be faded out * @param duration the animation duration in milliseconds * @return a fade animation that will set the visibility of the view at the start and end of animation */ public static Animation fadeOutAnimation(long duration, final View view) { Animation animation = fadeOutAnimation(500, 0); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { view.setVisibility(View.VISIBLE); } }); return animation; } /** * Creates a pair of animation that will fade in, delay, then fade out * @param duration the animation duration in milliseconds * @param delay how long to wait after fading in the subject and before starting the fade out * @return a fade in then out animations */ public static Animation[] fadeInThenOutAnimation(long duration, long delay) { return new Animation[] {fadeInAnimation(duration,0), fadeOutAnimation(duration, duration+delay)}; } /** * Fades the view in. Animation starts right away. * @param v the view to be faded in */ public static void fadeOut(View v) { if (v==null) return; v.startAnimation(fadeOutAnimation(500, v)); } /** * Fades the view out. Animation starts right away. * @param v the view to be faded out */ public static void fadeIn(View v) { if (v==null) return; v.startAnimation(fadeInAnimation(500, v)); } /** * Fades the view in, delays the specified amount of time, then fades the view out * @param v the view to be faded in then out * @param delay how long the view will be visible for */ public static void fadeInThenOut(final View v, long delay) { if (v==null) return; v.setVisibility(View.VISIBLE); AnimationSet animation = new AnimationSet(true); Animation[] fadeInOut = fadeInThenOutAnimation(500,delay); animation.addAnimation(fadeInOut[0]); animation.addAnimation(fadeInOut[1]); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { v.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationStart(Animation animation) { v.setVisibility(View.VISIBLE); } }); v.startAnimation(animation); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/animation/AnimationFactory.java
Java
art
15,303
// Copyright 2002, Google, Inc. // // 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 net.cardgame.oraclecard.billingutils; /** * Exception thrown when encountering an invalid Base64 input character. * * @author nelson */ public class Base64DecoderException extends Exception { public Base64DecoderException() { super(); } public Base64DecoderException(String s) { super(s); } private static final long serialVersionUID = 1L; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/Base64DecoderException.java
Java
art
1,016
/* Copyright (c) 2012 Google Inc. * * 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 net.cardgame.oraclecard.billingutils; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import android.text.TextUtils; import android.util.Log; /** * Security-related methods. For a secure implementation, all of this code * should be implemented on a server that communicates with the * application on the device. For the sake of simplicity and clarity of this * example, this code is included here and is executed on the device. If you * must verify the purchases on the phone, you should obfuscate this code to * make it harder for an attacker to replace the code with stubs that treat all * purchases as verified. */ public class Security { private static final String TAG = "IABUtil/Security"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; /** * Verifies that the data was signed with the given signature, and returns * the verified purchase. The data is in JSON format and signed * with a private key. The data also contains the {@link PurchaseState} * and product ID of the purchase. * @param base64PublicKey the base64-encoded public key to use for verifying. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return false; } boolean verified = false; if (!TextUtils.isEmpty(signature)) { PublicKey key = Security.generatePublicKey(base64PublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return false; } } return true; } /** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid */ public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); throw new IllegalArgumentException(e); } } /** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException."); } catch (InvalidKeyException e) { Log.e(TAG, "Invalid key specification."); } catch (SignatureException e) { Log.e(TAG, "Signature exception."); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); } return false; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/Security.java
Java
art
5,220
package net.cardgame.oraclecard.billingutils; // Portions copyright 2002, Google, Inc. // // 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. // This code was converted from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed. /* The original code said: * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit * <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rharder@usa.net * @version 1.3 */ /** * Base64 converter class. This code is not a complete MIME encoder; * it simply converts binary data to base64 data and back. * * <p>Note {@link CharBase64} is a GWT-compatible implementation of this * class. */ public class Base64 { /** Specify encoding (value is {@code true}). */ public final static boolean ENCODE = true; /** Specify decoding (value is {@code false}). */ public final static boolean DECODE = false; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte) '\n'; /** * The 64 valid Base64 values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * The 64 valid web safe Base64 values. */ private final static byte[] WEBSAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; /** The web safe decodabet */ private final static byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44 62, // Dash '-' sign at decimal 45 -9, -9, // Decimal 46-47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91-94 63, // Underscore '_' at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // Indicates white space in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates equals sign in encoding private final static byte EQUALS_SIGN_ENC = -1; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param alphabet is the encoding alphabet * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index alphabet // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = alphabet[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Encodes a byte array into Base64 notation. * Equivalent to calling * {@code encodeBytes(source, 0, source.length)} * * @param source The data to convert * @since 1.4 */ public static String encode(byte[] source) { return encode(source, 0, source.length, ALPHABET, true); } /** * Encodes a byte array into web safe Base64 notation. * * @param source The data to convert * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries */ public static String encodeWebSafe(byte[] source, boolean doPadding) { return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet the encoding alphabet * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries * @since 1.4 */ public static String encode(byte[] source, int off, int len, byte[] alphabet, boolean doPadding) { byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE); int outLen = outBuff.length; // If doPadding is false, set length to truncate '=' // padding characters while (doPadding == false && outLen > 0) { if (outBuff[outLen - 1] != '=') { break; } outLen -= 1; } return new String(outBuff, 0, outLen); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet is the encoding alphabet * @param maxLineLength maximum length of one line. * @return the BASE64-encoded byte array */ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet, int maxLineLength) { int lenDiv3 = (len + 2) / 3; // ceil(len / 3) int len43 = lenDiv3 * 4; byte[] outBuff = new byte[len43 // Main 4:3 + (len43 / maxLineLength)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { // The following block of code is the same as // encode3to4( source, d + off, 3, outBuff, e, alphabet ); // but inlined for faster encoding (~20% improvement) int inBuff = ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24); outBuff[e] = alphabet[(inBuff >>> 18)]; outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f]; outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f]; outBuff[e + 3] = alphabet[(inBuff) & 0x3f]; lineLength += 4; if (lineLength == maxLineLength) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, alphabet); lineLength += 4; if (lineLength == maxLineLength) { // Add a last newline outBuff[e + 4] = NEW_LINE; e++; } e += 4; } assert (e == outBuff.length); return outBuff; } /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param decodabet the decodabet for decoding Base64 content * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, byte[] decodabet) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } else { // Example: DkLE int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes /** * Decodes data from Base64 notation. * * @param s the string to decode (decoded in default encoding) * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decode(bytes, 0, bytes.length); } /** * Decodes data from web safe Base64 notation. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param s the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decodeWebSafe(bytes, 0, bytes.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source The Base64 encoded data * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source) throws Base64DecoderException { return decode(source, 0, source.length); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded data. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException { return decodeWebSafe(source, 0, source.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, DECODABET); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded byte array. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data */ public static byte[] decodeWebSafe(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, WEBSAFE_DECODABET); } /** * Decodes Base64 content using the supplied decodabet and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @param decodabet the decodabet for decoding Base64 content * @return decoded data */ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet) throws Base64DecoderException { int len34 = len * 3 / 4; byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits sbiDecode = decodabet[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { // An equals sign (for padding) must not occur at position 0 or 1 // and must be the last byte[s] in the encoded value if (sbiCrop == EQUALS_SIGN) { int bytesLeft = len - i; byte lastByte = (byte) (source[len - 1 + off] & 0x7f); if (b4Posn == 0 || b4Posn == 1) { throw new Base64DecoderException( "invalid padding byte '=' at byte offset " + i); } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) { throw new Base64DecoderException( "padding byte '=' falsely signals end of encoded value " + "at offset " + i); } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) { throw new Base64DecoderException( "encoded value has invalid trailing byte"); } break; } b4[b4Posn++] = sbiCrop; if (b4Posn == 4) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); b4Posn = 0; } } } else { throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)"); } } // Because web safe encoding allows non padding base64 encodes, we // need to pad the rest of the b4 buffer with equal signs when // b4Posn != 0. There can be at most 2 equal signs at the end of // four characters, so the b4 buffer must have two or three // characters. This also catches the case where the input is // padded with EQUALS_SIGN if (b4Posn != 0) { if (b4Posn == 1) { throw new Base64DecoderException("single trailing character at offset " + (len - 1)); } b4[b4Posn++] = EQUALS_SIGN; outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/Base64.java
Java
art
24,849
/* Copyright (c) 2012 Google Inc. * * 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 net.cardgame.oraclecard.billingutils; /** * Exception thrown when something went wrong with in-app billing. * An IabException has an associated IabResult (an error). * To get the IAB result that caused this exception to be thrown, * call {@link #getResult()}. */ public class IabException extends Exception { IabResult mResult; public IabException(IabResult r) { this(r, null); } public IabException(int response, String message) { this(new IabResult(response, message)); } public IabException(IabResult r, Exception cause) { super(r.getMessage(), cause); mResult = r; } public IabException(int response, String message, Exception cause) { this(new IabResult(response, message), cause); } /** Returns the IAB result (error) that this exception signals. */ public IabResult getResult() { return mResult; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/IabException.java
Java
art
1,545
/* Copyright (c) 2012 Google Inc. * * 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 net.cardgame.oraclecard.billingutils; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app billing purchase. */ public class Purchase { String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS String mOrderId; String mPackageName; String mSku; long mPurchaseTime; int mPurchaseState; String mDeveloperPayload; String mToken; String mOriginalJson; String mSignature; public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException { mItemType = itemType; mOriginalJson = jsonPurchaseInfo; JSONObject o = new JSONObject(mOriginalJson); mOrderId = o.optString("orderId"); mPackageName = o.optString("packageName"); mSku = o.optString("productId"); mPurchaseTime = o.optLong("purchaseTime"); mPurchaseState = o.optInt("purchaseState"); mDeveloperPayload = o.optString("developerPayload"); mToken = o.optString("token", o.optString("purchaseToken")); mSignature = signature; } public String getItemType() { return mItemType; } public String getOrderId() { return mOrderId; } public String getPackageName() { return mPackageName; } public String getSku() { return mSku; } public long getPurchaseTime() { return mPurchaseTime; } public int getPurchaseState() { return mPurchaseState; } public String getDeveloperPayload() { return mDeveloperPayload; } public String getToken() { return mToken; } public String getOriginalJson() { return mOriginalJson; } public String getSignature() { return mSignature; } @Override public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/Purchase.java
Java
art
2,428
/* Copyright (c) 2012 Google Inc. * * 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 net.cardgame.oraclecard.billingutils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a block of information about in-app items. * An Inventory is returned by such methods as {@link IabHelper#queryInventory}. */ public class Inventory { Map<String,SkuDetails> mSkuMap = new HashMap<String,SkuDetails>(); Map<String,Purchase> mPurchaseMap = new HashMap<String,Purchase>(); Inventory() { } /** Returns the listing details for an in-app product. */ public SkuDetails getSkuDetails(String sku) { return mSkuMap.get(sku); } /** Returns purchase information for a given product, or null if there is no purchase. */ public Purchase getPurchase(String sku) { return mPurchaseMap.get(sku); } /** Returns whether or not there exists a purchase of the given product. */ public boolean hasPurchase(String sku) { return mPurchaseMap.containsKey(sku); } /** Return whether or not details about the given product are available. */ public boolean hasDetails(String sku) { return mSkuMap.containsKey(sku); } /** * Erase a purchase (locally) from the inventory, given its product ID. This just * modifies the Inventory object locally and has no effect on the server! This is * useful when you have an existing Inventory object which you know to be up to date, * and you have just consumed an item successfully, which means that erasing its * purchase data from the Inventory you already have is quicker than querying for * a new Inventory. */ public void erasePurchase(String sku) { if (mPurchaseMap.containsKey(sku)) mPurchaseMap.remove(sku); } /** Returns a list of all owned product IDs. */ List<String> getAllOwnedSkus() { return new ArrayList<String>(mPurchaseMap.keySet()); } /** Returns a list of all owned product IDs of a given type */ List<String> getAllOwnedSkus(String itemType) { List<String> result = new ArrayList<String>(); for (Purchase p : mPurchaseMap.values()) { if (p.getItemType().equals(itemType)) result.add(p.getSku()); } return result; } /** Returns a list of all purchases. */ List<Purchase> getAllPurchases() { return new ArrayList<Purchase>(mPurchaseMap.values()); } void addSkuDetails(SkuDetails d) { mSkuMap.put(d.getSku(), d); } void addPurchase(Purchase p) { mPurchaseMap.put(p.getSku(), p); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/Inventory.java
Java
art
3,266
/* Copyright (c) 2012 Google Inc. * * 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 net.cardgame.oraclecard.billingutils; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.ServiceConnection; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import com.android.vending.billing.IInAppBillingService; /** * Provides convenience methods for in-app billing. You can create one instance of this * class for your application and use it to process in-app billing operations. * It provides synchronous (blocking) and asynchronous (non-blocking) methods for * many common in-app billing operations, as well as automatic signature * verification. * * After instantiating, you must perform setup in order to start using the object. * To perform setup, call the {@link #startSetup} method and provide a listener; * that listener will be notified when setup is complete, after which (and not before) * you may call other methods. * * After setup is complete, you will typically want to request an inventory of owned * items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync} * and related methods. * * When you are done with this object, don't forget to call {@link #dispose} * to ensure proper cleanup. This object holds a binding to the in-app billing * service, which will leak unless you dispose of it correctly. If you created * the object on an Activity's onCreate method, then the recommended * place to dispose of it is the Activity's onDestroy method. * * A note about threading: When using this object from a background thread, you may * call the blocking versions of methods; when using from a UI thread, call * only the asynchronous versions and handle the results via callbacks. * Also, notice that you can only call one asynchronous operation at a time; * attempting to start a second asynchronous operation while the first one * has not yet completed will result in an exception being thrown. * * @author Bruno Oliveira (Google) * */ public class IabHelper { // Is debug logging enabled? boolean mDebugLog = false; String mDebugTag = "IabHelper"; // Is setup done? boolean mSetupDone = false; // Has this object been disposed of? (If so, we should ignore callbacks, etc) boolean mDisposed = false; // Are subscriptions supported? boolean mSubscriptionsSupported = false; // Is an asynchronous operation in progress? // (only one at a time can be in progress) boolean mAsyncInProgress = false; // (for logging/debugging) // if mAsyncInProgress == true, what asynchronous operation is in progress? String mAsyncOperation = ""; // Context we were passed during initialization Context mContext; // Connection to the service IInAppBillingService mService; ServiceConnection mServiceConn; // The request code used to launch purchase flow int mRequestCode; // The item type of the current purchase flow String mPurchasingItemType; // Public key for verifying signature, in base64 encoding String mSignatureBase64 = null; // Billing response codes public static final int BILLING_RESPONSE_RESULT_OK = 0; public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; public static final int BILLING_RESPONSE_RESULT_ERROR = 6; public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; // IAB Helper error codes public static final int IABHELPER_ERROR_BASE = -1000; public static final int IABHELPER_REMOTE_EXCEPTION = -1001; public static final int IABHELPER_BAD_RESPONSE = -1002; public static final int IABHELPER_VERIFICATION_FAILED = -1003; public static final int IABHELPER_SEND_INTENT_FAILED = -1004; public static final int IABHELPER_USER_CANCELLED = -1005; public static final int IABHELPER_UNKNOWN_PURCHASE_RESPONSE = -1006; public static final int IABHELPER_MISSING_TOKEN = -1007; public static final int IABHELPER_UNKNOWN_ERROR = -1008; public static final int IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE = -1009; public static final int IABHELPER_INVALID_CONSUMPTION = -1010; // Keys for the responses from InAppBillingService public static final String RESPONSE_CODE = "RESPONSE_CODE"; public static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; public static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; public static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; public static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; public static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; public static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; public static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; public static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // Item types public static final String ITEM_TYPE_INAPP = "inapp"; public static final String ITEM_TYPE_SUBS = "subs"; // some fields on the getSkuDetails response bundle public static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; public static final String GET_SKU_DETAILS_ITEM_TYPE_LIST = "ITEM_TYPE_LIST"; /** * Creates an instance. After creation, it will not yet be ready to use. You must perform * setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not * block and is safe to call from a UI thread. * * @param ctx Your application or Activity context. Needed to bind to the in-app billing service. * @param base64PublicKey Your application's public key, encoded in base64. * This is used for verification of purchase signatures. You can find your app's base64-encoded * public key in your application's page on Google Play Developer Console. Note that this * is NOT your "developer public key". */ public IabHelper(Context ctx, String base64PublicKey) { mContext = ctx.getApplicationContext(); mSignatureBase64 = base64PublicKey; logDebug("IAB helper created."); } /** * Enables or disable debug logging through LogCat. */ public void enableDebugLogging(boolean enable, String tag) { checkNotDisposed(); mDebugLog = enable; mDebugTag = tag; } public void enableDebugLogging(boolean enable) { checkNotDisposed(); mDebugLog = enable; } /** * Callback for setup process. This listener's {@link #onIabSetupFinished} method is called * when the setup process is complete. */ public interface OnIabSetupFinishedListener { /** * Called to notify that setup is complete. * * @param result The result of the setup process. */ public void onIabSetupFinished(IabResult result); } /** * Starts the setup process. This will start up the setup process asynchronously. * You will be notified through the listener when the setup process is complete. * This method is safe to call from a UI thread. * * @param listener The listener to notify when the setup process is complete. */ public void startSetup(final OnIabSetupFinishedListener listener) { // If already set up, can't do it again. checkNotDisposed(); if (mSetupDone) throw new IllegalStateException("IAB helper is already set up."); // Connection to IAB service logDebug("Starting in-app billing setup."); mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { logDebug("Billing service disconnected."); mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { if (mDisposed) return; logDebug("Billing service connected."); mService = IInAppBillingService.Stub.asInterface(service); String packageName = mContext.getPackageName(); try { logDebug("Checking for in-app billing 3 support."); // check for in-app billing v3 support int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP); if (response != BILLING_RESPONSE_RESULT_OK) { if (listener != null) listener.onIabSetupFinished(new IabResult(response, "Error checking for billing v3 support.")); // if in-app purchases aren't supported, neither are subscriptions. mSubscriptionsSupported = false; return; } logDebug("In-app billing version 3 supported for " + packageName); // check for v3 subscriptions support response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Subscriptions AVAILABLE."); mSubscriptionsSupported = true; } else { logDebug("Subscriptions NOT AVAILABLE. Response: " + response); } mSetupDone = true; } catch (RemoteException e) { if (listener != null) { listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION, "RemoteException while setting up in-app billing.")); } e.printStackTrace(); return; } if (listener != null) { listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful.")); } } }; Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) { // service available to handle that Intent mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); } else { // no service available to handle that Intent if (listener != null) { listener.onIabSetupFinished( new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device.")); } } } /** * Dispose of object, releasing resources. It's very important to call this * method when you are done with this object. It will release any resources * used by it such as service connections. Naturally, once the object is * disposed of, it can't be used again. */ public void dispose() { logDebug("Disposing."); mSetupDone = false; if (mServiceConn != null) { logDebug("Unbinding from service."); if (mContext != null) mContext.unbindService(mServiceConn); } mDisposed = true; mContext = null; mServiceConn = null; mService = null; mPurchaseListener = null; } private void checkNotDisposed() { if (mDisposed) throw new IllegalStateException("IabHelper was disposed of, so it cannot be used."); } /** Returns whether subscriptions are supported. */ public boolean subscriptionsSupported() { checkNotDisposed(); return mSubscriptionsSupported; } /** * Callback that notifies when a purchase is finished. */ public interface OnIabPurchaseFinishedListener { /** * Called to notify that an in-app purchase finished. If the purchase was successful, * then the sku parameter specifies which item was purchased. If the purchase failed, * the sku and extraData parameters may or may not be null, depending on how far the purchase * process went. * * @param result The result of the purchase. * @param info The purchase information (null if purchase failed) */ public void onIabPurchaseFinished(IabResult result, Purchase info); } // The listener registered on launchPurchaseFlow, which we have to call back when // the purchase finishes OnIabPurchaseFinishedListener mPurchaseListener; public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData); } /** * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, * which will involve bringing up the Google Play screen. The calling activity will be paused while * the user interacts with Google Play, and the result will be delivered via the activity's * {@link android.app.Activity#onActivityResult} method, at which point you must call * this object's {@link #handleActivityResult} method to continue the purchase flow. This method * MUST be called from the UI thread of the Activity. * * @param act The calling activity. * @param sku The sku of the item to purchase. * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS) * @param requestCode A request code (to differentiate from other responses -- * as in {@link android.app.Activity#startActivityForResult}). * @param listener The listener to notify when the purchase process finishes * @param extraData Extra data (developer payload), which will be returned with the purchase data * when the purchase completes. This extra data will be permanently bound to that purchase * and will always be returned when the purchase is queried. */ public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { checkNotDisposed(); checkSetupDone("launchPurchaseFlow"); flagStartAsync("launchPurchaseFlow"); IabResult result; if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) { IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available."); flagEndAsync(); if (listener != null) listener.onIabPurchaseFinished(r, null); return; } try { logDebug("Constructing buy intent for " + sku + ", item type: " + itemType); Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData); int response = getResponseCodeFromBundle(buyIntentBundle); if (response != BILLING_RESPONSE_RESULT_OK) { logError("Unable to buy item, Error response: " + getResponseDesc(response)); flagEndAsync(); result = new IabResult(response, "Unable to buy item"); if (listener != null) listener.onIabPurchaseFinished(result, null); return; } PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT); logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode); mRequestCode = requestCode; mPurchaseListener = listener; mPurchasingItemType = itemType; act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } catch (SendIntentException e) { logError("SendIntentException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent."); if (listener != null) listener.onIabPurchaseFinished(result, null); } catch (RemoteException e) { logError("RemoteException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow"); if (listener != null) listener.onIabPurchaseFinished(result, null); } } /** * Handles an activity result that's part of the purchase flow in in-app billing. If you * are calling {@link #launchPurchaseFlow}, then you must call this method from your * Activity's {@link android.app.Activity@onActivityResult} method. This method * MUST be called from the UI thread of the Activity. * * @param requestCode The requestCode as you received it. * @param resultCode The resultCode as you received it. * @param data The data (Intent) as you received it. * @return Returns true if the result was related to a purchase flow and was handled; * false if the result was not related to a purchase, in which case you should * handle it normally. */ public boolean handleActivityResult(int requestCode, int resultCode, Intent data) { IabResult result; if (requestCode != mRequestCode) return false; checkNotDisposed(); checkSetupDone("handleActivityResult"); // end of async purchase operation that started on launchPurchaseFlow flagEndAsync(); if (data == null) { logError("Null data in IAB activity result."); result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } int responseCode = getResponseCodeFromIntent(data); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) { logDebug("Successful resultcode from purchase activity."); logDebug("Purchase data: " + purchaseData); logDebug("Data signature: " + dataSignature); logDebug("Extras: " + data.getExtras()); logDebug("Expected item type: " + mPurchasingItemType); if (purchaseData == null || dataSignature == null) { logError("BUG: either purchaseData or dataSignature is null."); logDebug("Extras: " + data.getExtras().toString()); result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } Purchase purchase = null; try { purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature); String sku = purchase.getSku(); // Verify signature if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) { logError("Purchase signature verification FAILED for sku " + sku); result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase); return true; } logDebug("Purchase signature successfully verified."); } catch (JSONException e) { logError("Failed to parse purchase data."); e.printStackTrace(); result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } if (mPurchaseListener != null) { mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase); } } else if (resultCode == Activity.RESULT_OK) { // result code was OK, but in-app billing response was not OK. logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode)); if (mPurchaseListener != null) { result = new IabResult(responseCode, "Problem purchashing item."); mPurchaseListener.onIabPurchaseFinished(result, null); } } else if (resultCode == Activity.RESULT_CANCELED) { logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } else { logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } return true; } public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException { return queryInventory(querySkuDetails, moreSkus, null); } /** * Queries the inventory. This will query all owned items from the server, as well as * information on additional skus, if specified. This method may block or take long to execute. * Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}. * * @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well * as purchase information. * @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @throws IabException if a problem occurs while refreshing the inventory. */ public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus, List<String> moreSubsSkus) throws IabException { checkNotDisposed(); checkSetupDone("queryInventory"); try { Inventory inv = new Inventory(); int r = queryPurchases(inv, ITEM_TYPE_INAPP); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned items)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of items)."); } } // if subscriptions are supported, then also query for subscriptions if (mSubscriptionsSupported) { r = queryPurchases(inv, ITEM_TYPE_SUBS); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned subscriptions)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions)."); } } } return inv; } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e); } catch (JSONException e) { throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e); } } /** * Listener that notifies when an inventory query operation completes. */ public interface QueryInventoryFinishedListener { /** * Called to notify that an inventory query operation completed. * * @param result The result of the operation. * @param inv The inventory. */ public void onQueryInventoryFinished(IabResult result, Inventory inv); } /** * Asynchronous wrapper for inventory query. This will perform an inventory * query as described in {@link #queryInventory}, but will do so asynchronously * and call back the specified listener upon completion. This method is safe to * call from a UI thread. * * @param querySkuDetails as in {@link #queryInventory} * @param moreSkus as in {@link #queryInventory} * @param listener The listener to notify when the refresh operation completes. */ public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreSkus, final QueryInventoryFinishedListener listener) { final Handler handler = new Handler(); checkNotDisposed(); checkSetupDone("queryInventory"); flagStartAsync("refresh inventory"); (new Thread(new Runnable() { public void run() { IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful."); Inventory inv = null; try { inv = queryInventory(querySkuDetails, moreSkus); } catch (IabException ex) { result = ex.getResult(); } flagEndAsync(); final IabResult result_f = result; final Inventory inv_f = inv; if (!mDisposed && listener != null) { handler.post(new Runnable() { public void run() { listener.onQueryInventoryFinished(result_f, inv_f); } }); } } })).start(); } public void queryInventoryAsync(QueryInventoryFinishedListener listener) { queryInventoryAsync(true, null, listener); } public void queryInventoryAsync(boolean querySkuDetails, QueryInventoryFinishedListener listener) { queryInventoryAsync(querySkuDetails, null, listener); } /** * Consumes a given in-app product. Consuming can only be done on an item * that's owned, and as a result of consumption, the user will no longer own it. * This method may block or take long to return. Do not call from the UI thread. * For that, see {@link #consumeAsync}. * * @param itemInfo The PurchaseInfo that represents the item to consume. * @throws IabException if there is a problem during consumption. */ void consume(Purchase itemInfo) throws IabException { checkNotDisposed(); checkSetupDone("consume"); if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) { throw new IabException(IABHELPER_INVALID_CONSUMPTION, "Items of type '" + itemInfo.mItemType + "' can't be consumed."); } try { String token = itemInfo.getToken(); String sku = itemInfo.getSku(); if (token == null || token.equals("")) { logError("Can't consume "+ sku + ". No token."); throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: " + sku + " " + itemInfo); } logDebug("Consuming sku: " + sku + ", token: " + token); int response = mService.consumePurchase(3, mContext.getPackageName(), token); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Successfully consumed sku: " + sku); } else { logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response)); throw new IabException(response, "Error consuming sku " + sku); } } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while consuming. PurchaseInfo: " + itemInfo, e); } } /** * Callback that notifies when a consumption operation finishes. */ public interface OnConsumeFinishedListener { /** * Called to notify that a consumption has finished. * * @param purchase The purchase that was (or was to be) consumed. * @param result The result of the consumption operation. */ public void onConsumeFinished(Purchase purchase, IabResult result); } /** * Callback that notifies when a multi-item consumption operation finishes. */ public interface OnConsumeMultiFinishedListener { /** * Called to notify that a consumption of multiple items has finished. * * @param purchases The purchases that were (or were to be) consumed. * @param results The results of each consumption operation, corresponding to each * sku. */ public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results); } /** * Asynchronous wrapper to item consumption. Works like {@link #consume}, but * performs the consumption in the background and notifies completion through * the provided listener. This method is safe to call from a UI thread. * * @param purchase The purchase to be consumed. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(Purchase purchase, OnConsumeFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); List<Purchase> purchases = new ArrayList<Purchase>(); purchases.add(purchase); consumeAsyncInternal(purchases, listener, null); } /** * Same as {@link consumeAsync}, but for multiple items at once. * @param purchases The list of PurchaseInfo objects representing the purchases to consume. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); consumeAsyncInternal(purchases, null, listener); } /** * Returns a human-readable description for the given response code. * * @param code The response code * @return A human-readable string explaining the result code. * It also includes the result code numerically. */ public static String getResponseDesc(int code) { String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" + "3:Billing Unavailable/4:Item unavailable/" + "5:Developer Error/6:Error/7:Item Already Owned/" + "8:Item not owned").split("/"); String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" + "-1002:Bad response received/" + "-1003:Purchase signature verification failed/" + "-1004:Send intent failed/" + "-1005:User cancelled/" + "-1006:Unknown purchase response/" + "-1007:Missing token/" + "-1008:Unknown error/" + "-1009:Subscriptions not available/" + "-1010:Invalid consumption attempt").split("/"); if (code <= IABHELPER_ERROR_BASE) { int index = IABHELPER_ERROR_BASE - code; if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index]; else return String.valueOf(code) + ":Unknown IAB Helper Error"; } else if (code < 0 || code >= iab_msgs.length) return String.valueOf(code) + ":Unknown"; else return iab_msgs[code]; } // Checks that setup was done; if not, throws an exception. void checkSetupDone(String operation) { if (!mSetupDone) { logError("Illegal state for operation (" + operation + "): IAB helper is not set up."); throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromBundle(Bundle b) { Object o = b.get(RESPONSE_CODE); if (o == null) { logDebug("Bundle with null response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for bundle response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName()); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromIntent(Intent i) { Object o = i.getExtras().get(RESPONSE_CODE); if (o == null) { logError("Intent with no response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for intent response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName()); } } void flagStartAsync(String operation) { if (mAsyncInProgress) throw new IllegalStateException("Can't start async operation (" + operation + ") because another async operation(" + mAsyncOperation + ") is in progress."); mAsyncOperation = operation; mAsyncInProgress = true; logDebug("Starting async operation: " + operation); } void flagEndAsync() { logDebug("Ending async operation: " + mAsyncOperation); mAsyncOperation = ""; mAsyncInProgress = false; } int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException { // Query purchases logDebug("Querying owned items, item type: " + itemType); logDebug("Package name: " + mContext.getPackageName()); boolean verificationFailed = false; String continueToken = null; do { logDebug("Calling getPurchases with continuation token: " + continueToken); Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken); int response = getResponseCodeFromBundle(ownedItems); logDebug("Owned items response: " + String.valueOf(response)); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getPurchases() failed: " + getResponseDesc(response)); return response; } if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) { logError("Bundle returned from getPurchases() doesn't contain required fields."); return IABHELPER_BAD_RESPONSE; } ArrayList<String> ownedSkus = ownedItems.getStringArrayList( RESPONSE_INAPP_ITEM_LIST); ArrayList<String> purchaseDataList = ownedItems.getStringArrayList( RESPONSE_INAPP_PURCHASE_DATA_LIST); ArrayList<String> signatureList = ownedItems.getStringArrayList( RESPONSE_INAPP_SIGNATURE_LIST); for (int i = 0; i < purchaseDataList.size(); ++i) { String purchaseData = purchaseDataList.get(i); String signature = signatureList.get(i); String sku = ownedSkus.get(i); if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) { logDebug("Sku is owned: " + sku); Purchase purchase = new Purchase(itemType, purchaseData, signature); if (TextUtils.isEmpty(purchase.getToken())) { logWarn("BUG: empty/null token!"); logDebug("Purchase data: " + purchaseData); } // Record ownership and token inv.addPurchase(purchase); } else { logWarn("Purchase signature verification **FAILED**. Not adding item."); logDebug(" Purchase data: " + purchaseData); logDebug(" Signature: " + signature); verificationFailed = true; } } continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN); logDebug("Continuation token: " + continueToken); } while (!TextUtils.isEmpty(continueToken)); return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK; } int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus) throws RemoteException, JSONException { logDebug("Querying SKU details."); ArrayList<String> skuList = new ArrayList<String>(); skuList.addAll(inv.getAllOwnedSkus(itemType)); if (moreSkus != null) { for (String sku : moreSkus) { if (!skuList.contains(sku)) { skuList.add(sku); } } } if (skuList.size() == 0) { logDebug("queryPrices: nothing to do because there are no SKUs."); return BILLING_RESPONSE_RESULT_OK; } Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus); if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) { int response = getResponseCodeFromBundle(skuDetails); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getSkuDetails() failed: " + getResponseDesc(response)); return response; } else { logError("getSkuDetails() returned a bundle with neither an error nor a detail list."); return IABHELPER_BAD_RESPONSE; } } ArrayList<String> responseList = skuDetails.getStringArrayList( RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { SkuDetails d = new SkuDetails(itemType, thisResponse); logDebug("Got sku details: " + d); inv.addSkuDetails(d); } return BILLING_RESPONSE_RESULT_OK; } void consumeAsyncInternal(final List<Purchase> purchases, final OnConsumeFinishedListener singleListener, final OnConsumeMultiFinishedListener multiListener) { final Handler handler = new Handler(); flagStartAsync("consume"); (new Thread(new Runnable() { public void run() { final List<IabResult> results = new ArrayList<IabResult>(); for (Purchase purchase : purchases) { try { consume(purchase); results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku())); } catch (IabException ex) { results.add(ex.getResult()); } } flagEndAsync(); if (!mDisposed && singleListener != null) { handler.post(new Runnable() { public void run() { singleListener.onConsumeFinished(purchases.get(0), results.get(0)); } }); } if (!mDisposed && multiListener != null) { handler.post(new Runnable() { public void run() { multiListener.onConsumeMultiFinished(purchases, results); } }); } } })).start(); } void logDebug(String msg) { if (mDebugLog) Log.d(mDebugTag, msg); } void logError(String msg) { Log.e(mDebugTag, "In-app billing error: " + msg); } void logWarn(String msg) { Log.w(mDebugTag, "In-app billing warning: " + msg); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/IabHelper.java
Java
art
45,273
/* Copyright (c) 2012 Google Inc. * * 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 net.cardgame.oraclecard.billingutils; /** * Represents the result of an in-app billing operation. * A result is composed of a response code (an integer) and possibly a * message (String). You can get those by calling * {@link #getResponse} and {@link #getMessage()}, respectively. You * can also inquire whether a result is a success or a failure by * calling {@link #isSuccess()} and {@link #isFailure()}. */ public class IabResult { int mResponse; String mMessage; public IabResult(int response, String message) { mResponse = response; if (message == null || message.trim().length() == 0) { mMessage = IabHelper.getResponseDesc(response); } else { mMessage = message + " (response: " + IabHelper.getResponseDesc(response) + ")"; } } public int getResponse() { return mResponse; } public String getMessage() { return mMessage; } public boolean isSuccess() { return mResponse == IabHelper.BILLING_RESPONSE_RESULT_OK; } public boolean isFailure() { return !isSuccess(); } public String toString() { return "IabResult: " + getMessage(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/IabResult.java
Java
art
1,799
/* Copyright (c) 2012 Google Inc. * * 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 net.cardgame.oraclecard.billingutils; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app product's listing details. */ public class SkuDetails { String mItemType; String mSku; String mType; String mPrice; String mTitle; String mDescription; String mJson; public SkuDetails(String jsonSkuDetails) throws JSONException { this(IabHelper.ITEM_TYPE_INAPP, jsonSkuDetails); } public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException { mItemType = itemType; mJson = jsonSkuDetails; JSONObject o = new JSONObject(mJson); mSku = o.optString("productId"); mType = o.optString("type"); mPrice = o.optString("price"); mTitle = o.optString("title"); mDescription = o.optString("description"); } public String getSku() { return mSku; } public String getType() { return mType; } public String getPrice() { return mPrice; } public String getTitle() { return mTitle; } public String getDescription() { return mDescription; } @Override public String toString() { return "SkuDetails:" + mJson; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/billingutils/SkuDetails.java
Java
art
1,783
package net.cardgame.oraclecard.service; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Type; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; import jp.jma.oraclecard.R; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.FileUtils; import net.cardgame.orcalecard.utils.Utils; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ServiceDownload extends IntentService implements ServiceDownloadListener { public final static String KEY_PATH_SERVER = "path_server"; public final static String KEY_DECK_ID = "deckBeanId"; public final static String KEY_POSITION = "Position"; public final static String KEY_PERCENT = "percent download"; public final static String KEY_PATH_SAVE = "path save"; public final static String KEY_STATUS = "status download"; public final static String KEY_MESSAGE_FULL_MEMORY = "full_memory"; private static DownloadUnzipObject downloadObject1; private static DownloadUnzipObject downloadObject2; private static boolean cancel = false; public ServiceDownload(String name) { super(name); // TODO Auto-generated constructor stub } public ServiceDownload() { super("ServiceDownload"); } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub // Get data Bundle bundle = intent.getExtras(); cancel = false; if (bundle.containsKey("cancel")) { cancel = true; return; } String patch = bundle.getString(KEY_PATH_SERVER); int deckId = bundle.getInt(KEY_DECK_ID); int position = bundle.getInt(KEY_POSITION); String patchSave = bundle.getString(KEY_PATH_SAVE); DownloadUnzipObject object = new DownloadUnzipObject(deckId, position, patch, patchSave); boolean excute = false; if (downloadObject1 == null) { if (downloadObject2 == null || (downloadObject2 != null && object.getDeckId() != downloadObject2 .getDeckId())) { downloadObject1 = object; excute = true; } } else if (downloadObject2 == null && downloadObject1.getDeckId() != object.getDeckId()) { downloadObject2 = object; excute = true; } if (excute) { // excute download and unzip file DownloadFileAndUnzip ayncTask = new DownloadFileAndUnzip(this); ayncTask.execute(object); } } /* This task implement Download Deck bean from server */ class DownloadFileAndUnzip extends AsyncTask<DownloadUnzipObject, Void, DownloadUnzipObject> { /** * Downloading file in background thread * */ private final static int CONNECT_TIMEOUT = 15 * 1000; private final static int READ_TIMEOUT = 30 * 1000; private Context mContext; FileUtils fileUtils; DownloadFileAndUnzip(Context context) { mContext = context; } @Override protected DownloadUnzipObject doInBackground( DownloadUnzipObject... progress) { DownloadUnzipObject downloadObject = progress[0]; long downloaded = 0; try { File folder = new File( ConstantValue.getPatchCardData(ServiceDownload.this)); if (!folder.exists()) { folder.mkdirs(); } File file = new File(downloadObject.getPathSaveFile()); URL url = new URL(downloadObject.getUrlDownload()); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setReadTimeout(READ_TIMEOUT); connection.setConnectTimeout(CONNECT_TIMEOUT); if (file.exists()) { downloaded = (int) file.length(); } long fileLength = 0; if (downloaded > 0) { fileLength = connection.getContentLength(); if (downloaded >= fileLength) { downloadObject.setPercent(50); // perform unzip file FileUtils fileUtils = new FileUtils(); fileUtils.registryUnzipListener(ServiceDownload.this); if (fileUtils.unzipFile(downloadObject)) downloadObject.setFinished(); return downloadObject; } else { connection.disconnect(); url = new URL(downloadObject.getUrlDownload()); connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(READ_TIMEOUT); connection.setConnectTimeout(CONNECT_TIMEOUT); } } connection.setRequestProperty("Range", "bytes=" + downloaded + "-"); connection.setDoOutput(true); BufferedInputStream in = new BufferedInputStream( connection.getInputStream()); FileOutputStream fos = downloaded == 0 ? new FileOutputStream( file) : new FileOutputStream( downloadObject.getPathSaveFile(), true); BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); byte[] data = new byte[1024]; long lenghtOfFile = connection.getContentLength() + downloaded; if (!FileUtils.availableDownload(lenghtOfFile)) { // Bộ nhớ không đủ, không cho phép download String message1 = getResources().getString( R.string.freespace_unvailable1); String message2 = getResources().getString( R.string.freespace_unvailable2); String message = message1 + 3 * lenghtOfFile / (1024 * 1024) + message2; // send broadcast receiver Intent intent = new Intent(ConstantValue.ACTION_DOWNLOAD); intent.putExtra(KEY_MESSAGE_FULL_MEMORY, message); LocalBroadcastManager.getInstance(ServiceDownload.this) .sendBroadcast(intent); return downloadObject; } int count; int percent = 0; while ((count = in.read(data, 0, 1024)) != -1) { if (cancel) return downloadObject; downloaded += count; float result = (float) downloaded / (float) lenghtOfFile * 100; result = result / 2; if (result - percent >= 1) { downloadObject.setPercent((int) result); // send progress percentage to broadcast Intent intent = new Intent( ConstantValue.ACTION_DOWNLOAD); intent.putExtra(KEY_DECK_ID, downloadObject.getDeckId()); intent.putExtra(KEY_POSITION, downloadObject.getPosition()); intent.putExtra(KEY_PERCENT, downloadObject.getPercent()); LocalBroadcastManager.getInstance(ServiceDownload.this) .sendBroadcast(intent); // publishProgress(downloadObject); percent = (int) result; } bout.write(data, 0, count); } bout.flush(); bout.close(); in.close(); connection.disconnect(); } catch (Exception e) { Log.e("Error: ", e.toString()); return downloadObject; } downloadObject.setPercent(50); // perform unzip file fileUtils = new FileUtils(); fileUtils.registryUnzipListener(ServiceDownload.this); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub if (cancel) fileUtils.stopUnzip(); } }, 1000, 1000); if (fileUtils.unzipFile(downloadObject)) downloadObject.setFinished(); timer.cancel(); return downloadObject; } @Override protected void onPostExecute(DownloadUnzipObject result) { // TODO Auto-generated method stub super.onPostExecute(result); if (downloadObject1 != null && result.getDeckId() == downloadObject1.getDeckId()) { downloadObject1 = null; } else { downloadObject2 = null; } // send to broadcast receiver Intent intent = new Intent(ConstantValue.ACTION_DOWNLOAD); intent.putExtra(KEY_DECK_ID, result.getDeckId()); intent.putExtra(KEY_POSITION, result.getPosition()); intent.putExtra(KEY_PERCENT, result.getPercent()); intent.putExtra(KEY_STATUS, result.isFinished()); LocalBroadcastManager.getInstance(ServiceDownload.this) .sendBroadcast(intent); saveStatus(result); } void saveStatus(DownloadUnzipObject object) { SecurePreferences appPreferences = new SecurePreferences(mContext, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); String listSaved = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); ArrayList<DeckBean> listDeckBean = gson.fromJson(listSaved, listOfDeckBean); for (DeckBean deckBean : listDeckBean) { if (deckBean.deckId == object.getDeckId()) { deckBean.percentDownloaded = object.isFinished() ? -2 : object.getPercent(); if (!deckBean.isFree) { deckBean.isUnlock = true; } ArrayList<DeckBean> listSave = checkUnlockSpecial(listDeckBean); String save = gson.toJson(listSave, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); return; } } } ArrayList<DeckBean> checkUnlockSpecial(ArrayList<DeckBean> listDeckBean) { int total = 0; for (DeckBean deckbean : listDeckBean) { if (deckbean.percentDownloaded == -2) total++; if (total >= 2) return unlockSpecialAndRandom(listDeckBean); } return listDeckBean; } ArrayList<DeckBean> unlockSpecialAndRandom( ArrayList<DeckBean> listDeckBean) { for (DeckBean deckbean : listDeckBean) { if (deckbean.deckId == 999 || deckbean.deckId == 998) { deckbean.isUnlock = true; } } return listDeckBean; } } @Override public void onUpdateProgressListener(int percent, int position, int deckId) { // TODO Auto-generated method stub Intent intent = new Intent(ConstantValue.ACTION_DOWNLOAD); // Add data intent.putExtra(KEY_DECK_ID, deckId); intent.putExtra(KEY_POSITION, position); intent.putExtra(KEY_PERCENT, percent); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } @Override public void onDownloadFailListener(DownloadUnzipObject object, String message) { // TODO Auto-generated method stub } @Override public void onFinishedListener(DownloadUnzipObject object) { // TODO Auto-generated method stub } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/service/ServiceDownload.java
Java
art
10,742
package net.cardgame.oraclecard.service; public class DownloadUnzipObject { @Override public String toString() { return "DownloadUnzipObject [deckId=" + deckId + ", position=" + position + ", percent=" + percent + ", urlDownload=" + urlDownload + ", finished=" + finished + ", pathSaveFile=" + pathSaveFile + ", strId=" + strId + "]"; } private int deckId; private int position; private int percent; private String urlDownload; private boolean finished = false; private String pathSaveFile; private String strId; public String getStringId() { return strId; } public String getPathSaveFile() { return pathSaveFile; } public void setPathSaveFile(String pathSaveFile) { this.pathSaveFile = pathSaveFile; } public int getDeckId() { return deckId; } public void setDeckId(int deckId) { this.deckId = deckId; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public int getPercent() { return percent; } public void setPercent(int percent) { this.percent = percent; } public String getUrlDownload() { return urlDownload; } public void setUrlDownload(String urlDownload) { this.urlDownload = urlDownload; } public void setFinished() { this.finished = true; } public boolean isFinished() { return finished; } public DownloadUnzipObject(int deckId, int position, String url, String pathSave) { this.deckId = deckId; this.position = position; this.urlDownload = url; this.pathSaveFile = pathSave; this.percent = 0; strId = deckId < 10 ? "0" + deckId : "" + deckId; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/service/DownloadUnzipObject.java
Java
art
1,716
package net.cardgame.oraclecard.service; public interface ServiceDownloadListener { void onUpdateProgressListener(int percent, int position, int deckId); void onDownloadFailListener(DownloadUnzipObject object, String message); void onFinishedListener(DownloadUnzipObject object); }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/service/ServiceDownloadListener.java
Java
art
297
package net.cardgame.oraclecard.service; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Date; import net.cardgame.orcalecard.bean.DeckBean; import net.cardgame.orcalecard.pref.SecurePreferences; import net.cardgame.orcalecard.utils.ConstantValue; import net.cardgame.orcalecard.utils.NetworkUtils; import net.cardgame.orcalecard.utils.XmlParser; import android.app.IntentService; import android.content.Intent; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class ServiceUpdateFileConfig extends IntentService { public ServiceUpdateFileConfig(String name) { super(name); // TODO Auto-generated constructor stub } public ServiceUpdateFileConfig() { super("ServiceUpdateFileConfig"); } @Override protected void onHandleIntent(Intent intent) { // TODO Auto-generated method stub ArrayList<DeckBean> listDeckBean = new ArrayList<DeckBean>(); ArrayList<DeckBean> listDeckBeanSaved = new ArrayList<DeckBean>(); String deckXml = "null"; NetworkUtils networkUtils = new NetworkUtils(); if (NetworkUtils.isNetworkConnected(this)) { deckXml = networkUtils.getStringFromUrl(ConstantValue.BASE_URL + ConstantValue.LIST_DECK_SUB_URL); } else return; listDeckBean = new XmlParser().getDeckBeans(deckXml); // get sharedreference Type listOfDeckBean = new TypeToken<ArrayList<DeckBean>>() { }.getType(); SecurePreferences appPreferences = new SecurePreferences(this, ConstantValue.APP_PREFERENCES, ConstantValue.PREFERENCES_SECRET_KEY, true); Gson gson = new Gson(); String config = appPreferences .getString(ConstantValue.CONFIG_DECKBEAN_KEY); listDeckBeanSaved = gson.fromJson(config, listOfDeckBean); if (listDeckBean == null || listDeckBean.isEmpty() || listDeckBeanSaved == null || listDeckBeanSaved.isEmpty()) return; // test // DeckBean deck = listDeckBean.get(16); // DeckBean deck1 = new DeckBean(); // deck1.deckId = 19; // deck1.deckName = "test"; // deck1.isFree = true; // deck1.releaseDate = deck.releaseDate; // deck1.inAppPurchaseId = "12131121"; // deck1.deckPrice = 132; // deck1.cardNumber = 44; // deck1.pathServerDownload = deck.pathServerDownload; // DeckBean deck2 = new DeckBean(); // deck2.deckId = 20; // deck2.deckName = "test2"; // deck2.isFree = true; // deck2.releaseDate = deck.releaseDate; // deck2.inAppPurchaseId = "12131121"; // deck2.deckPrice = 132; // deck2.cardNumber = 44; // deck2.pathServerDownload = deck.pathServerDownload; // listDeckBean.add(deck1); // listDeckBean.add(deck2); // listDeckBean.remove(10); // listDeckBean.add(deck1); // // update list deck bean for (DeckBean deckBean : listDeckBean) { boolean add = true; for (DeckBean dec : listDeckBeanSaved) { if (dec.deckId == deckBean.deckId) { add = false; dec.deckName = deckBean.deckName; if (deckBean.isFree == false && dec.isFree == true) { dec.isUnlock = false; } dec.isFree = deckBean.isFree; dec.releaseDate = deckBean.releaseDate; dec.inAppPurchaseId = deckBean.inAppPurchaseId; dec.deckPrice = deckBean.deckPrice; dec.cardNumber = deckBean.cardNumber; dec.pathServerDownload = deckBean.pathServerDownload; break; } } if (add) { listDeckBeanSaved.add(deckBean); } } // remove deck bean if server has removed int size = listDeckBeanSaved.size(); for (int i = 0; i < size; i++) { DeckBean deckBean = listDeckBeanSaved.get(i); boolean remove = true; for (DeckBean deckBean2 : listDeckBean) { if (deckBean.deckId == deckBean2.deckId) { remove = false; break; } } if (remove) { listDeckBeanSaved.remove(i); size--; } } // put shared reference String save = gson.toJson(listDeckBeanSaved, listOfDeckBean); appPreferences.put(ConstantValue.CONFIG_DECKBEAN_KEY, save); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/service/ServiceUpdateFileConfig.java
Java
art
4,029
package net.cardgame.oraclecard.common; public interface SavedListener { public void onSave(boolean save); }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/SavedListener.java
Java
art
118
package net.cardgame.oraclecard.common; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; public class Helper { public static void getListViewSize(ListView myListView) { ListAdapter myListAdapter = myListView.getAdapter(); if (myListAdapter == null) { // do nothing return null return; } // set listAdapter in loop for getting final size int totalHeight = 0; for (int size = 0; size < myListAdapter.getCount(); size++) { View listItem = myListAdapter.getView(size, null, myListView); listItem.measure(0, 0); totalHeight += listItem.getMeasuredHeight(); } // setting listview item in adapter ViewGroup.LayoutParams params = myListView.getLayoutParams(); params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1)); myListView.setLayoutParams(params); // print height of adapter on log Log.i("height of listItem:", String.valueOf(totalHeight)); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/Helper.java
Java
art
1,061
package net.cardgame.oraclecard.common; import net.cardgame.orcalecard.bean.HistoryBean; public interface SelectedHistoryListener { public void onSelectedItemListener(int id); public void onFinished(); public void onDeleteHistory(HistoryBean history); }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/SelectedHistoryListener.java
Java
art
272
package net.cardgame.oraclecard.common; import jp.jma.oraclecard.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; public class ImageClickable extends ImageView { private String path; boolean loadding = false; public ImageClickable(Context context) { super(context); } public ImageClickable(Context context, AttributeSet attrs) { super(context, attrs); } public ImageClickable(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private Handler mHandler = new Handler() { public void handleMessage(android.os.Message msg) { if (msg.obj == null) { ImageClickable.this .setImageResource(R.drawable.image_not_found); return; } ImageClickable.this.setImageDrawable((Drawable) msg.obj); loadding = false; }; }; public void loadImage(String path) { this.path = path; if (path != null) { new ThreadLoadImage(mHandler, path, this, 1, true).start(); } } public void setPath(String path) { this.path = path; } private void reLoadImage() { if (path != null) { new ThreadLoadImage(mHandler, path, this, 1, true).start(); } } @Override public boolean onTouchEvent(MotionEvent event) { if (isEnabled() && isClickable()) switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: setColorFilter(Color.parseColor("#ee0467FB"), PorterDuff.Mode.MULTIPLY); break; case MotionEvent.ACTION_UP: setColorFilter(null); break; case MotionEvent.ACTION_CANCEL: setColorFilter(null); break; default: break; } return super.onTouchEvent(event); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub BitmapDrawable drawable = (BitmapDrawable) getDrawable(); if (drawable != null) { Bitmap bitmap = drawable.getBitmap(); if (!bitmap.isRecycled()) { super.onDraw(canvas); } else { if (!loadding) { loadding = true; reLoadImage(); } } } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/ImageClickable.java
Java
art
2,420
/******************************************************************************* * Copyright (c) 2013 Chris Banes. * * 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 net.cardgame.oraclecard.common; import java.io.InputStream; import java.lang.ref.WeakReference; import jp.jma.oraclecard.MyApplication; import net.cardgame.orcalecard.utils.FileUtils; import uk.co.senab.bitmapcache.BitmapLruCache; import uk.co.senab.bitmapcache.CacheableBitmapDrawable; import uk.co.senab.bitmapcache.CacheableImageView; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.util.AttributeSet; import android.widget.ImageView; /** * Simple extension of CacheableImageView which allows downloading of Images of * the Internet. * * This code isn't production quality, but works well enough for this sample.s * * @author Chris Banes */ public class BitmapCacheableImageView extends CacheableImageView { /** * This task simply fetches an Bitmap from the specified URL and wraps it in * a wrapper. This implementation is NOT 'best practice' or production ready * code. */ private static class ImageUrlAsyncTask extends AsyncTask<String, Void, CacheableBitmapDrawable> { private final BitmapLruCache mCache; private final WeakReference<ImageView> mImageViewRef; private final BitmapFactory.Options mDecodeOpts; ImageUrlAsyncTask(ImageView imageView, BitmapLruCache cache, BitmapFactory.Options decodeOpts) { mCache = cache; mImageViewRef = new WeakReference<ImageView>(imageView); mDecodeOpts = decodeOpts; } @Override protected CacheableBitmapDrawable doInBackground(String... params) { // Return early if the ImageView has disappeared. if (null == mImageViewRef.get()) { return null; } final String sourcePath = params[0]; // Now we're not on the main thread we can check all caches CacheableBitmapDrawable result = mCache.getFromDiskCache(params[0], mDecodeOpts); try { if (null == result) { InputStream is = FileUtils.decrytToInputStream(sourcePath); // Add to cache result = mCache.put(sourcePath, is, mDecodeOpts, true); } } catch (Exception e) { // TODO: handle exception } return result; } @Override protected void onPostExecute(CacheableBitmapDrawable result) { super.onPostExecute(result); ImageView iv = mImageViewRef.get(); if (null != iv) { iv.setImageDrawable(result); } } } private BitmapLruCache mCache; private ImageUrlAsyncTask mCurrentTask; float rotate = 0; Context context; public BitmapCacheableImageView(Context context, AttributeSet attrs) { super(context, attrs); mCache = MyApplication.getInstance().getBitmapCache(); this.context = context; } public boolean loadImage(String sourcePath, Context context, float rotate) { this.rotate = rotate; // First check whether there's already a task running, if so cancel it if (null != mCurrentTask) { mCurrentTask.cancel(true); } // Check to see if the memory cache already has the bitmap. We can // safely do // this on the main thread. BitmapDrawable wrapper = mCache.getFromMemoryCache(sourcePath); BitmapFactory.Options option = new BitmapFactory.Options(); option.outHeight = this.getHeight(); option.outWidth = this.getWidth(); if (null != wrapper) { // The cache has it, so just display it setImageDrawable(wrapper); return true; } else { // Memory Cache doesn't have the URL, do threaded request... setImageDrawable(null); mCurrentTask = new ImageUrlAsyncTask(this, mCache, option); mCurrentTask.execute(sourcePath); // ThreadLoadImage thread = new ThreadLoadImage(sourcePath, option, // mCache); // thread.start(); return false; } } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/BitmapCacheableImageView.java
Java
art
4,432
package net.cardgame.oraclecard.common; import java.io.InputStream; import jp.jma.oraclecard.MyApplication; import net.cardgame.orcalecard.utils.FileUtils; import uk.co.senab.bitmapcache.BitmapLruCache; import uk.co.senab.bitmapcache.CacheableBitmapDrawable; import android.content.Context; import android.graphics.BitmapFactory; import android.graphics.BitmapFactory.Options; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.os.Message; import android.widget.ImageView; public class ThreadLoadImage extends Thread { String patch; BitmapFactory.Options option; int what; Handler handler; private BitmapLruCache mCache; Boolean cacheOnMemory; public ThreadLoadImage(Handler handler, String patch, ImageView imageview, int what, boolean cacheOnMemory) { // TODO Auto-generated constructor stubt this.cacheOnMemory = cacheOnMemory; mCache = MyApplication.getInstance().getBitmapCache(); this.handler = handler; this.what = what; this.patch = patch; this.option = new Options(); if (imageview != null) { option.outHeight = imageview.getHeight(); option.outWidth = imageview.getWidth(); } } public ThreadLoadImage(Context context, Handler handler, String patch, ImageView imageview, int what) { // TODO Auto-generated constructor stubt this.cacheOnMemory = true; mCache = MyApplication.getInstance().getBitmapCache(); this.handler = handler; this.what = what; this.patch = patch; this.option = new Options(); if (imageview != null) { option.outHeight = imageview.getHeight(); option.outWidth = imageview.getWidth(); } imageview = null; } @Override public void run() { // TODO Auto-generated method stub super.run(); BitmapDrawable wrapper = mCache.getFromMemoryCache(patch); if (wrapper != null && !wrapper.getBitmap().isRecycled()) { Message msg = handler.obtainMessage(what); msg.obj = wrapper; wrapper = null; msg.what = what; handler.sendMessage(msg); return; } CacheableBitmapDrawable result = mCache.getFromDiskCache(patch, option); if (null == result || result.getBitmap().isRecycled()) { try { InputStream is = FileUtils.decrytToInputStream(patch); // Add to mCache result = mCache.put(patch, is, option, cacheOnMemory); } catch (Exception e) { } } Message msg = handler.obtainMessage(what); msg.obj = result; result = null; msg.what = what; handler.sendMessage(msg); } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/ThreadLoadImage.java
Java
art
2,541
package net.cardgame.oraclecard.common; import net.cardgame.orcalecard.bean.NewsBean; public interface onDeleteNewsBeanListener { public void onDeleted(NewsBean newsBean); }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/onDeleteNewsBeanListener.java
Java
art
184
/* * Copyright (C) 2010 The Android Open Source Project * * 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 net.cardgame.oraclecard.common; import jp.jma.oraclecard.R; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.ViewConfiguration; import android.widget.CompoundButton; /** * A MySwitch is a two-state toggle switch widget that can select between two * options. The user may drag the "thumb" back and forth to choose the selected * option, or simply tap to toggle as if it were a checkbox. The * {@link #setText(CharSequence) text} property controls the text displayed in * the label for the switch, whereas the {@link #setTextOff(CharSequence) off} * and {@link #setTextOn(CharSequence) on} text controls the text on the thumb. * Similarly, the {@link #setTextAppearance(android.content.Context, int) * textAppearance} and the related setTypeface() methods control the typeface * and style of label text, whereas the * {@link #setSwitchTextAppearance(android.content.Context, int) * switchTextAppearance} and the related seSwitchTypeface() methods control that * of the thumb. * */ public class MySwitch extends CompoundButton { private static final int TOUCH_MODE_IDLE = 0; private static final int TOUCH_MODE_DOWN = 1; private static final int TOUCH_MODE_DRAGGING = 2; private static final String TAG = "MySwitch"; // Enum for the "typeface" XML parameter. private static final int SANS = 1; private static final int SERIF = 2; private static final int MONOSPACE = 3; private static final int VERTICAL = 0; private static final int HORIZONTAL = 1; private int mOrientation = HORIZONTAL; private OnChangeAttemptListener mOnChangeAttemptListener; private boolean mPushStyle; private boolean mTextOnThumb; private int mThumbExtraMovement; private Drawable mLeftBackground; private Drawable mRightBackground; private Drawable mMaskDrawable; private Drawable mThumbDrawable; private Drawable mTrackDrawable; private int mThumbTextPadding; private int mTrackTextPadding; private int mSwitchMinWidth; private int mSwitchMinHeight; private int mSwitchPadding; private CharSequence mTextOn; private CharSequence mTextOff; private Drawable mDrawableOn; private Drawable mDrawableOff; private boolean fixed = false; private boolean clickDisabled = false; private boolean onOrOff = true; private Bitmap pushBitmap; private Bitmap maskBitmap; private Bitmap tempBitmap; private Canvas backingLayer; private int mTouchMode; private int mTouchSlop; private float mTouchX; private float mTouchY; private VelocityTracker mVelocityTracker = VelocityTracker.obtain(); private int mMinFlingVelocity; private float mThumbPosition = 0; private int mSwitchWidth; private int mSwitchHeight; private int mThumbWidth; private int mThumbHeight; private int mSwitchLeft; private int mSwitchTop; private int mSwitchRight; private int mSwitchBottom; private TextPaint mTextPaint; private ColorStateList mTextColors; private Layout mOnLayout; private Layout mOffLayout; private Paint xferPaint; private Bitmap leftBitmap, rightBitmap; private final Rect mTrackPaddingRect = new Rect(); private final Rect mThPad = new Rect(); private final Rect canvasClipBounds = new Rect(); private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked }; /** * Construct a new MySwitch with default styling. * * @param context * The Context that will determine this widget's theming. */ public MySwitch(Context context) { this(context, null); } /** * Construct a new MySwitch with default styling, overriding specific style * attributes as requested. * * @param context * The Context that will determine this widget's theming. * @param attrs * Specification of attributes that should deviate from default * styling. */ public MySwitch(Context context, AttributeSet attrs) { this(context, attrs, R.attr.mySwitchStyleAttr); } /** * Construct a new MySwitch with a default style determined by the given * theme attribute, overriding specific style attributes as requested. * * @param context * The Context that will determine this widget's theming. * @param attrs * Specification of attributes that should deviate from the * default styling. * @param defStyle * An attribute ID within the active theme containing a reference * to the default style for this widget. e.g. * android.R.attr.switchStyle. */ public MySwitch(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); Resources res = getResources(); mTextPaint.density = res.getDisplayMetrics().density; mTextPaint.setShadowLayer(0.5f, 1.0f, 1.0f, Color.BLACK); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MySwitch, defStyle, 0); mLeftBackground = a.getDrawable(R.styleable.MySwitch_leftBackground); // if (mLeftBackground == null) { // mLeftBackground = new ColorDrawable(0xFF11BB33); // } mRightBackground = a.getDrawable(R.styleable.MySwitch_rightBackground); // if (mRightBackground == null) { // mRightBackground = new ColorDrawable(0x993322BB); // } mOrientation = a.getInteger(R.styleable.MySwitch_orientation, HORIZONTAL); // Log.d(TAG, "mLeftBackground="+mLeftBackground); // Log.d(TAG, "mRightBackground="+mRightBackground); mThumbDrawable = a.getDrawable(R.styleable.MySwitch_thumb); mTrackDrawable = a.getDrawable(R.styleable.MySwitch_track); mTextOn = a.getText(R.styleable.MySwitch_textOn); mTextOff = a.getText(R.styleable.MySwitch_textOff); mDrawableOn = a.getDrawable(R.styleable.MySwitch_drawableOn); mDrawableOff = a.getDrawable(R.styleable.MySwitch_drawableOff); mPushStyle = a.getBoolean(R.styleable.MySwitch_pushStyle, false); mTextOnThumb = a.getBoolean(R.styleable.MySwitch_textOnThumb, false); mThumbExtraMovement = a.getDimensionPixelSize( R.styleable.MySwitch_thumbExtraMovement, 0); mThumbTextPadding = a.getDimensionPixelSize( R.styleable.MySwitch_thumbTextPadding, 0); mTrackTextPadding = a.getDimensionPixelSize( R.styleable.MySwitch_trackTextPadding, 0); mSwitchMinWidth = a.getDimensionPixelSize( R.styleable.MySwitch_switchMinWidth, 0); mSwitchMinHeight = a.getDimensionPixelSize( R.styleable.MySwitch_switchMinHeight, 0); mSwitchPadding = a.getDimensionPixelSize( R.styleable.MySwitch_switchPadding, 0); mTrackDrawable.getPadding(mTrackPaddingRect); mThumbDrawable.getPadding(mThPad); mMaskDrawable = a.getDrawable(R.styleable.MySwitch_backgroundMask); RuntimeException e = null; if ((mLeftBackground != null) || (mRightBackground != null)) { // if ((mMaskDrawable == null) && (mLeftBackground == null) && // (mRightBackground == null)) { if (mMaskDrawable == null) { e = new IllegalArgumentException( a.getPositionDescription() + " if left/right background is given, then a mask has to be there"); } } if ((mLeftBackground != null) ^ (mRightBackground != null)) { if (mMaskDrawable == null) { e = new IllegalArgumentException( a.getPositionDescription() + " left and right background both should be there. only one is not allowed "); } } if ((mTextOnThumb) && (mPushStyle)) { e = new IllegalArgumentException( a.getPositionDescription() + " Text On Thumb and Push Stype are mutually exclusive. Only one can be present "); } xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // xferPaint.setColor(Color.TRANSPARENT); xferPaint.setXfermode(new PorterDuffXfermode(Mode.DST_IN)); int appearance = a.getResourceId( R.styleable.MySwitch_switchTextAppearanceAttrib, 0); if (appearance != 0) { setSwitchTextAppearance(context, appearance); } a.recycle(); if (e != null) { throw e; } ViewConfiguration config = ViewConfiguration.get(context); mTouchSlop = config.getScaledTouchSlop(); // Log.d(TAG, "mTouchSlop="+mTouchSlop); mMinFlingVelocity = config.getScaledMinimumFlingVelocity(); // Log.d(TAG, "mMinFlingVelocity="+mMinFlingVelocity); // Refresh display with current params refreshDrawableState(); setChecked(isChecked()); this.setClickable(true); // this.setOnClickListener(clickListener); } /** * Sets the switch text color, size, style, hint color, and highlight color * from the specified TextAppearance resource. */ public void setSwitchTextAppearance(Context context, int resid) { TypedArray appearance = context.obtainStyledAttributes(resid, R.styleable.mySwitchTextAppearanceAttrib); ColorStateList colors; int ts; colors = appearance .getColorStateList(R.styleable.mySwitchTextAppearanceAttrib_textColor); if (colors != null) { mTextColors = colors; } else { // If no color set in TextAppearance, default to the view's // textColor mTextColors = getTextColors(); } ts = appearance.getDimensionPixelSize( R.styleable.mySwitchTextAppearanceAttrib_textSize, 0); if (ts != 0) { if (ts != mTextPaint.getTextSize()) { mTextPaint.setTextSize(ts); requestLayout(); } } int typefaceIndex, styleIndex; typefaceIndex = appearance.getInt( R.styleable.mySwitchTextAppearanceAttrib_typeface, -1); styleIndex = appearance.getInt( R.styleable.mySwitchTextAppearanceAttrib_textStyle, -1); setSwitchTypefaceByIndex(typefaceIndex, styleIndex); appearance.recycle(); } private void setSwitchTypefaceByIndex(int typefaceIndex, int styleIndex) { Typeface tf = null; switch (typefaceIndex) { case SANS: tf = Typeface.SANS_SERIF; break; case SERIF: tf = Typeface.SERIF; break; case MONOSPACE: tf = Typeface.MONOSPACE; break; } setSwitchTypeface(tf, styleIndex); } /** * Sets the typeface and style in which the text should be displayed on the * switch, and turns on the fake bold and italic bits in the Paint if the * Typeface that you provided does not have all the bits in the style that * you specified. */ public void setSwitchTypeface(Typeface tf, int style) { if (style > 0) { if (tf == null) { tf = Typeface.defaultFromStyle(style); } else { tf = Typeface.create(tf, style); } setSwitchTypeface(tf); // now compute what (if any) algorithmic styling is needed int typefaceStyle = tf != null ? tf.getStyle() : 0; int need = style & ~typefaceStyle; mTextPaint.setFakeBoldText((need & Typeface.BOLD) != 0); mTextPaint.setTextSkewX((need & Typeface.ITALIC) != 0 ? -0.25f : 0); } else { mTextPaint.setFakeBoldText(false); mTextPaint.setTextSkewX(0); setSwitchTypeface(tf); } } /** * Sets the typeface in which the text should be displayed on the switch. * Note that not all Typeface families actually have bold and italic * variants, so you may need to use * {@link #setSwitchTypeface(Typeface, int)} to get the appearance that you * actually want. * * @attr ref android.R.styleable#TextView_typeface * @attr ref android.R.styleable#TextView_textStyle */ public void setSwitchTypeface(Typeface tf) { if (mTextPaint.getTypeface() != tf) { mTextPaint.setTypeface(tf); requestLayout(); invalidate(); } } /** * Returns the text displayed when the button is in the checked state. */ public CharSequence getTextOn() { return mTextOn; } /** * Sets the text displayed when the button is in the checked state. */ public void setTextOn(CharSequence textOn) { mTextOn = textOn; this.mOnLayout = null; requestLayout(); } /** * Returns the text displayed when the button is not in the checked state. */ public CharSequence getTextOff() { return mTextOff; } /** * Sets the text displayed when the button is not in the checked state. */ public void setTextOff(CharSequence textOff) { mTextOff = textOff; this.mOffLayout = null; requestLayout(); } /** * Interface definition for a callback to be invoked when the switch is in a * fixed state and there was an attempt to change its state either via a * click or drag */ public static interface OnChangeAttemptListener { /** * Called when an attempt was made to change the checked state of the * switch while the switch was in a fixed state. * * @param isChecked * The current state of switch. */ void onChangeAttempted(boolean isChecked); } /** * Register a callback to be invoked when there is an attempt to change the * state of the switch when its in fixated * * @param listener * the callback to call on checked state change */ public void setOnChangeAttemptListener(OnChangeAttemptListener listener) { mOnChangeAttemptListener = listener; } /** * fixates the switch on one of the positions ON or OFF. if the switch is * fixated, then it cannot be switched to the other position * * @param fixed * If true, sets the switch to fixed mode. If false, sets the * switch to switched mode. * @param onOrOff * The switch position to which it will be fixed. If it is true * then the switch is fixed on ON. If it is false then the switch * is fixed on OFF * @Note The position is only fixed from the user interface. It can still be * changed through program by using {@link #setChecked(boolean) * setChecked} */ public void fixate(boolean fixed, boolean onOrOff) { fixate(fixed); this.onOrOff = onOrOff; if (onOrOff) this.setChecked(true); } /** * fixates the switch on one of the positions ON or OFF. if the switch is * fixated, then it cannot be switched to the other position * * @param fixed * if true, sets the switch to fixed mode. if false, sets the * switch to switched mode. */ public void fixate(boolean fixed) { this.fixed = fixed; } /** * returns if the switch is fixed to one of its positions */ public boolean isFixed() { return fixed; } private Layout makeLayout(CharSequence text) { return new StaticLayout(text, mTextPaint, (int) android.util.FloatMath.ceil(Layout.getDesiredWidth(text, mTextPaint)), Layout.Alignment.ALIGN_NORMAL, 1.f, 0, true); } /** * @return true if (x, y) is within the target area of the switch thumb */ private boolean hitThumb(float x, float y) { if (mOrientation == HORIZONTAL) { final int thumbTop = mSwitchTop - mTouchSlop; final int thumbLeft = mSwitchLeft + (int) (mThumbPosition + 0.5f) - mTouchSlop; final int thumbRight = thumbLeft + mThumbWidth + mTouchSlop;// + // mThPad.left // + // mThPad.right final int thumbBottom = mSwitchBottom + mTouchSlop; return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom; } // if (mOrientation == VERTICAL) if (mSwitchHeight > 150) { final int thumbLeft = mSwitchLeft - mTouchSlop; final int thumbTop = mSwitchTop + (int) (mThumbPosition + 0.5f) - mTouchSlop; final int thumbBottom = thumbTop + mThumbHeight + mTouchSlop;// + // mThPad.top // + // mThPad.bottom final int thumbRight = mSwitchRight + mTouchSlop; return x > thumbLeft && x < thumbRight && y > thumbTop && y < thumbBottom; } else { return x > mSwitchLeft && x < mSwitchRight && y > mSwitchTop && y < mSwitchBottom; } } @Override public boolean onTouchEvent(MotionEvent ev) { // if (fixed) { // Log.d(TAG, "the switch position is fixed to " + (onOrOff ? // "On":"Off") + "position."); // return true; // } mVelocityTracker.addMovement(ev); // Log.d(TAG, "onTouchEvent(ev="+ev.toString()+")"); // Log.d(TAG, "mTouchMode="+mTouchMode); final int action = ev.getActionMasked(); switch (action) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); if (isEnabled() && hitThumb(x, y)) { mTouchMode = TOUCH_MODE_DOWN; mTouchX = x; mTouchY = y; } break; } case MotionEvent.ACTION_MOVE: { switch (mTouchMode) { case TOUCH_MODE_IDLE: // Didn't target the thumb, treat normally. break; case TOUCH_MODE_DOWN: { final float x = ev.getX(); final float y = ev.getY(); if (Math.abs(x - mTouchX) > mTouchSlop / 2 || Math.abs(y - mTouchY) > mTouchSlop / 2) { mTouchMode = TOUCH_MODE_DRAGGING; if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(true); } mTouchX = x; mTouchY = y; return true; } break; } case TOUCH_MODE_DRAGGING: { final float x = ev.getX(); final float dx = x - mTouchX; final float y = ev.getY(); final float dy = y - mTouchY; if (mOrientation == HORIZONTAL) { float newPos = Math.max(0, Math.min(mThumbPosition + dx, getThumbScrollRange())); if (newPos != mThumbPosition) { mThumbPosition = newPos; mTouchX = x; invalidate(); } return true; } if (mOrientation == VERTICAL) { float newPos = Math.max(0, Math.min(mThumbPosition + dy, getThumbScrollRange())); if (newPos != mThumbPosition) { mThumbPosition = newPos; mTouchY = y; invalidate(); } return true; } } } break; } case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: { if (mTouchMode == TOUCH_MODE_DRAGGING) { stopDrag(ev); return true; } mTouchMode = TOUCH_MODE_IDLE; mVelocityTracker.clear(); break; } } boolean flag = super.onTouchEvent(ev); // Log.d(TAG, "super.onTouchEvent(ev) returned="+flag); return flag; } /* * OnClickListener clickListener = new OnClickListener() { public void * onClick(View v) { Log.d(TAG, "onClick()"); * animateThumbToCheckedState(isChecked()); } } */ @Override public boolean performClick() { if (!clickDisabled) { // Log.d(TAG, "performClick(). current Value="+isChecked()); if (!fixed) { boolean flag = super.performClick(); // Log.d(TAG, // "after super.performClick(). Value="+isChecked()); return flag; } else { if (this.mOnChangeAttemptListener != null) this.mOnChangeAttemptListener .onChangeAttempted(isChecked()); return false; } } else { return false; } } public void disableClick() { clickDisabled = true; } public void enableClick() { clickDisabled = false; } /* * public void toggleWithAnimation(boolean animate) { toggle(); if (animate) * { animateThumbToCheckedState(isChecked()); } } * * //@Override public boolean isChecked1() { Log.d(TAG, * "isChecked()-mTextOnThumb="+mTextOnThumb); if (mTextOnThumb) { Log.d(TAG, * "returning = "+super.isChecked()); return super.isChecked(); } Log.d(TAG, * "returning="+(!(super.isChecked()))); return !(super.isChecked()); } */ public CharSequence getCurrentText() { if (isChecked()) return mTextOn; return mTextOff; } public CharSequence getText(boolean checkedState) { if (checkedState) return mTextOn; else return mTextOff; } private void cancelSuperTouch(MotionEvent ev) { MotionEvent cancel = MotionEvent.obtain(ev); cancel.setAction(MotionEvent.ACTION_CANCEL); super.onTouchEvent(cancel); cancel.recycle(); } /** * Called from onTouchEvent to end a drag operation. * * @param ev * Event that triggered the end of drag mode - ACTION_UP or * ACTION_CANCEL */ private void stopDrag(MotionEvent ev) { mTouchMode = TOUCH_MODE_IDLE; // Up and not canceled, also checks the switch has not been disabled // during the drag boolean commitChange = ev.getAction() == MotionEvent.ACTION_UP && isEnabled(); // check if the swtich is fixed to a position commitChange = commitChange && (!fixed); // Log.d(TAG,"commitChange="+commitChange); cancelSuperTouch(ev); if (commitChange) { boolean newState; mVelocityTracker.computeCurrentVelocity(1000); if (mOrientation == HORIZONTAL) { float xvel = mVelocityTracker.getXVelocity(); if (Math.abs(xvel) > mMinFlingVelocity) { newState = xvel > 0; } else { newState = getTargetCheckedState(); } } else { float yvel = mVelocityTracker.getYVelocity(); if (Math.abs(yvel) > mMinFlingVelocity) { newState = yvel > 0; } else { newState = getTargetCheckedState(); } } if (mTextOnThumb) animateThumbToCheckedState(newState); else animateThumbToCheckedState(!newState); } else { animateThumbToCheckedState(isChecked()); if (fixed) if (this.mOnChangeAttemptListener != null) this.mOnChangeAttemptListener .onChangeAttempted(isChecked()); } } private void animateThumbToCheckedState(boolean newCheckedState) { // TODO animate! // float targetPos = newCheckedState ? 0 : getThumbScrollRange(); // mThumbPosition = targetPos; setChecked(newCheckedState); } private boolean getTargetCheckedState() { return mThumbPosition >= getThumbScrollRange() / 2; } @Override public void setChecked(boolean checked) { // Log.d(TAG, "setChecked("+checked+")"); boolean lc = checked; if (!mTextOnThumb) { lc = !checked; } super.setChecked(checked); mThumbPosition = lc ? getThumbScrollRange() : 0; invalidate(); } @SuppressLint("WrongCall") protected void onLayout_orig(boolean changed, int left, int top, int right, int bottom) { // Log.d(TAG, "left=" + left + // ",top="+top+",right="+right+",bottom="+bottom); super.onLayout(changed, left, top, right, bottom); mThumbPosition = isChecked() ? getThumbScrollRange() : 0; int switchRight = getWidth() - getPaddingRight(); int switchLeft = switchRight - mSwitchWidth; int switchTop = 0; int switchBottom = 0; switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) { default: case Gravity.TOP: switchTop = getPaddingTop(); switchBottom = switchTop + mSwitchHeight; break; case Gravity.CENTER_VERTICAL: switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 - mSwitchHeight / 2; switchBottom = switchTop + mSwitchHeight; break; case Gravity.BOTTOM: switchBottom = getHeight() - getPaddingBottom(); switchTop = switchBottom - mSwitchHeight; break; } mSwitchLeft = switchLeft; mSwitchTop = switchTop; mSwitchBottom = switchBottom; mSwitchRight = switchRight; // Log.d(TAG, "mSwitchLeft="+mSwitchLeft+" mSwitchRight="+mSwitchRight); // Log.d(TAG, "mSwitchTop="+mSwitchTop+" mSwitchBottom="+mSwitchBottom); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (mOnLayout == null) { mOnLayout = makeLayout(mTextOn); } if (mOffLayout == null) { mOffLayout = makeLayout(mTextOff); } final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth()); final int maxTextHeight = Math.max(mOnLayout.getHeight(), mOffLayout.getHeight()); mThumbWidth = maxTextWidth + mThumbTextPadding * 2 + mThPad.left + mThPad.right; mThumbWidth = Math.max(mThumbWidth, mThumbDrawable.getIntrinsicWidth()); if (mTextOnThumb == false) { mThumbWidth = mThumbDrawable.getIntrinsicWidth(); if (mThumbWidth < 15) { // TODO: change this to something guessed based on the other // parameters. mThumbWidth = 15; } } mThumbHeight = maxTextHeight + mThumbTextPadding * 2 + mThPad.bottom + mThPad.top; mThumbHeight = Math.max(mThumbHeight, mThumbDrawable.getIntrinsicHeight()); if (mTextOnThumb == false) { mThumbHeight = mThumbDrawable.getIntrinsicHeight(); if (mThumbHeight < 15) { // TODO: change this to something guessed based on the other // parameters. mThumbHeight = 15; } } // Log.d(TAG, "mThumbWidth=" + mThumbWidth); // Log.d(TAG, "mThumbHeight=" + mThumbHeight); int switchWidth; if (mOrientation == HORIZONTAL) { switchWidth = Math.max(mSwitchMinWidth, maxTextWidth * 2 + mThumbTextPadding * 2 + mTrackTextPadding * 2 + mTrackPaddingRect.left + mTrackPaddingRect.right); if (mTextOnThumb == false) { switchWidth = Math.max(maxTextWidth + mThumbWidth + mTrackTextPadding * 2 + (mTrackPaddingRect.right + mTrackPaddingRect.left) / 2, mSwitchMinWidth); } if (this.mPushStyle) { switchWidth = Math.max(mSwitchMinWidth, maxTextWidth + mThumbWidth + mTrackTextPadding + (mTrackPaddingRect.left + mTrackPaddingRect.right) / 2); } } else { switchWidth = Math.max(maxTextWidth + mThumbTextPadding * 2 + mThPad.left + mThPad.right, mThumbWidth); if ((this.mPushStyle) || (mTextOnThumb == false)) { switchWidth = Math.max(maxTextWidth + mTrackTextPadding * 2 + mTrackPaddingRect.left + mTrackPaddingRect.right, mThumbWidth); } } switchWidth = Math.max(mSwitchMinWidth, switchWidth); final int trackHeight = mTrackDrawable.getIntrinsicHeight(); final int thumbHeight = mThumbDrawable.getIntrinsicHeight(); int switchHeight = Math.max(mSwitchMinHeight, maxTextHeight); switchHeight = Math.max(trackHeight, switchHeight); switchHeight = Math.max(switchHeight, thumbHeight); if (mOrientation == VERTICAL) { switchHeight = mOnLayout.getHeight() + mOffLayout.getHeight() + mThumbTextPadding * 2 + mThPad.top + mThPad.bottom + mTrackPaddingRect.bottom + mTrackPaddingRect.top + mTrackTextPadding * 2; if (mTextOnThumb == false) { switchHeight = Math.max(mThumbHeight + maxTextHeight + (mTrackPaddingRect.bottom + mTrackPaddingRect.top) / 2 + mTrackTextPadding * 2, mSwitchMinHeight); } if (this.mPushStyle) { switchHeight = Math.max(mSwitchMinHeight, maxTextHeight + mThumbHeight + mTrackTextPadding + (mTrackPaddingRect.top + mTrackPaddingRect.bottom) / 2); } } switch (widthMode) { case MeasureSpec.AT_MOST: widthSize = Math.min(widthSize, switchWidth); break; case MeasureSpec.UNSPECIFIED: widthSize = switchWidth; break; case MeasureSpec.EXACTLY: // Just use what we were given break; } switch (heightMode) { case MeasureSpec.AT_MOST: heightSize = Math.min(heightSize, switchHeight); break; case MeasureSpec.UNSPECIFIED: heightSize = switchHeight; break; case MeasureSpec.EXACTLY: // Just use what we were given break; } mSwitchWidth = switchWidth; mSwitchHeight = switchHeight; // Log.d(TAG, "onMeasure():mSwitchWidth=" + mSwitchWidth // + " mSwitchHeight=" + mSwitchHeight); super.onMeasure(widthMeasureSpec, heightMeasureSpec); final int measuredHeight = getMeasuredHeight(); final int measuredWidth = getMeasuredWidth(); if (measuredHeight < switchHeight) { setMeasuredDimension(getMeasuredWidth(), switchHeight); } if (measuredWidth < switchWidth) { setMeasuredDimension(switchWidth, getMeasuredHeight()); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { // Log.d(TAG, "onLayout()-left=" + left + ",top=" + top + ",right=" // + right + ",bottom=" + bottom); super.onLayout(changed, left, top, right, bottom); int switchTop = 0; int switchBottom = 0; switch (getGravity() & Gravity.VERTICAL_GRAVITY_MASK) { default: case Gravity.TOP: switchTop = getPaddingTop(); switchBottom = switchTop + mSwitchHeight; break; case Gravity.CENTER_VERTICAL: switchTop = (getPaddingTop() + getHeight() - getPaddingBottom()) / 2 - mSwitchHeight / 2; switchBottom = switchTop + mSwitchHeight; break; case Gravity.BOTTOM: switchBottom = getHeight() - getPaddingBottom(); switchTop = switchBottom - mSwitchHeight; break; } // mSwitchWidth = right - left; // mSwitchHeight = bottom - top; mSwitchBottom = mSwitchHeight - getPaddingBottom(); mSwitchTop = mSwitchBottom - mSwitchHeight; mSwitchRight = mSwitchWidth - getPaddingRight(); mSwitchLeft = mSwitchRight - mSwitchWidth; if (this.mTextOnThumb) { mThumbPosition = isChecked() ? getThumbScrollRange() : 0; } else { mThumbPosition = isChecked() ? 0 : getThumbScrollRange(); } // Log.d(TAG, "getWidth()=" + getWidth() + " getHeight()=" + // getHeight()); // Log.d(TAG, "getPaddingLeft()=" + getPaddingLeft() // + " getPaddingRight()=" + getPaddingRight()); // Log.d(TAG, "getPaddingTop()=" + getPaddingTop() // + " getPaddingBottom()=" + getPaddingBottom()); // // Log.d(TAG, "mSwitchWidth=" + mSwitchWidth + " mSwitchHeight=" // + mSwitchHeight); // Log.d(TAG, "mSwitchLeft=" + mSwitchLeft + " mSwitchRight=" // + mSwitchRight); // Log.d(TAG, "mSwitchTop=" + mSwitchTop + " mSwitchBottom=" // + mSwitchBottom); // now that the layout is known, prepare the drawables mTrackDrawable.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); if (mDrawableOn != null) mDrawableOn.setBounds(0, 0, mDrawableOn.getIntrinsicWidth(), mDrawableOn.getIntrinsicHeight()); if (mDrawableOff != null) mDrawableOff.setBounds(0, 0, mDrawableOff.getIntrinsicWidth(), mDrawableOff.getIntrinsicHeight()); if (mLeftBackground != null) mLeftBackground.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); if (mRightBackground != null) mRightBackground.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); if (mMaskDrawable != null) { tempBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, mSwitchBottom - mSwitchTop, Config.ARGB_8888); backingLayer = new Canvas(tempBitmap); mMaskDrawable.setBounds(mSwitchLeft, mSwitchTop, mSwitchRight, mSwitchBottom); // Log.d(TAG,"bitmap width="+tempBitmap.getWidth()+" bitmap.height="+tempBitmap.getHeight()); // Log.d(TAG,"bitmap 0,0="+String.format("%x", // (tempBitmap.getPixel(0,0)))+" bitmap 40,40="+String.format("%x", // (tempBitmap.getPixel(40,40)))); // Bitmap maskBitmap = Bitmap.createBitmap(mSwitchRight - // mSwitchLeft, mSwitchBottom - mSwitchTop, Config.ARGB_8888); // Canvas maskLayer = new Canvas(maskBitmap); mMaskDrawable.draw(backingLayer); // Log.d(TAG,"mask width="+maskBitmap.getWidth()+" mask.height="+maskBitmap.getHeight()); // Log.d(TAG,"mask 0,0="+String.format("%x", // (maskBitmap.getPixel(0,0)))+" mask 40,40="+String.format("%x", // (maskBitmap.getPixel(40,40)))); maskBitmap = tempBitmap.extractAlpha(); // Log.d(TAG,"mask 0,0="+String.format("%x", // (maskBitmap.getPixel(0,0)))+" mask 40,40="+String.format("%x", // (maskBitmap.getPixel(40,40)))); if (mLeftBackground != null) { mLeftBackground.draw(backingLayer); // leftBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // Canvas backingLayer2 = new Canvas(leftBitmap); // backingLayer2.drawBitmap(tempBitmap, 0, 0, null); // backingLayer2.drawBitmap(maskBitmap, 0, 0, xferPaint); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); leftBitmap = tempBitmap.copy(tempBitmap.getConfig(), true); } if (mRightBackground != null) { mRightBackground.draw(backingLayer); // rightBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // Canvas backingLayer3 = new Canvas(rightBitmap); // backingLayer3.drawBitmap(tempBitmap, 0, 0, null); // backingLayer3.drawBitmap(maskBitmap, 0, 0, xferPaint); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); rightBitmap = tempBitmap.copy(tempBitmap.getConfig(), true); } } if (mPushStyle) { // final int switchInnerLeft = mSwitchLeft + mTrackPaddingRect.left; final int switchInnerTop = mSwitchTop + mTrackPaddingRect.top; // final int switchInnerRight = mSwitchRight - // mTrackPaddingRect.right; final int switchInnerBottom = mSwitchBottom - mTrackPaddingRect.bottom; final int switchVerticalMid = (switchInnerTop + switchInnerBottom) / 2; final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth()); final int maxTextHeight = Math.max(mOnLayout.getHeight(), mOffLayout.getHeight()); int width = maxTextWidth * 2 + mTrackPaddingRect.left + mTrackPaddingRect.right + mThumbWidth + mTrackTextPadding * 4; int height = mSwitchBottom - mSwitchTop; if (mOrientation == VERTICAL) { height = mTrackPaddingRect.top + mTrackTextPadding + maxTextHeight + mTrackTextPadding + mThumbHeight + mTrackTextPadding + maxTextHeight + mTrackTextPadding + mTrackPaddingRect.bottom; width = mSwitchRight - mSwitchLeft; } Log.d(TAG, "pushBitmap width=" + width + " height=" + height); pushBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888); Canvas backingLayer = new Canvas(pushBitmap); mTextPaint.drawableState = getDrawableState(); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } // for vertical orientation leftBitmap is used as top bitmap if (leftBitmap != null) { backingLayer.save(); if (backingLayer.getClipBounds(canvasClipBounds)) { if (mOrientation == HORIZONTAL) { canvasClipBounds.right -= width / 2; } if (mOrientation == VERTICAL) { canvasClipBounds.bottom -= height / 2; } backingLayer.clipRect(canvasClipBounds); } backingLayer.drawBitmap(leftBitmap, 0, 0, null); backingLayer.restore(); } if (rightBitmap != null) { backingLayer.save(); if (backingLayer.getClipBounds(canvasClipBounds)) { if (mOrientation == HORIZONTAL) { canvasClipBounds.left += (width) / 2; } if (mOrientation == VERTICAL) { canvasClipBounds.top += (height) / 2; } backingLayer.clipRect(canvasClipBounds); } if (mOrientation == HORIZONTAL) { backingLayer.translate(width / 2 - mTrackPaddingRect.right, 0); } if (mOrientation == VERTICAL) { backingLayer.translate(0, height / 2 - mTrackPaddingRect.bottom); } backingLayer.drawBitmap(rightBitmap, 0, 0, null); backingLayer.restore(); } /* * if (mOrientation == HORIZONTAL) { * backingLayer.translate(mTrackPaddingRect.left, 0); * backingLayer.save(Canvas.MATRIX_SAVE_FLAG); * backingLayer.translate((maxTextWidth - mOffLayout.getWidth())/2, * switchVerticalMid - mOffLayout.getHeight() / 2); * mOffLayout.draw(backingLayer); backingLayer.restore(); * backingLayer.translate(maxTextWidth+ mTrackTextPadding * 2+ * (maxTextWidth - mOnLayout.getWidth())/2 + mThumbWidth+ * mThPad.left + mThPad.right, switchVerticalMid - * mOnLayout.getHeight() / 2); mOnLayout.draw(backingLayer); } * * if (mOrientation == VERTICAL) { * backingLayer.translate(0,mTrackPaddingRect.top); * backingLayer.save(Canvas.MATRIX_SAVE_FLAG); * backingLayer.translate((maxTextWidth - mOffLayout.getWidth())/2, * switchVerticalMid - mOffLayout.getHeight() / 2); * mOffLayout.draw(backingLayer); backingLayer.restore(); * backingLayer.translate((maxTextWidth - mOnLayout.getWidth())/2, * maxTextHeight+ mTrackTextPadding * 2+ (maxTextHeight - * mOnLayout.getHeight())/2 + mThumbWidth+ mThPad.left + * mThPad.top); mOnLayout.draw(backingLayer); } */ } } // Draw the switch @Override protected void onDraw(Canvas canvas) { // Log.d(TAG, // "onDraw()canvas:height="+canvas.getHeight()+" width="+canvas.getWidth()); // Rect canvasClipBounds = canvas.getClipBounds(); // Log.d(TAG, "onDraw()canvas:clipbounds="+canvasClipBounds); // super.onDraw(canvas); int switchInnerLeft = mSwitchLeft + mTrackPaddingRect.left; int switchInnerTop = mSwitchTop + mTrackPaddingRect.top; int switchInnerRight = mSwitchRight - mTrackPaddingRect.right; int switchInnerBottom = mSwitchBottom - mTrackPaddingRect.bottom; int thumbRange = getThumbScrollRange(); int thumbPos = (int) (mThumbPosition + 0.5f); int alpha = mTextPaint.getAlpha(); mTextPaint.drawableState = getDrawableState(); // Log.d(TAG, // "switchInnerLeft="+switchInnerLeft+" switchInnerRight="+switchInnerRight); // Log.d(TAG, // "switchInnerTop="+switchInnerTop+" switchInnerBottom="+switchInnerBottom); // Log.d(TAG, "thumbRange="+thumbRange+" thumbPos="+thumbPos); if (mOrientation == VERTICAL) { int switchHorizontalMid = (switchInnerLeft + switchInnerRight) / 2; int thumbBoundR = mSwitchRight; int thumbBoundT = switchInnerTop + 1 * this.getThumbScrollRange() - mThumbExtraMovement; int thumbBoundB = thumbBoundT + mThumbHeight; if (mPushStyle) { final int maxTextHeight = Math.max(mOnLayout.getHeight(), mOffLayout.getHeight()); // tempBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // backingLayer = new Canvas(tempBitmap); backingLayer.save(); backingLayer.translate(0, -thumbRange + thumbPos); backingLayer.drawBitmap(pushBitmap, 0, 0, null); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); mTrackDrawable.draw(canvas); backingLayer.drawColor(0xff000000, Mode.DST_IN); backingLayer.save(); backingLayer.translate(0, -thumbRange + thumbPos); backingLayer.translate(0, mTrackPaddingRect.top); backingLayer.save(); backingLayer.translate(0, (maxTextHeight - mOffLayout.getHeight()) / 2); if (mDrawableOff != null) mDrawableOff.draw(backingLayer); backingLayer.translate( switchHorizontalMid - mOffLayout.getWidth() / 2, 0); mOffLayout.draw(backingLayer); backingLayer.restore(); backingLayer.translate(0, maxTextHeight + mTrackTextPadding * 2 + (maxTextHeight - mOnLayout.getHeight()) / 2 + mThumbHeight);// + mThPad.left + mThPad.right,) if (mDrawableOn != null) mDrawableOn.draw(backingLayer); backingLayer.translate( switchHorizontalMid - mOnLayout.getWidth() / 2, 0);// + // mThPad.left // + // mThPad.right,) mOnLayout.draw(backingLayer); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); } else { if (rightBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { if (this.mOrientation == HORIZONTAL) { canvasClipBounds.left += (thumbPos + mThumbWidth / 2); } if (this.mOrientation == VERTICAL) { canvasClipBounds.top += (thumbPos + mThumbHeight / 2); } canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(rightBitmap, 0, 0, null); canvas.restore(); } if (leftBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { if (this.mOrientation == HORIZONTAL) { canvasClipBounds.right -= (thumbRange - thumbPos + mThumbWidth / 2); } if (this.mOrientation == VERTICAL) { canvasClipBounds.bottom = (canvasClipBounds.top + thumbPos + mThumbHeight / 2); } canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(leftBitmap, 0, 0, null); canvas.restore(); } // draw the track mTrackDrawable.draw(canvas); canvas.save(); // evaluate the coordinates for drawing the Thumb and Text canvas.clipRect(switchInnerLeft, mSwitchTop, switchInnerRight, mSwitchBottom); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } // draw the texts for On/Off in reduced alpha mode. if (this.getTargetCheckedState() ^ (mTextOnThumb)) mTextPaint.setAlpha(alpha / 4); else mTextPaint.setAlpha(alpha); thumbBoundT = switchInnerTop + 1 * this.getThumbScrollRange() - mThumbExtraMovement; thumbBoundB = thumbBoundT + mThumbHeight; canvas.save(); canvas.translate(0, (thumbBoundT + thumbBoundB) / 2 - mOnLayout.getHeight() / 2); if ((mDrawableOn != null) && (mTextPaint.getAlpha() == alpha)) mDrawableOn.draw(canvas); canvas.translate( (mSwitchLeft + mSwitchRight) / 2 - mOnLayout.getWidth() / 2, 0); mOnLayout.draw(canvas); canvas.restore(); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } if (this.getTargetCheckedState() ^ (mTextOnThumb)) mTextPaint.setAlpha(alpha); else mTextPaint.setAlpha(alpha / 4); thumbBoundT = switchInnerTop + 0 * this.getThumbScrollRange() - mThumbExtraMovement; thumbBoundB = thumbBoundT + mThumbHeight; canvas.save(); canvas.translate(0, (thumbBoundT + thumbBoundB) / 2 - mOffLayout.getHeight() / 2); if ((mDrawableOff != null) && (mTextPaint.getAlpha() == alpha)) mDrawableOff.draw(canvas); canvas.translate( (mSwitchLeft + mSwitchRight) / 2 - mOffLayout.getWidth() / 2, 0); mOffLayout.draw(canvas); canvas.restore(); canvas.restore(); } thumbBoundT = switchInnerTop + thumbPos - mThumbExtraMovement; thumbBoundB = switchInnerTop + thumbPos - mThumbExtraMovement + mThumbHeight; // Draw the Thumb // Log.d(TAG, "thumbBoundT, thumbBoundB=(" + thumbBoundT + "," // + thumbBoundB + ")"); // Log.d(TAG, "mSwitchLeft, mSwitchRight=(" + mSwitchLeft + "," // + mSwitchRight + ")"); mThumbDrawable.setBounds(mSwitchLeft, thumbBoundT, mSwitchRight, thumbBoundB); mThumbDrawable.draw(canvas); mTextPaint.setAlpha(alpha); // Draw the text on the Thumb if (mTextOnThumb) { Layout offSwitchText = getTargetCheckedState() ? mOnLayout : mOffLayout; canvas.save(); canvas.translate( (mSwitchLeft + mSwitchRight) / 2 - offSwitchText.getWidth() / 2, (thumbBoundT + thumbBoundB) / 2 - offSwitchText.getHeight() / 2); // (switchInnerTop + switchInnerBottom) / 2 - // onSwitchText.getHeight() - this.mThumbTextPadding); offSwitchText.draw(canvas); canvas.restore(); } } if (mOrientation == HORIZONTAL) { int thumbL = switchInnerLeft;// + mThPad.left; int thumbR = switchInnerLeft + mThumbWidth;// - mThPad.right; int dxOffText = mTextOnThumb ? (thumbL + thumbR) / 2 - mOffLayout.getWidth() / 2 + mTrackTextPadding - mThumbTextPadding // (thumbL+thumbR)/2 already has // 2*mThumbTextPadding // so we have to subtract it : switchInnerLeft + mTrackTextPadding; thumbL = thumbL + thumbRange; thumbR = thumbR + thumbRange; int dxOnText = mTextOnThumb ? (thumbL + thumbR) / 2 - mOnLayout.getWidth() / 2 // (thumbL + thumbR)/2 already has the ThumbTextPadding // so we dont have to add it : switchInnerRight - mOnLayout.getWidth() - mTrackTextPadding; int switchVerticalMid = (switchInnerTop + switchInnerBottom) / 2; int thumbBoundL = switchInnerLeft + thumbPos - mThumbExtraMovement;// + // mThPad.left int thumbBoundR = switchInnerLeft + thumbPos + mThumbWidth - mThumbExtraMovement;// - mThPad.right if (mPushStyle) { final int maxTextWidth = Math.max(mOnLayout.getWidth(), mOffLayout.getWidth()); // tempBitmap = Bitmap.createBitmap(mSwitchRight - mSwitchLeft, // mSwitchBottom - mSwitchTop, Config.ARGB_8888); // backingLayer = new Canvas(tempBitmap); backingLayer.save(); backingLayer.translate(-thumbRange + thumbPos, 0); backingLayer.drawBitmap(pushBitmap, 0, 0, null); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); mTrackDrawable.draw(canvas); backingLayer.drawColor(0xff000000, Mode.DST_IN); backingLayer.save(); backingLayer.translate(-thumbRange + thumbPos, 0); backingLayer.translate(mTrackPaddingRect.left, 0); backingLayer.save(); backingLayer.translate( (maxTextWidth - mOffLayout.getWidth()) / 2, switchVerticalMid - mOffLayout.getHeight() / 2); mOffLayout.draw(backingLayer); if (mDrawableOff != null) mDrawableOff.draw(backingLayer); backingLayer.restore(); backingLayer.translate(maxTextWidth + mTrackTextPadding * 2 + (maxTextWidth - mOnLayout.getWidth()) / 2 + mThumbWidth,// + mThPad.left + mThPad.right, switchVerticalMid - mOnLayout.getHeight() / 2); mOnLayout.draw(backingLayer); if (mDrawableOn != null) mDrawableOn.draw(backingLayer); backingLayer.restore(); backingLayer.drawBitmap(maskBitmap, 0, 0, xferPaint); canvas.drawBitmap(tempBitmap, 0, 0, null); } else { if (rightBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.left += (mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(rightBitmap, 0, 0, null); canvas.restore(); } if (leftBitmap != null) { canvas.save(); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.right -= (thumbRange - mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } canvas.drawBitmap(leftBitmap, 0, 0, null); canvas.restore(); } // draw the track mTrackDrawable.draw(canvas); // evaluate the coordinates for drawing the Thumb and Text canvas.save(); canvas.clipRect(switchInnerLeft, mSwitchTop, switchInnerRight, mSwitchBottom); // mTextColors should not be null, but just in case if (mTextColors != null) { mTextPaint.setColor(mTextColors.getColorForState( getDrawableState(), mTextColors.getDefaultColor())); } // draw the texts for On/Off in reduced alpha mode. mTextPaint.setAlpha(alpha / 4); if (getTargetCheckedState()) { canvas.save(); canvas.translate(dxOnText, switchVerticalMid - mOnLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.left += (mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOnLayout.draw(canvas); if (mDrawableOn != null) mDrawableOn.draw(canvas); canvas.restore(); if (mTextOnThumb == false) mTextPaint.setAlpha(alpha); canvas.save(); canvas.translate(dxOffText, switchVerticalMid - mOffLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.right -= (thumbRange - mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOffLayout.draw(canvas); if (mDrawableOff != null) mDrawableOff.draw(canvas); canvas.restore(); } else { canvas.save(); canvas.translate(dxOffText, switchVerticalMid - mOffLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.right -= (thumbRange - mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOffLayout.draw(canvas); if (mDrawableOff != null) mDrawableOff.draw(canvas); canvas.restore(); if (mTextOnThumb == false) mTextPaint.setAlpha(alpha); canvas.save(); canvas.translate(dxOnText, switchVerticalMid - mOnLayout.getHeight() / 2); if (canvas.getClipBounds(canvasClipBounds)) { canvasClipBounds.left += (mThumbPosition + mThumbWidth / 2); canvas.clipRect(canvasClipBounds); } mOnLayout.draw(canvas); if (mDrawableOn != null) mDrawableOn.draw(canvas); canvas.restore(); } canvas.restore(); } // Draw the Thumb // Log.d(TAG, // "thumbBoundL, thumbBoundR=("+thumbBoundL+","+thumbBoundR+")"); mThumbDrawable.setBounds(thumbBoundL, mSwitchTop, thumbBoundR, mSwitchBottom); mThumbDrawable.draw(canvas); // Draw the text on the Thumb if (mTextOnThumb) { mTextPaint.setAlpha(alpha); Layout onSwitchText = getTargetCheckedState() ? mOnLayout : mOffLayout; canvas.save(); canvas.translate( (thumbBoundL + thumbBoundR) / 2 - onSwitchText.getWidth() / 2, (switchInnerTop + switchInnerBottom) / 2 - onSwitchText.getHeight() / 2); onSwitchText.draw(canvas); canvas.restore(); } } } @Override public int getCompoundPaddingRight() { int padding = super.getCompoundPaddingRight() + mSwitchWidth; if (!TextUtils.isEmpty(getText())) { padding += mSwitchPadding; } return padding; } @Override public int getCompoundPaddingTop() { int padding = super.getCompoundPaddingTop() + mSwitchHeight; if (!TextUtils.isEmpty(getText())) { padding += mSwitchPadding; } return padding; } private int getThumbScrollRange() { if (mTrackDrawable == null) { return 0; } int range = 0; if (mOrientation == VERTICAL) range = mSwitchHeight - mThumbHeight - mTrackPaddingRect.top - mTrackPaddingRect.bottom + mThumbExtraMovement * 2; if (mOrientation == HORIZONTAL) range = mSwitchWidth - mThumbWidth - mTrackPaddingRect.left - mTrackPaddingRect.right + mThumbExtraMovement * 2; if (this.mPushStyle) range += this.mTrackTextPadding * 2; // Log.d(TAG,"getThumbScrollRange() = "+ range); return range; } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } @Override protected void drawableStateChanged() { super.drawableStateChanged(); int[] myDrawableState = getDrawableState(); // Set the state of the Drawable // Drawable may be null when checked state is set from XML, from super // constructor if (mThumbDrawable != null) mThumbDrawable.setState(myDrawableState); if (mTrackDrawable != null) mTrackDrawable.setState(myDrawableState); invalidate(); } @Override protected boolean verifyDrawable(Drawable who) { return super.verifyDrawable(who) || who == mThumbDrawable || who == mTrackDrawable; } }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/MySwitch.java
Java
art
51,910
package net.cardgame.oraclecard.common; import android.widget.ImageView; public interface CustomAnimationListener { public void onEndAnimation(ImageView imageview); }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/net/cardgame/oraclecard/common/CustomAnimationListener.java
Java
art
177
/* * Copyright (C) 2012 The Android Open Source Project * * 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 com.android.vending.billing; import android.os.Bundle; /** * InAppBillingService is the service that provides in-app billing version 3 and beyond. * This service provides the following features: * 1. Provides a new API to get details of in-app items published for the app including * price, type, title and description. * 2. The purchase flow is synchronous and purchase information is available immediately * after it completes. * 3. Purchase information of in-app purchases is maintained within the Google Play system * till the purchase is consumed. * 4. An API to consume a purchase of an inapp item. All purchases of one-time * in-app items are consumable and thereafter can be purchased again. * 5. An API to get current purchases of the user immediately. This will not contain any * consumed purchases. * * All calls will give a response code with the following possible values * RESULT_OK = 0 - success * RESULT_USER_CANCELED = 1 - user pressed back or canceled a dialog * RESULT_BILLING_UNAVAILABLE = 3 - this billing API version is not supported for the type requested * RESULT_ITEM_UNAVAILABLE = 4 - requested SKU is not available for purchase * RESULT_DEVELOPER_ERROR = 5 - invalid arguments provided to the API * RESULT_ERROR = 6 - Fatal error during the API action * RESULT_ITEM_ALREADY_OWNED = 7 - Failure to purchase since item is already owned * RESULT_ITEM_NOT_OWNED = 8 - Failure to consume since item is not owned */ interface IInAppBillingService { /** * Checks support for the requested billing API version, package and in-app type. * Minimum API version supported by this interface is 3. * @param apiVersion the billing version which the app is using * @param packageName the package name of the calling app * @param type type of the in-app item being purchased "inapp" for one-time purchases * and "subs" for subscription. * @return RESULT_OK(0) on success, corresponding result code on failures */ int isBillingSupported(int apiVersion, String packageName, String type); /** * Provides details of a list of SKUs * Given a list of SKUs of a valid type in the skusBundle, this returns a bundle * with a list JSON strings containing the productId, price, title and description. * This API can be called with a maximum of 20 SKUs. * @param apiVersion billing API version that the Third-party is using * @param packageName the package name of the calling app * @param skusBundle bundle containing a StringArrayList of SKUs with key "ITEM_ID_LIST" * @return Bundle containing the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "DETAILS_LIST" with a StringArrayList containing purchase information * in JSON format similar to: * '{ "productId" : "exampleSku", "type" : "inapp", "price" : "$5.00", * "title : "Example Title", "description" : "This is an example description" }' */ Bundle getSkuDetails(int apiVersion, String packageName, String type, in Bundle skusBundle); /** * Returns a pending intent to launch the purchase flow for an in-app item by providing a SKU, * the type, a unique purchase token and an optional developer payload. * @param apiVersion billing API version that the app is using * @param packageName package name of the calling app * @param sku the SKU of the in-app item as published in the developer console * @param type the type of the in-app item ("inapp" for one-time purchases * and "subs" for subscription). * @param developerPayload optional argument to be sent back with the purchase information * @return Bundle containing the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "BUY_INTENT" - PendingIntent to start the purchase flow * * The Pending intent should be launched with startIntentSenderForResult. When purchase flow * has completed, the onActivityResult() will give a resultCode of OK or CANCELED. * If the purchase is successful, the result data will contain the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "INAPP_PURCHASE_DATA" - String in JSON format similar to * '{"orderId":"12999763169054705758.1371079406387615", * "packageName":"com.example.app", * "productId":"exampleSku", * "purchaseTime":1345678900000, * "purchaseToken" : "122333444455555", * "developerPayload":"example developer payload" }' * "INAPP_DATA_SIGNATURE" - String containing the signature of the purchase data that * was signed with the private key of the developer * TODO: change this to app-specific keys. */ Bundle getBuyIntent(int apiVersion, String packageName, String sku, String type, String developerPayload); /** * Returns the current SKUs owned by the user of the type and package name specified along with * purchase information and a signature of the data to be validated. * This will return all SKUs that have been purchased in V3 and managed items purchased using * V1 and V2 that have not been consumed. * @param apiVersion billing API version that the app is using * @param packageName package name of the calling app * @param type the type of the in-app items being requested * ("inapp" for one-time purchases and "subs" for subscription). * @param continuationToken to be set as null for the first call, if the number of owned * skus are too many, a continuationToken is returned in the response bundle. * This method can be called again with the continuation token to get the next set of * owned skus. * @return Bundle containing the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "INAPP_PURCHASE_ITEM_LIST" - StringArrayList containing the list of SKUs * "INAPP_PURCHASE_DATA_LIST" - StringArrayList containing the purchase information * "INAPP_DATA_SIGNATURE_LIST"- StringArrayList containing the signatures * of the purchase information * "INAPP_CONTINUATION_TOKEN" - String containing a continuation token for the * next set of in-app purchases. Only set if the * user has more owned skus than the current list. */ Bundle getPurchases(int apiVersion, String packageName, String type, String continuationToken); /** * Consume the last purchase of the given SKU. This will result in this item being removed * from all subsequent responses to getPurchases() and allow re-purchase of this item. * @param apiVersion billing API version that the app is using * @param packageName package name of the calling app * @param purchaseToken token in the purchase information JSON that identifies the purchase * to be consumed * @return 0 if consumption succeeded. Appropriate error values for failures. */ int consumePurchase(int apiVersion, String packageName, String purchaseToken); }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/src/com/android/vending/billing/IInAppBillingService.aidl
AIDL
art
8,443
/** Automatically generated file. DO NOT MODIFY */ package jp.jma.oraclecard; public final class BuildConfig { public final static boolean DEBUG = true; }
01-project-boi-bai
trunk/ 01-project-boi-bai --username macthevuls@gmail.com/OrcaleCard/gen/jp/jma/oraclecard/BuildConfig.java
Java
art
159
/** Automatically generated file. DO NOT MODIFY */ package gracedave.CoopATMFinder; public final class BuildConfig { public final static boolean DEBUG = true; }
11bindra11-atm
CoopATMFinder/gen/gracedave/CoopATMFinder/BuildConfig.java
Java
mit
165
package gracedave.CoopATMFinder; import android.app.Activity; import android.os.Bundle; public class CoopATMFinderActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
11bindra11-atm
CoopATMFinder/src/gracedave/CoopATMFinder/CoopATMFinderActivity.java
Java
mit
356
/* Copyright 2011 Gene Chen 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. */ #include "xdcc.h" #include "xdcc_version.h" #include "irchandler.h" #include "channelhandler.h" #include "xmlstructs.h" #include "dcapifetcher.h" #include "qgproxy.h" #include "updateform.h" #include "loginform.h" #include "settingsform.h" #include <QClipboard> #include <QSharedPointer> #include <QImage> #include <QSettings> #include <QFile> #include <QEvent> #include <QProcess> XDCC::XDCC(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags) { ui.setupUi(this); m_Settings = new QSettings("DotaCash", "DCClient X", this); m_Timer = new QTimer(this); connect(m_Timer, SIGNAL(timeout()), this, SLOT(tick())); m_CGProxy = new CGProxy(this); m_LocalServer = new QLocalServer(this); m_LocalServer->listen("DCClientIPC"); connect(m_LocalServer, SIGNAL(newConnection()), this, SLOT(newConnection())); connect(ui.txtChatInput, SIGNAL(returnPressed()), this, SLOT(handleChat())); connect(ui.tabGames, SIGNAL(currentChanged(int)), this, SLOT(tick())); ui.tblPubGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblPubGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblPubGames->horizontalHeader()->hideSection(2); ui.tblPubGames->horizontalHeader()->hideSection(3); ui.tblPrivGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblPrivGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblPrivGames->horizontalHeader()->hideSection(2); ui.tblPrivGames->horizontalHeader()->hideSection(3); ui.tblHLGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblHLGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblHLGames->horizontalHeader()->hideSection(2); ui.tblHLGames->horizontalHeader()->hideSection(3); ui.tblCustomGames->horizontalHeader()->setResizeMode(0, QHeaderView::Interactive); ui.tblCustomGames->horizontalHeader()->setResizeMode(1, QHeaderView::Fixed); ui.tblCustomGames->horizontalHeader()->hideSection(2); ui.tblCustomGames->horizontalHeader()->hideSection(3); ui.tblPlayers->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch); ui.tblPlayers->horizontalHeader()->setResizeMode(1, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(3, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(4, QHeaderView::ResizeToContents); ui.tblPlayers->horizontalHeader()->setResizeMode(5, QHeaderView::ResizeToContents); connect(ui.tblPubGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblPrivGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblHLGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblCustomGames, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(gameDoubleClicked(int, int))); connect(ui.tblPubGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.tblPrivGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.tblHLGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.tblCustomGames, SIGNAL(cellClicked(int, int)), this, SLOT(gameClicked(int, int))); connect(ui.actionCheck_for_updates, SIGNAL(triggered()), this, SLOT(checkForUpdates())); connect(ui.action_About, SIGNAL(triggered()), this, SLOT(showAbout())); connect(ui.action_Options, SIGNAL(triggered()), this, SLOT(showSettings())); m_UpdateForm = new UpdateForm(this); m_LoginForm = new LoginForm(this); m_SettingsForm = new SettingsForm(this); connect(m_UpdateForm, SIGNAL(updateFromURL(QString&)), this, SLOT(updateFromURL(QString&))); connect(m_CGProxy, SIGNAL(joinedGame(QString, QString)), ui.tabChannels, SLOT(joinedGame(QString, QString))); m_Skin = m_Settings->value("Skin", "default").toString(); QFile styleSheet(QString("./skins/%1/style.css").arg(m_Skin)); QString style; if(styleSheet.open(QFile::ReadOnly)) { QTextStream styleIn(&styleSheet); style = styleIn.readAll(); styleSheet.close(); this->setStyleSheet(style); } m_Active = true; qApp->installEventFilter( this ); m_UpdateForm->checkForUpdates(APPCAST_URL, false); m_LoginForm->show(); } XDCC::~XDCC() { while(!m_GameInfos.empty()) { delete m_GameInfos.front(); m_GameInfos.pop_front(); } while(!m_QueueInfos.empty()) { delete m_QueueInfos.front(); m_QueueInfos.pop_front(); } while(!m_PlayerInfos.empty()) { delete m_PlayerInfos.front(); m_PlayerInfos.pop_front(); } delete m_Settings; m_Settings = NULL; delete m_Timer; delete m_CGProxy; delete m_LocalServer; delete m_LoginForm; delete m_SettingsForm; } void XDCC::updateFromURL(QString& url) { QMessageBox::warning(this, "DCClient X Update", tr("DCClient will now restart in order to apply updates.")); m_LoginForm->hide(); QStringList params; params << "--install-dir" << "."; params << "--package-dir" << "updates"; params << "--script" << "updates/file_list.xml"; if(QProcess::startDetached("updater.exe", params)) QApplication::quit(); else QMessageBox::warning(this, tr("Problem"),tr("Unable to start updater, try updating manually by downloading the file: <a href=\"%1\">%2</a>").arg(url).arg(url)); } bool XDCC::eventFilter(QObject *obj, QEvent *event) { bool inactiveRefresh = false; if(m_Settings) inactiveRefresh = m_Settings->value("InactiveRefresh", false).toBool(); static bool inActivationEvent = false; if(!inactiveRefresh) { if (obj == qApp && !inActivationEvent) { if (event->type() == QEvent::ApplicationActivate && !m_Active) { inActivationEvent = true; m_Active = true; this->tick(); m_Timer->start(3000); inActivationEvent = false; } else if (event->type() == QEvent::ApplicationDeactivate && m_Active) { inActivationEvent = true; m_Active = false; m_Timer->stop(); inActivationEvent = false; } } } return QMainWindow::eventFilter(obj, event); } void XDCC::checkForUpdates() { m_UpdateForm->checkForUpdates(APPCAST_URL, true); } void XDCC::showAbout() { QMessageBox::information(this, "DotaCash Client X", tr("DotaCash Client X v%1 by Zephyrix").arg(XDCC_VERSION)); } void XDCC::showSettings() { m_SettingsForm->show(); } void XDCC::gameDoubleClicked(int row, int column) { Q_UNUSED(column); QTableWidget* table; switch(ui.tabGames->currentIndex()) { case 0: table = ui.tblPubGames; break; case 1: table = ui.tblPrivGames; break; case 2: table = ui.tblHLGames; break; case 3: table = ui.tblCustomGames; break; default: return; } if(row < table->rowCount()) { QString txt = table->item(row, 0)->text(); QString id = table->item(row, 2)->text(); QString ip = table->item(row, 3)->text(); QClipboard *cb = QApplication::clipboard(); cb->setText(txt); requestGame(ip); ui.statusBar->showMessage(tr("%1 copied to clipboard and is now visible in LAN screen.").arg(txt), 3000); } } void XDCC::gameClicked(int row, int column) { Q_UNUSED(column); QTableWidget* table; switch(ui.tabGames->currentIndex()) { case 0: table = ui.tblPubGames; break; case 1: table = ui.tblPrivGames; break; case 2: table = ui.tblHLGames; break; case 3: table = ui.tblCustomGames; break; default: return; } if(row < table->rowCount()) { QTableWidgetItem* tblItem = table->item(row, 2); if(tblItem) m_CurrentID = tblItem->text(); tick(); } } void XDCC::newConnection() { m_ClientConnection = m_LocalServer->nextPendingConnection(); connect(m_ClientConnection, SIGNAL(disconnected()), m_ClientConnection, SLOT(deleteLater())); connect(m_ClientConnection, SIGNAL(readyRead()), this, SLOT(readData())); } void XDCC::readData() { QDataStream in(m_ClientConnection); QString arg; in >> arg; activateWindow(); } void XDCC::tick() { if(!m_Active) return; if(!m_CurrentID.isEmpty()) { ApiFetcher* playersFetcher = new ApiFetcher(this); connect(playersFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parsePlayersXml(QString&))); QString playersUrl = "http://" + API_SERVER + QString("/api/gp.php?u=%1&l=%2").arg(m_SessionID).arg(m_CurrentID); playersFetcher->fetch(playersUrl); } ApiFetcher* gamesFetcher = new ApiFetcher(this); connect(gamesFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseGamesXml(QString&))); m_CurrentType = ui.tabGames->currentIndex(); QString gamesUrl = "http://" + API_SERVER + QString("/api/gg.php?u=%1&t=%2").arg(m_SessionID).arg(m_CurrentType+1); gamesFetcher->fetch(gamesUrl); ApiFetcher* queueFetcher = new ApiFetcher(this); connect(queueFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseQueueXml(QString&))); QString queueUrl ="http://" + API_SERVER + QString("/api/cq.php?u=%1").arg(m_SessionID); queueFetcher->fetch(queueUrl); } void XDCC::activate() { ui.tabChannels->connectToIrc(this->GetUsername()); connect(ui.tabChannels, SIGNAL(showMessage(QString, int)), this, SLOT(showMessage(QString, int))); connect(m_SettingsForm, SIGNAL(reloadSkin()), ui.tabChannels, SLOT(reloadSkin())); connect(ui.tabChannels, SIGNAL(requestGame(QString)), this , SLOT(requestGame(QString))); this->tick(); m_Timer->start(3000); this->show(); } void XDCC::showMessage(QString message, int timeout=3000) { ui.statusBar->showMessage(message, timeout); } void XDCC::handleChat() { QString curTab = ui.tabChannels->tabText(ui.tabChannels->currentIndex()); QString Message = ui.txtChatInput->text(); ui.txtChatInput->clear(); ui.tabChannels->handleChat(curTab, Message); } void XDCC::parseGamesXml(QString& data) { QXmlStreamReader xml(data); for(int i = 0; i < m_GameInfos.size(); ++i) delete m_GameInfos.at(i); m_GameInfos.clear(); QMap<QString, QString> resultMap; QString currentTag; while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.qualifiedName() == "game") { GameInfo* gameInfo = new GameInfo; gameInfo->name = resultMap["name"]; gameInfo->ip = resultMap["ip"]; gameInfo->players = resultMap["players"]; gameInfo->id = resultMap["idLobby"]; m_GameInfos.push_back(gameInfo); resultMap.clear(); } currentTag.clear(); } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } else { QTableWidget* table; switch(m_CurrentType) { case 0: table = ui.tblPubGames; break; case 1: table = ui.tblPrivGames; break; case 2: table = ui.tblHLGames; break; case 3: table = ui.tblCustomGames; break; default: return; } table->setRowCount(m_GameInfos.size()); for(int i = 0; i < m_GameInfos.size(); ++i) { GameInfo* gameInfo = m_GameInfos.at(i); QTableWidgetItem *itemName = new QTableWidgetItem( gameInfo->name ); QTableWidgetItem *itemPlrCount = new QTableWidgetItem( gameInfo->players ); QTableWidgetItem *idx = new QTableWidgetItem( gameInfo->id ); QTableWidgetItem *ip = new QTableWidgetItem( gameInfo->ip ); itemName->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemPlrCount->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemPlrCount->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); table->setItem(i, 0, itemName); table->setItem(i, 1, itemPlrCount); table->setItem(i, 2, idx); table->setItem(i, 3, ip); } } } void XDCC::parseQueueXml(QString& data) { QXmlStreamReader xml(data); QMap<QString, QString> resultMap; QString currentTag; for(int i = 0; i < m_QueueInfos.size(); ++i) delete m_QueueInfos.at(i); m_QueueInfos.clear(); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.qualifiedName() == "game") { QueueInfo* queueInfo = new QueueInfo; queueInfo->position = resultMap["Position"]; queueInfo->name = resultMap["GameName"]; m_QueueInfos.push_back(queueInfo); resultMap.clear(); } currentTag.clear(); } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } else { for(int i = 0; i < ui.tblQueue->rowCount(); ++i) delete ui.tblQueue->itemAt(i, 0); ui.tblQueue->setRowCount(m_QueueInfos.size()); for(int i = 0; i < m_QueueInfos.size(); ++i) { QueueInfo* queueInfo = m_QueueInfos.at(i); QTableWidgetItem *itemName = new QTableWidgetItem( queueInfo->name ); itemName->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemName->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); ui.tblQueue->setItem(i, 0, itemName); } } } void XDCC::parsePlayersXml(QString& data) { QXmlStreamReader xml(data); QMap<QString, QString> resultMap; QString currentTag; for(int i = 0; i < m_PlayerInfos.size(); ++i) delete m_PlayerInfos.at(i); m_PlayerInfos.clear(); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.qualifiedName() == "player") { PlayerInfo* playerInfo = new PlayerInfo; playerInfo->name = resultMap["playername"]; playerInfo->slot = resultMap["playerslot"]; playerInfo->realm = resultMap["playerrealm"]; playerInfo->elo = resultMap["playerelo"]; playerInfo->games = resultMap["playergames"]; playerInfo->kdr = resultMap["playerkdr"]; playerInfo->wins = resultMap["playerwins"]; m_PlayerInfos.push_back(playerInfo); resultMap.clear(); } currentTag.clear(); } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } else { for(int i = 0; i < ui.tblPlayers->rowCount(); ++i) { delete ui.tblPlayers->itemAt(i, 0); delete ui.tblPlayers->itemAt(i, 1); delete ui.tblPlayers->itemAt(i, 2); delete ui.tblPlayers->itemAt(i, 3); delete ui.tblPlayers->itemAt(i, 4); delete ui.tblPlayers->itemAt(i, 5); } ui.tblPlayers->setRowCount(m_PlayerInfos.size()); for(int i = 0; i < m_PlayerInfos.size(); ++i) { PlayerInfo* playerInfo = m_PlayerInfos.at(i); QTableWidgetItem *itemName = new QTableWidgetItem( playerInfo->name ); QTableWidgetItem *itemRealm = new QTableWidgetItem( playerInfo->realm ); QTableWidgetItem *itemELO = new QTableWidgetItem( playerInfo->elo ); QTableWidgetItem *itemGames = new QTableWidgetItem( playerInfo->games ); QTableWidgetItem *itemKDR = new QTableWidgetItem( playerInfo->kdr ); QTableWidgetItem *itemWins = new QTableWidgetItem( playerInfo->wins ); itemName->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); //itemName->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemRealm->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemRealm->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemELO->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemELO->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemGames->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemGames->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemKDR->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemKDR->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); itemWins->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); itemWins->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter); QColor color; if(i < 5) // sentinel { if(i % 2) color = QColor(0xFF, 0xEE, 0xEE); else color = QColor(0xFF, 0xF5, 0xF5); } else if(i < 10) // scourge { if(i % 2) color = QColor(0xEE, 0xFF, 0xEE); else color = QColor(0xF5, 0xFF, 0xF5); } else // other cells color = QColor(0xFF, 0xFF, 0xFF); itemName->setBackgroundColor(color); itemRealm->setBackgroundColor(color); itemELO->setBackgroundColor(color); itemGames->setBackgroundColor(color); itemKDR->setBackgroundColor(color); itemWins->setBackgroundColor(color); ui.tblPlayers->setItem(i, 0, itemName); ui.tblPlayers->setItem(i, 1, itemRealm); ui.tblPlayers->setItem(i, 2, itemELO); ui.tblPlayers->setItem(i, 3, itemGames); ui.tblPlayers->setItem(i, 4, itemKDR); ui.tblPlayers->setItem(i, 5, itemWins); } } } void XDCC::requestGame(QString IP) { ApiFetcher* safelistFetcher = new ApiFetcher(this); QString safelistUrl = "http://" + API_SERVER + QString("/api/dccslip.php?u=%1&botip=%2").arg(m_SessionID).arg(IP); safelistFetcher->fetch(safelistUrl); m_CGProxy->requestGame(IP); }
12ayhuang-mac-experiment
xdcc.cpp
C++
asf20
17,759
HEADERS += ./xmlstructs.h \ ./dcapifetcher.h \ ./xdcc.h \ ./loginform.h \ ./resource.h \ ./channelhandler.h \ ./irchandler.h \ ./commandpacket.h \ ./gameprotocol.h \ ./gpsprotocol.h \ ./qgproxy.h \ ./xdcc_version.h \ ./settingsform.h \ ./friendshandler.h SOURCES += ./dcapifetcher.cpp \ ./main.cpp \ ./loginform.cpp \ ./xdcc.cpp \ ./channelhandler.cpp \ ./irchandler.cpp \ ./commandpacket.cpp \ ./gameprotocol.cpp \ ./gpsprotocol.cpp \ ./qgproxy.cpp \ ./settingsform.cpp \ ./friendshandler.cpp FORMS += ./xdcc_main.ui \ ./xdcc_login.ui \ ./xdcc_update.ui \ ./xdcc_options.ui \ RESOURCES += xdcc.qrc
12ayhuang-mac-experiment
xDCC.pri
QMake
asf20
710
/* Copyright 2011 Gene Chen 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. */ #ifndef FRIENDSHANDLER_H #define FRIENDSHANDLER_H #include "xdcc.h" #include <QObject> #include <QTextBrowser> #include <QListWidget> #define COMMUNI_STATIC #include <Irc> #include <IrcMessage> class FriendsHandler : public QObject { Q_OBJECT public: FriendsHandler(QString nFriendName, QWidget *parent=0); bool GetStatus() { return m_Status; } void SetStatus(bool nStatus) { m_Status = nStatus; } public slots: void joined(const QString); void parted(const QString, const QString); void nickChanged(const QString, const QString); void messageReceived(const QString &origin, const QString &message); void noticeReceived(const QString &origin, const QString &message); signals: void showMessage(QString, MessageType msgType = Normal); void requestGame(QString); private: QString m_FriendName; bool m_Status; }; #endif
12ayhuang-mac-experiment
friendshandler.h
C++
asf20
1,431
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_H #define XDCC_H #ifdef WIN32 #include <Windows.h> #ifdef _DEBUG #include <vld.h> #endif #endif #include "ui_xdcc_main.h" #include <QtGui/QMainWindow> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QXmlStreamReader> #include <QDebug> #include <QMessageBox> #include <QTimer> #include <qlocalserver.h> #include <qlocalsocket.h> #include <QSettings> #include <QStringList> class GameRequester; class CGProxy; class UpdateForm; class LoginForm; class SettingsForm; class ApiFetcher; struct GameInfo; struct QueueInfo; struct PlayerInfo; class XDCC : public QMainWindow { Q_OBJECT public: XDCC(QWidget *parent = 0, Qt::WFlags flags = 0); ~XDCC(); void SetUsername(QString nUsername) { m_Username = nUsername; ui.lbl_Account->setText(m_Username); } void SetScore(quint32 nScore) { m_Score = nScore; ui.lbl_Rating->setText(QString::number(m_Score)); } void SetRank(quint32 nRank) { m_Rank = nRank; ui.lbl_Rank->setText(QString::number(m_Rank)); } void SetSessionID(QString nSessionID) { m_SessionID = nSessionID; } QString GetUsername() { return m_Username; } quint32 GetScore() { return m_Score; } quint32 GetRank() { return m_Rank; } QString GetSessionID() { return m_SessionID; } void activate(); public slots: void tick(); void newConnection(); void readData(); void handleChat(); void gameDoubleClicked(int, int); void gameClicked(int, int); void parseGamesXml(QString&); void parseQueueXml(QString&); void parsePlayersXml(QString&); void showMessage(QString, int); void checkForUpdates(); void showAbout(); void showSettings(); void requestGame(QString); void updateFromURL(QString&); private: Ui::xDCCClass ui; UpdateForm* m_UpdateForm; LoginForm* m_LoginForm; SettingsForm* m_SettingsForm; QSettings* m_Settings; QString m_Username; quint32 m_Score; quint32 m_Rank; QString m_SessionID; QTimer* m_Timer; QLocalServer* m_LocalServer; QLocalSocket* m_ClientConnection; CGProxy* m_CGProxy; QVector<GameInfo*> m_GameInfos; QVector<QueueInfo*> m_QueueInfos; QVector<PlayerInfo*> m_PlayerInfos; int m_CurrentType; QString m_CurrentID; QString m_Skin; bool m_Active; bool eventFilter(QObject *obj, QEvent *event); ApiFetcher* m_PlayersFetcher; ApiFetcher* m_GamesFetcher; ApiFetcher* m_QueueFetcher; }; #endif // XDCC_H
12ayhuang-mac-experiment
xdcc.h
C++
asf20
2,929
/* Copyright 2010 Trevor Hogan 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. */ #ifndef COMMANDPACKET_H #define COMMANDPACKET_H #include <QByteArray> // // CCommandPacket // class CCommandPacket { private: unsigned char m_PacketType; int m_ID; QByteArray m_Data; public: CCommandPacket( unsigned char nPacketType, int nID, QByteArray nData ); ~CCommandPacket( ); unsigned char GetPacketType( ) { return m_PacketType; } int GetID( ) { return m_ID; } QByteArray GetData( ) { return m_Data; } }; #endif
12ayhuang-mac-experiment
commandpacket.h
C++
asf20
1,029
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_LOGIN_H #define XDCC_LOGIN_H #include <QtGui/QMainWindow> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QXmlStreamReader> #include <QSettings> #include "xdcc.h" #include "ui_xdcc_login.h" class LoginForm : public QDialog { Q_OBJECT public: LoginForm(XDCC* nXDCC, QWidget *parent = 0, Qt::WFlags flags = 0); ~LoginForm(); public slots: void login(); void parseLogin(QString& data); private: Ui::LoginDialog ui; QXmlStreamReader xml; QString Username; QSettings* settings; ApiFetcher* fetcher; XDCC* m_xDCC; }; #endif // XDCC_H
12ayhuang-mac-experiment
loginform.h
C++
asf20
1,171
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by xDCC.rc // #define IDI_ICON1 106 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 107 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
12ayhuang-mac-experiment
resource.h
C
asf20
431
/* Copyright 2011 Gene Chen 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. */ #include "loginform.h" #include "xdcc.h" #include "dcapifetcher.h" #include "xdcc_version.h" #include <QDebug> #include <QMap> #include <QMessageBox> LoginForm::LoginForm(XDCC* nxDCC, QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags), m_xDCC(nxDCC) { ui.setupUi(this); connect(ui.btnLogin, SIGNAL(clicked()), this, SLOT(login())); settings = new QSettings("DotaCash", "DCClient X"); QString oldUsername = settings->value("Username").toString(); if(!oldUsername.isEmpty()) { ui.txtUsername->setText(oldUsername); ui.txtPassword->setFocus(); } ui.webNews->setUrl(QUrl("http://" + API_SERVER + "/api/news.php")); } LoginForm::~LoginForm() { delete settings; //delete fetcher; } void LoginForm::login() { QString Password; Username = ui.txtUsername->text(); Password = ui.txtPassword->text(); if(Username.isEmpty() || Password.isEmpty()) return; ui.txtUsername->setReadOnly(true); ui.txtPassword->setReadOnly(true); ui.btnLogin->setDisabled(true); fetcher = new ApiFetcher(); connect(fetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseLogin(QString&))); QString url = "http://" + API_SERVER + QString("/api/login.php?u=%1&p=%2").arg(Username).arg(Password); fetcher->fetch(url); } void LoginForm::parseLogin(QString& data) { ui.txtUsername->setReadOnly(false); ui.txtPassword->setReadOnly(false); ui.btnLogin->setDisabled(false); xml.clear(); xml.addData(data); QString currentTag; QMap<QString, QString> resultMap; while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { currentTag = xml.name().toString(); } else if (xml.isEndElement()) { if(xml.name() == "user") break; } else if (xml.isCharacters() && !xml.isWhitespace()) { resultMap[currentTag] = xml.text().toString(); } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } if(resultMap["result"] == "1") { QString AccountName = resultMap["accountname"]; quint32 Score = resultMap["score"].toUInt(); quint32 Rank = resultMap["rank"].toUInt(); QString SessionID = resultMap["session"]; settings->setValue("Username", Username); m_xDCC->SetUsername(AccountName); m_xDCC->SetScore(Score); m_xDCC->SetRank(Rank); m_xDCC->SetSessionID(SessionID); m_xDCC->activate(); this->hide(); } else { QMessageBox::information(this, "", QString("%1").arg(resultMap["reason"])); } }
12ayhuang-mac-experiment
loginform.cpp
C++
asf20
3,079
/* Copyright 2011 Trevor Hogan 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. Modified by Gene Chen for Qt compatibility */ #include "gameprotocol.h" #include <QtEndian> #include <QDataStream> #include <QDebug> QByteArray CGameProtocol :: ExtractString( QDataStream& ds ) { QByteArray data; // will hold your data when done quint8 byte; do { // ds is your QDataStream already pointing into your file ds >> byte; data.append(byte); } while (byte != 0); return data; } bool CGameProtocol::AssignLength( QByteArray &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) if( content.size( ) >= 4 && content.size( ) <= 65535 ) { QByteArray LengthBytes; uchar dest[2]; qToLittleEndian<quint16>(content.size(), dest); LengthBytes = QByteArray((char*)dest, 2); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; } bool CGameProtocol::ValidateLength( QByteArray &content ) { // verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length quint16 Length; QByteArray LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes.push_back( content[2] ); LengthBytes.push_back( content[3] ); Length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if( Length == content.size( ) ) return true; } return false; } QByteArray CGameProtocol::DecodeStatString( QByteArray &data ) { quint8 Mask; QByteArray Result; for( int i = 0; i < data.size( ); i++ ) { if( ( i % 8 ) == 0 ) Mask = data[i]; else { if( ( Mask & ( 1 << ( i % 8 ) ) ) == 0 ) Result.push_back( data[i] - 1 ); else Result.push_back( data[i] ); } } return Result; } CGameInfo* CGameProtocol :: RECEIVE_W3GS_GAMEINFO ( QByteArray data ) { if( ValidateLength( data ) && data.size( ) >= 16 ) { QDataStream stream(data); quint32 ProductID; quint32 Version; quint32 HostCounter; quint32 EntryKey; QString GameName; QString GamePassword; QByteArray StatString; quint32 SlotsTotal; quint32 MapGameType; quint32 Unknown2; quint32 SlotsOpen; quint32 UpTime; quint16 Port; stream.skipRawData(4); stream.setByteOrder(QDataStream::LittleEndian); stream >> ProductID; stream >> Version; stream >> HostCounter; stream >> EntryKey; GameName = ExtractString(stream); GamePassword = ExtractString(stream); StatString = ExtractString(stream); stream >> SlotsTotal; stream >> MapGameType; stream >> Unknown2; stream >> SlotsOpen; stream >> UpTime; stream >> Port; QByteArray DecStatString = CGameProtocol::DecodeStatString( StatString ); QDataStream ds(DecStatString); ds.setByteOrder(QDataStream::LittleEndian); ds.skipRawData(5); quint16 MapWidth; quint16 MapHeight; ds >> MapWidth; ds >> MapHeight; bool Reliable = true;//((MapWidth == 1984) && (MapHeight == 1984)); return new CGameInfo(ProductID, Version, HostCounter, EntryKey, GameName, GamePassword, StatString, SlotsTotal, MapGameType, Unknown2, SlotsOpen, UpTime, Port, Reliable); } return false; } QByteArray CGameProtocol :: SEND_W3GS_DECREATEGAME( quint32 entrykey ) { QByteArray packet; QDataStream ds(&packet, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)W3GS_DECREATEGAME; ds << (quint16)0; ds << entrykey; AssignLength( packet ); return packet; } QByteArray CGameProtocol :: SEND_W3GS_CHAT_FROM_HOST( quint8 fromPID, QByteArray toPIDs, quint8 flag, quint32 flagExtra, QString message ) { QByteArray packet; QDataStream ds(&packet, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); if( !toPIDs.isEmpty( ) && !message.isEmpty( ) && message.size( ) < 255 ) { ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)W3GS_CHAT_FROM_HOST; ds << (quint16)0; ds << (quint8)toPIDs.size(); // number of receivers ds.writeRawData(toPIDs.data(), toPIDs.length()); ds << fromPID; ds << flag; if(flagExtra != -1) ds << flagExtra; ds.writeRawData(message.toAscii(), message.length()); ds << (quint8)0; AssignLength( packet ); } // DEBUG_Print( "SENT W3GS_CHAT_FROM_HOST" ); // DEBUG_Print( packet ); return packet; } quint32 CGameInfo::NextUniqueGameID = 1; CGameInfo::CGameInfo(quint32 nProductID, quint32 nVersion, quint32 nHostCounter, quint32 nEntryKey, QString nGameName, QString nGamePassword, QByteArray nStatString, quint32 nSlotsTotal, quint32 nMapGameType, quint32 nUnknown2, quint32 nSlotsOpen, quint32 nUpTime, quint16 nPort, bool nReliable) : ProductID(nProductID), Version(nVersion), HostCounter(nHostCounter), EntryKey(nEntryKey), GameName(nGameName), GamePassword(nGamePassword), StatString(nStatString), SlotsTotal(nSlotsTotal), MapGameType(nMapGameType), Unknown2(nUnknown2), SlotsOpen(nSlotsOpen), UpTime(nUpTime), Port(nPort), Reliable(nReliable) { UniqueGameID = NextUniqueGameID++; } QByteArray CGameInfo::GetPacket(quint16 port) { QByteArray packet; QDataStream ds(&packet, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol :: W3GS_GAMEINFO; ds << (quint16)0; ds << ProductID; ds << Version; ds << UniqueGameID; ds << UniqueGameID; ds.writeRawData(GameName.toUtf8(), GameName.length()); ds << (quint8)0; ds.writeRawData(GamePassword.toUtf8(), GamePassword.length()); ds << (quint8)0; ds.writeRawData(StatString.data(), StatString.length()); ds << SlotsTotal; ds << MapGameType; ds << Unknown2; ds << SlotsOpen; ds << UpTime; ds << port; QByteArray LengthBytes; uchar dest[2]; qToLittleEndian<quint16>(packet.size(), dest); LengthBytes = QByteArray((char*)dest, 2); packet[2] = LengthBytes[0]; packet[3] = LengthBytes[1]; return packet; }
12ayhuang-mac-experiment
gameprotocol.cpp
C++
asf20
6,348
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_UPDATE_H #define XDCC_UPDATE_H #include <QtGui/QMainWindow> #include <QSettings> #include "xdcc.h" #include "ui_xdcc_update.h" class DownloaderForm; class UpdateForm : public QDialog { Q_OBJECT public: UpdateForm(QWidget *parent = 0, Qt::WFlags flags = 0); void checkForUpdates(QString appCastURL, bool alwaysShow); public slots: void parseUpdateData(QString& data); void updateNow(); void beginUpdate(); signals: void updateFromURL(QString&); private: Ui_UpdateDialog ui; DownloaderForm* m_Downloader; QMap<QString,QString> m_Latest; ApiFetcher* m_Fetcher; QString m_Version; bool m_AlwaysShow; QMap<QString, QString> UpdateForm::parseUpdateItem(QXmlStreamReader& xml); void addElementDataToMap(QXmlStreamReader& xml, QMap<QString, QString>& map); bool isUpdateRequired(QString& latestVer); }; #endif // XDCC_UPDATEFORM_H
12ayhuang-mac-experiment
updateform.h
C++
asf20
1,454
/* Copyright 2011 Gene Chen 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. */ #include "ui_xdcc_main.h" #include "channelhandler.h" #include "friendshandler.h" #include <qstringlist.h> #include <IrcUtil> IrcHandler::IrcHandler(QWidget* parent) : QTabWidget(parent), irc(0) { connect(this, SIGNAL(tabCloseRequested(int)), this, SLOT(myCloseTab(int))); QString friendsList = QSettings("DotaCash", "DCClient X", this).value("Friends").toString(); if(!friendsList.isEmpty()) m_Friends = friendsList.toLower().split(";"); } void IrcHandler::connectToIrc(QString name) { m_Username = name; irc = new IrcSession(this); connect(irc, SIGNAL(connected()), this, SLOT(connected())); connect(irc, SIGNAL(disconnected()), this, SLOT(disconnected())); connect(irc, SIGNAL(messageReceived(IrcMessage*)), this, SLOT(messageReceived(IrcMessage*))); irc->setHost("irc.dotacash.com"); irc->setPort(6667); irc->setNickName(m_Username); irc->setUserName("dcclient"); irc->setRealName(m_Username); irc->open(); } void IrcHandler::myCloseTab(int idx) { QString channel = this->tabText(idx); if(channel.startsWith("##") || channel == "#dcchat" || channel == "#dotacash") return; else { if(channel.at(0) == '#') irc->sendCommand(IrcCommand::createPart(channel)); removeTabName(channel); } } void IrcHandler::connected() { emit showMessage(tr("Connected to %1").arg("irc.dotacash.com"), 3000); irc->sendCommand(IrcCommand::createJoin("#dcchat")); irc->sendCommand(IrcCommand::createJoin("#dotacash")); irc->sendCommand(IrcCommand::createJoin(QString("##%1").arg(m_Username))); for(int i = 0; i < m_Friends.size(); ++i) irc->sendCommand(IrcCommand::createJoin(QString("##%1").arg(m_Friends.at(i).toLower()))); } void IrcHandler::disconnected() { for(int i = 0; i < m_ChannelMap.size(); ++i) delete m_ChannelMap.values().at(i); m_ChannelMap.clear(); emit showMessage(tr("Disconnected from %1, reconnecting...").arg("irc.dotacash.com"), 3000); } void IrcHandler::handleChat(QString& origin, QString& Message) { if(!irc) return; if(Message.isEmpty()) return; ChannelHandler* channel = m_ChannelMap[origin.toLower()]; if(Message.startsWith('/')) { QStringList Payload = Message.split(' '); QString Command; Command = Payload.at(0); Payload.pop_front(); if((Command == "/join" || Command == "/j") && !Payload.isEmpty()) { QString JoinChan = Payload.at(0); if(JoinChan.startsWith("##")) return; irc->sendCommand(IrcCommand::createJoin(JoinChan)); } else if(Command == "/part" || Command == "/p") { if(Payload.isEmpty()) { if(origin.startsWith("##") || origin == "#dcchat" || origin == "#dotacash") return; irc->sendCommand(IrcCommand::createPart(origin)); removeTabName(origin.toLower()); } else { if(Payload.at(0).startsWith("##") || Payload.at(0) == "#dcchat" || Payload.at(0) == "#dotacash") return; irc->sendCommand(IrcCommand::createPart(Payload.at(0))); } } else if(Command == "/nick" && !Payload.empty()) { irc->sendCommand(IrcCommand::createNick(Payload.at(0))); irc->setNickName(Payload.at(0)); } else if((Command == "/whisper" || Command == "/w") && Payload.size() >= 2) { QString to = Payload.at(0); Payload.pop_front(); QString& txt = Payload.join(" "); ChannelHandler* handler = m_ChannelMap[to.toLower()]; if(!handler) { handler = new ChannelHandler(false, this); m_ChannelMap[to.toLower()] = handler; this->addTab(handler->GetTab(), to); this->setCurrentIndex(this->count() - 1); } handler->showText(QString("&lt;%1&gt; %2").arg(irc->nickName()).arg(txt)); irc->sendCommand(IrcCommand::createMessage(to, txt)); } else if((Command == "/f" || Command == "/friends") && !Payload.isEmpty()) { if(Payload.at(0) == "l" || Payload.at(0) == "list") { int count = m_FriendsMap.size(); if(!count) showTextCurrentTab(tr("You currently have no friends :("), Err); else { showTextCurrentTab(tr("Your friends are:"), Sys); for(int i = 0; i < count; ++i) { QString friendName = m_FriendsMap.keys().at(i); FriendsHandler* myFriend = m_FriendsMap.values().at(i); if(myFriend) { QString status = myFriend->GetStatus() ? tr("online") : tr("offline"); showTextCurrentTab(QString("%1: %2 - %3").arg(i+1).arg(friendName).arg(status), Sys); } } } } else if(Payload.at(0) == "a") { if(Payload.length() == 1) showTextCurrentTab(tr("You need to supply the name of the friend you wish to add to your list."), Err); else { QString friendName = Payload.at(1).toLower(); if(m_Friends.contains(friendName, Qt::CaseInsensitive)) showTextCurrentTab(tr("%1 is already in your friends list.").arg(friendName), Err); else if(friendName.toLower() == m_Username.toLower()) showTextCurrentTab(tr("You cannot add yourself your friends list."), Err); else { m_Friends << friendName; irc->sendCommand(IrcCommand::createJoin(QString("##%1").arg(friendName))); QSettings("DotaCash", "DCClient X", this).setValue("Friends", m_Friends.join(";")); showTextCurrentTab(tr("Added %1 to your friends list.").arg(friendName), Sys); } } } else if(Payload.at(0) == "r") { if(Payload.length() == 1) showTextCurrentTab(tr("You need to supply the name of the friend you wish to remove from your list."), Err); else { QString friendName = Payload.at(1).toLower(); if(!m_Friends.contains(friendName, Qt::CaseInsensitive)) showTextCurrentTab(tr("%1 is not in your friends list.").arg(friendName), Err); else { int idx = m_Friends.indexOf(friendName); m_Friends.removeAt(idx); irc->sendCommand(IrcCommand::createPart(QString("##%1").arg(friendName))); delete m_FriendsMap[friendName.toLower()]; m_FriendsMap.remove(friendName.toLower()); QSettings("DotaCash", "DCClient X", this).setValue("Friends", m_Friends.join(";")); showTextCurrentTab(tr("Removed %1 from your friends list.").arg(friendName), Sys); } } } else if(Payload.at(0) == "m" || Payload.at(0) == "msg") { if(Payload.length() == 1) showTextCurrentTab(tr("What do you want to say?"), Err); else { Payload.pop_front(); QString msg = Payload.join(" "); irc->sendCommand(IrcCommand::createMessage(QString("##%1").arg(m_Username.toLower()), msg)); showTextCurrentTab(tr("You whisper to your friends: %1").arg(msg), Sys); } } } else { showTextCurrentTab(tr("Invalid command."), Err); } } else { irc->sendCommand(IrcCommand::createMessage(origin.toLower(), Message)); showTextCurrentTab(QString("&lt;%1&gt; %2").arg(irc->nickName()).arg(Message)); } } void IrcHandler::joinedChannel(IrcPrefix origin, IrcJoinMessage* joinMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& channel = joinMsg->channel(); QString nameLower = channel.toLower(); if(user.toLower() == irc->nickName().toLower()) { if(channel.startsWith("##")) { if(nameLower != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[nameLower.mid(2)]; if(!handler) { handler = new FriendsHandler(channel.mid(2), this); m_FriendsMap[nameLower.mid(2)] = handler; } } } else { ChannelHandler* handler = m_ChannelMap[nameLower]; if(!handler) { handler = new ChannelHandler(channel.startsWith('#'), this); m_ChannelMap[nameLower] = handler; this->addTab(handler->GetTab(), channel); int idx = this->count() - 1; if(nameLower == "#dotacash" || nameLower == "#dcchat") this->tabBar()->setTabButton(idx, QTabBar::RightSide, 0); this->setCurrentIndex(idx); } } } else { if(channel.startsWith("##")) { if(nameLower != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[nameLower.mid(2)]; if(handler) handler->joined(user); } } else { ChannelHandler* handler = m_ChannelMap[nameLower]; if(handler) handler->joined(user); } } } void IrcHandler::partedChannel(IrcPrefix origin, IrcPartMessage* partMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& channel = partMsg->channel(); if(user.toLower() == irc->nickName().toLower()) removeTabName(channel.toLower()); else { if(channel.startsWith("##")) { if(channel.toLower() != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[channel.toLower().mid(2)]; if(handler) handler->parted(user, partMsg->reason()); } } else { ChannelHandler* handler = m_ChannelMap[channel.toLower()]; if(handler) handler->parted(user, partMsg->reason()); } } } void IrcHandler::quitMessage(IrcPrefix origin, IrcQuitMessage* quitMsg) { if(!origin.isValid()) return; QString& user = origin.name(); for(QMap<QString, ChannelHandler*>::iterator i = m_ChannelMap.constBegin(); i != m_ChannelMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->parted(user, quitMsg->reason()); } for(QMap<QString, FriendsHandler*>::iterator i = m_FriendsMap.constBegin(); i != m_FriendsMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->parted(user, quitMsg->reason()); } } void IrcHandler::privateMessage(IrcPrefix origin, IrcPrivateMessage* privMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& target = privMsg->target(); QString& message = privMsg->message(); QString txt = QString("<%1> %2").arg(user).arg(message); if(target.startsWith("##")) { if(target.toLower() != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[target.toLower().mid(2)]; if(handler) handler->messageReceived(user, message); } } else { if(target.toLower() != irc->nickName().toLower()) { ChannelHandler* handler = m_ChannelMap[target.toLower()]; if(!handler) { handler = new ChannelHandler(true, this); m_ChannelMap[target.toLower()] = handler; this->addTab(handler->GetTab(), target); this->setCurrentIndex(this->count() - 1); } handler->showText(txt); } else { ChannelHandler* handler = m_ChannelMap[user.toLower()]; if(!handler) { handler = new ChannelHandler(false, this); m_ChannelMap[user.toLower()] = handler; this->addTab(handler->GetTab(), user); this->setCurrentIndex(this->count() - 1); } handler->showText(txt); } } } void IrcHandler::noticeMessage(IrcPrefix origin, IrcNoticeMessage* noticeMsg) { if(!origin.isValid()) return; QString& user = origin.name(); QString& target = noticeMsg->target(); QString& message = noticeMsg->message(); if(target.startsWith("##")) { if(target.toLower() != ("##" + m_Username.toLower())) { FriendsHandler* handler = m_FriendsMap[target.toLower().mid(2)]; if(handler) handler->noticeReceived(user, message); } } else if(target.toLower() != irc->nickName().toLower()) { ChannelHandler* handler = m_ChannelMap[target.toLower()]; if(!handler) { handler = new ChannelHandler(target.startsWith('#'), this); m_ChannelMap[target.toLower()] = handler; this->addTab(handler->GetTab(), target); this->setCurrentIndex(this->count() - 1); } handler->noticeReceived(user, message); } else { QString txt = QString("<span class = \"notice\">-%1- %2</span>").arg(user).arg(IrcUtil::messageToHtml(message)); showTextCurrentTab(txt); } } void IrcHandler::nickMessage(IrcPrefix origin, IrcNickMessage* nickMsg) { if(!origin.isValid()) return; QString& user = origin.name(); if(user == irc->nickName()) irc->setNickName(nickMsg->nick()); for(QMap<QString, ChannelHandler*>::iterator i = m_ChannelMap.constBegin(); i != m_ChannelMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->nickChanged(user, nickMsg->nick()); } for(QMap<QString, FriendsHandler*>::iterator i = m_FriendsMap.constBegin(); i != m_FriendsMap.constEnd(); ++i) { if(!i.key().isEmpty() && (i.value() != NULL)) i.value()->nickChanged(user, nickMsg->nick()); } } void IrcHandler::numericMessage(IrcNumericMessage* numMsg) { int code = numMsg->code(); IrcMessage* msg = numMsg; switch(code) { case Irc::RPL_NAMREPLY: QString& channel = msg->parameters().at(2).toLower(); QStringList names = msg->parameters().at(3).split(' '); if(channel.startsWith("##")) { if(channel.mid(2) != m_Username.toLower()) { FriendsHandler* target = m_FriendsMap[channel.mid(2)]; if(target) { if(names.contains(channel.mid(2), Qt::CaseInsensitive)) target->SetStatus(true); } } } else { ChannelHandler* target = m_ChannelMap[channel]; if(target) target->UpdateNames(names); } break; } } void IrcHandler::messageReceived(IrcMessage *msg) { switch(msg->type()) { case IrcMessage::Join: joinedChannel(msg->prefix(), dynamic_cast<IrcJoinMessage*>(msg)); break; case IrcMessage::Part: partedChannel(msg->prefix(), dynamic_cast<IrcPartMessage*>(msg)); break; case IrcMessage::Quit: quitMessage(msg->prefix(), dynamic_cast<IrcQuitMessage*>(msg)); break; case IrcMessage::Private: privateMessage(msg->prefix(), dynamic_cast<IrcPrivateMessage*>(msg)); break; case IrcMessage::Notice: noticeMessage(msg->prefix(), dynamic_cast<IrcNoticeMessage*>(msg)); break; case IrcMessage::Nick: nickMessage(msg->prefix(), dynamic_cast<IrcNickMessage*>(msg)); break; case IrcMessage::Numeric: numericMessage(dynamic_cast<IrcNumericMessage*>(msg)); break; } } void IrcHandler::removeTabName(QString name) { ChannelHandler* chan = m_ChannelMap[name.toLower()]; if(chan) { for(int i = 0; i < this->count(); i++) { if(this->tabText(i).toLower() == name.toLower()) { this->removeTab(i); break; } } delete chan; m_ChannelMap.remove(name.toLower()); } } void IrcHandler::showTextCurrentTab(QString message, MessageType msgType) { QString channel = this->tabText(this->currentIndex()); ChannelHandler* handler = m_ChannelMap[channel.toLower()]; QString spanClass; switch(msgType) { case Err: spanClass = "err"; break; case Friends: spanClass = "fmsg"; break; case Sys: spanClass = "sysmsg"; break; case Normal: default: spanClass = "msg"; break; } if(handler) handler->showText(QString("<span class=\"%1\">%2</span>").arg(spanClass).arg(message)); } void IrcHandler::reloadSkin() { for(int i = 0; i < m_ChannelMap.count(); ++i) { ChannelHandler* handler = m_ChannelMap.values().at(i); if(handler) handler->reloadSkin(); } } void IrcHandler::joinedGame(QString ip, QString gameName) { irc->sendCommand(IrcCommand::createNotice(QString("##%1").arg(m_Username.toLower()), QString("xdcc://%1;%2").arg(ip).arg(gameName))); } void IrcHandler::handleUrl(QUrl url) { QString data = url.toString(); if(data.startsWith("xdcc://")) { emit requestGame(data.mid(7)); } }
12ayhuang-mac-experiment
irchandler.cpp
C++
asf20
15,650
/* Copyright 2011 Trevor Hogan 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. Modified by Gene Chen for Qt compatibility */ #ifndef GAMEPROTOCOL_H #define GAMEPROTOCOL_H #include <QByteArray> #include <QString> // // CGameProtocol // #define W3GS_HEADER_CONSTANT 247 #define GAME_NONE 0 // this case isn't part of the protocol, it's for internal use only #define GAME_FULL 2 #define GAME_PUBLIC 16 #define GAME_PRIVATE 17 #define GAMETYPE_CUSTOM 1 #define GAMETYPE_BLIZZARD 9 #define PLAYERLEAVE_DISCONNECT 1 #define PLAYERLEAVE_LOST 7 #define PLAYERLEAVE_LOSTBUILDINGS 8 #define PLAYERLEAVE_WON 9 #define PLAYERLEAVE_DRAW 10 #define PLAYERLEAVE_OBSERVER 11 #define PLAYERLEAVE_LOBBY 13 #define PLAYERLEAVE_GPROXY 100 #define REJECTJOIN_FULL 9 #define REJECTJOIN_STARTED 10 #define REJECTJOIN_WRONGPASSWORD 27 class CGameInfo; class CGameProtocol { public: enum Protocol { W3GS_PING_FROM_HOST = 1, // 0x01 W3GS_SLOTINFOJOIN = 4, // 0x04 W3GS_REJECTJOIN = 5, // 0x05 W3GS_PLAYERINFO = 6, // 0x06 W3GS_PLAYERLEAVE_OTHERS = 7, // 0x07 W3GS_GAMELOADED_OTHERS = 8, // 0x08 W3GS_SLOTINFO = 9, // 0x09 W3GS_COUNTDOWN_START = 10, // 0x0A W3GS_COUNTDOWN_END = 11, // 0x0B W3GS_INCOMING_ACTION = 12, // 0x0C W3GS_CHAT_FROM_HOST = 15, // 0x0F W3GS_START_LAG = 16, // 0x10 W3GS_STOP_LAG = 17, // 0x11 W3GS_HOST_KICK_PLAYER = 28, // 0x1C W3GS_REQJOIN = 30, // 0x1E W3GS_LEAVEGAME = 33, // 0x21 W3GS_GAMELOADED_SELF = 35, // 0x23 W3GS_OUTGOING_ACTION = 38, // 0x26 W3GS_OUTGOING_KEEPALIVE = 39, // 0x27 W3GS_CHAT_TO_HOST = 40, // 0x28 W3GS_DROPREQ = 41, // 0x29 W3GS_SEARCHGAME = 47, // 0x2F (UDP/LAN) W3GS_GAMEINFO = 48, // 0x30 (UDP/LAN) W3GS_CREATEGAME = 49, // 0x31 (UDP/LAN) W3GS_REFRESHGAME = 50, // 0x32 (UDP/LAN) W3GS_DECREATEGAME = 51, // 0x33 (UDP/LAN) W3GS_CHAT_OTHERS = 52, // 0x34 W3GS_PING_FROM_OTHERS = 53, // 0x35 W3GS_PONG_TO_OTHERS = 54, // 0x36 W3GS_MAPCHECK = 61, // 0x3D W3GS_STARTDOWNLOAD = 63, // 0x3F W3GS_MAPSIZE = 66, // 0x42 W3GS_MAPPART = 67, // 0x43 W3GS_MAPPARTOK = 68, // 0x44 W3GS_MAPPARTNOTOK = 69, // 0x45 - just a guess, received this packet after forgetting to send a crc in W3GS_MAPPART (f7 45 0a 00 01 02 01 00 00 00) W3GS_PONG_TO_HOST = 70, // 0x46 W3GS_INCOMING_ACTION2 = 72 // 0x48 - received this packet when there are too many actions to fit in W3GS_INCOMING_ACTION }; static bool AssignLength( QByteArray &content ); static bool ValidateLength( QByteArray &content ); static QByteArray ExtractString( QDataStream& ds ); static QByteArray DecodeStatString(QByteArray& ); CGameInfo* RECEIVE_W3GS_GAMEINFO( QByteArray data ); QByteArray SEND_W3GS_CHAT_FROM_HOST( quint8 fromPID, QByteArray toPIDs, quint8 flag, quint32 flagExtra, QString message ); QByteArray SEND_W3GS_DECREATEGAME( quint32 ); }; class CGameInfo { public: static quint32 NextUniqueGameID; public: CGameInfo(quint32 nProductID, quint32 nVersion, quint32 nHostCounter, quint32 nEntryKey, QString nGameName, QString nGamePassword, QByteArray nStatString, quint32 nSlotsTotal, quint32 nMapGameType, quint32 nUnknown2, quint32 nSlotsOpen, quint32 nUpTime, quint16 nPort, bool Reliable); quint32 GetProductID() { return ProductID; } quint32 GetVersion() { return Version; } quint32 GetHostCounter() { return HostCounter; } quint32 GetEntryKey() { return EntryKey; } QString GetGameName() { return GameName; } QString GetGamePassword() { return GamePassword; } QByteArray GetStatString() { return StatString; } quint32 GetSlotsTotal() { return SlotsTotal; } quint32 GetMapGameType() { return MapGameType; } quint32 GetSlotsOpen() { return SlotsOpen; } quint32 GetUpTime() { return UpTime; } quint16 GetPort() { return Port; } QString GetIP() { return IP; } quint32 GetUniqueGameID() { return UniqueGameID; } bool GetReliable() { return Reliable; } void SetProductID( quint32 nProductID ) { ProductID = nProductID; } void SetVersion( quint32 nVersion ) { Version = nVersion; } void SetHostCounter( quint32 nHostCounter ) { HostCounter = nHostCounter; } void SetGameName( QString nGameName ) { GameName = nGameName; } void SetGamePassword( QString nGamePassword ) { GamePassword = nGamePassword; } void SetStatString( QByteArray nStatString ) { StatString = nStatString; } void SetSlotsTotal( quint32 nSlotsTotal ) { SlotsTotal = nSlotsTotal; } void SetMapGameType( quint32 nMapGameType ) { MapGameType = nMapGameType; } void SetSlotsOpen( quint32 nSlotsOpen ) { SlotsOpen = nSlotsOpen; } void SetUpTime( quint32 nUpTime ) { UpTime = nUpTime; } void SetPort( quint16 nPort ) { Port = nPort; } void SetIP( QString nIP ) { IP = nIP; } QByteArray GetPacket(quint16); private: quint32 ProductID; quint32 Version; quint32 HostCounter; quint32 EntryKey; QString GameName; QString GamePassword; QByteArray StatString; quint32 SlotsTotal; quint32 MapGameType; quint32 Unknown2; quint32 SlotsOpen; quint32 UpTime; quint16 Port; QString IP; quint32 UniqueGameID; bool Reliable; }; #endif
12ayhuang-mac-experiment
gameprotocol.h
C++
asf20
5,668
/* Copyright 2011 Gene Chen 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. With code derived from gproxy: http://code.google.com/p/gproxyplusplus/ */ #ifndef QGPROXY_H #define QGPROXY_H #include "xdcc.h" #include <QQueue> #include <QTcpSocket> #include <QTcpServer> #include <QUdpSocket> class CGameInfo; class CGameProtocol; class CCommandPacket; class CGPSProtocol; class CGProxy : public QObject { Q_OBJECT public: CGProxy(QWidget* parent=0); ~CGProxy(); void requestGame(QString ip); const QVector<CGameInfo*> getGames() { return games; } public slots: void update(); void readPendingDatagrams(); void newConnection(); void readLocalPackets(); void readServerPackets(); void localDisconnected(); void remoteDisconnected(); signals: void joinedGame(QString, QString); private: QUdpSocket* m_RequesterSocket; QTcpServer* m_LocalServer; QTcpSocket* m_RemoteSocket; QTcpSocket* m_LocalSocket; CGameProtocol* m_GameProtocol; QVector<CGameInfo*> games; CGPSProtocol *m_GPSProtocol; QTimer* timer; QString m_RemoteServerIP; QByteArray m_RemoteBytes; QByteArray m_LocalBytes; QQueue<CCommandPacket *> m_LocalPackets; QQueue<CCommandPacket *> m_RemotePackets; QQueue<CCommandPacket *> m_PacketBuffer; QVector<quint8> m_Laggers; quint32 m_TotalPacketsReceivedFromLocal; quint32 m_TotalPacketsReceivedFromRemote; quint32 m_LastAckTime; quint32 m_LastActionTime; quint32 m_LastConnectionAttemptTime; quint32 m_ReconnectKey; quint32 m_LastBroadcastTime; quint16 m_ListenPort; quint16 m_ReconnectPort; quint8 m_PID; quint8 m_ChatPID; quint8 m_NumEmptyActions; quint8 m_NumEmptyActionsUsed; bool m_ActionReceived; bool m_GameIsReliable; bool m_GameStarted; bool m_Synchronized; bool m_LeaveGameSent; void parsePacket(QString, QByteArray); void processLocalPackets(); void processServerPackets(); void SendLocalChat( QString message ); void SendEmptyAction( ); }; #endif
12ayhuang-mac-experiment
qgproxy.h
C++
asf20
2,451
/* Copyright 2011 Gene Chen 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. With code derived from gproxy: http://code.google.com/p/gproxyplusplus/ */ #include "qgproxy.h" #include "gpsprotocol.h" #include "gameprotocol.h" #include "commandpacket.h" #include <QSettings> #include <QSound> #include <QtEndian> #include <time.h> #ifdef WIN32 #include <windows.h> #endif #ifndef WIN32 #include <sys/time.h> #endif #ifdef __APPLE__ #include <mach/mach_time.h> #endif quint32 GetTicks( ) { #ifdef WIN32 return timeGetTime( ); #elif __APPLE__ uint64_t current = mach_absolute_time( ); static mach_timebase_info_data_t info = { 0, 0 }; // get timebase info if( info.denom == 0 ) mach_timebase_info( &info ); uint64_t elapsednano = current * ( info.numer / info.denom ); // convert ns to ms return elapsednano / 1e6; #else uint32_t ticks; struct timespec t; clock_gettime( 1, &t ); ticks = t.tv_sec * 1000; ticks += t.tv_nsec / 1000000; return ticks; #endif } quint32 GetTime( ) { return GetTicks( ) / 1000; } CGProxy::CGProxy(QWidget* parent) : QObject(parent), m_LocalSocket(0) { m_LocalServer = new QTcpServer(this); m_ListenPort = 6125; while(!m_LocalServer->listen(QHostAddress::LocalHost, m_ListenPort)) m_ListenPort++; connect(m_LocalServer, SIGNAL(newConnection()), this, SLOT(newConnection())); m_RequesterSocket = new QUdpSocket(this); m_RequesterSocket->bind(m_ListenPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint); connect(m_RequesterSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); m_GameProtocol = new CGameProtocol(); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(update())); timer->start(30); m_TotalPacketsReceivedFromLocal = 0; m_TotalPacketsReceivedFromRemote = 0; m_LastConnectionAttemptTime = 0; m_GameIsReliable = false; m_GameStarted = false; m_LeaveGameSent = false; m_ActionReceived = false; m_Synchronized = true; m_ReconnectPort = 0; m_PID = 255; m_ChatPID = 255; m_ReconnectKey = 0; m_NumEmptyActions = 0; m_NumEmptyActionsUsed = 0; m_LastAckTime = 0; m_LastActionTime = 0; m_LastBroadcastTime = 0; m_RemoteSocket = new QTcpSocket(this); connect(m_RemoteSocket, SIGNAL(disconnected()), this, SLOT(remoteDisconnected())); connect(m_RemoteSocket, SIGNAL(readyRead()), this, SLOT(readServerPackets())); } CGProxy::~CGProxy() { m_LocalServer->close(); for( QVector<CGameInfo*>::iterator i = games.begin( ); i != games.end( ); ++i ) m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); while( !games.empty( ) ) { delete games.front( ); games.pop_front( ); } while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } while( !m_PacketBuffer.empty( ) ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); } delete m_RemoteSocket; delete m_GameProtocol; } void CGProxy::update() { processLocalPackets(); processServerPackets(); if( !m_RemoteServerIP.isEmpty( ) && m_LocalSocket != NULL && m_LocalSocket->state() == QTcpSocket::ConnectedState ) { if( m_GameIsReliable && m_ActionReceived && GetTime( ) - m_LastActionTime >= 60 ) { if( m_NumEmptyActionsUsed < m_NumEmptyActions ) { SendEmptyAction( ); m_NumEmptyActionsUsed++; } else { SendLocalChat( "GProxy++ ran out of time to reconnect, Warcraft III will disconnect soon." ); qDebug() << ( "[GPROXY] ran out of time to reconnect" ); m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } m_LastActionTime = GetTime( ); } if( m_RemoteSocket->state() == QTcpSocket::ConnectedState ) { if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 && GetTime( ) - m_LastAckTime >= 10 ) { m_RemoteSocket->write( m_GPSProtocol->SEND_GPSC_ACK( m_TotalPacketsReceivedFromRemote ) ); m_LastAckTime = GetTime( ); } } if( m_RemoteSocket->state() != QTcpSocket::ConnectingState && m_RemoteSocket->state() != QTcpSocket::ConnectedState ) { if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 ) { if(GetTime( ) - m_LastConnectionAttemptTime >= 10) { SendLocalChat( "You have been disconnected from the server." ); quint32 TimeRemaining = ( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 - ( GetTime( ) - m_LastActionTime ); if( GetTime( ) - m_LastActionTime > quint32( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 ) TimeRemaining = 0; SendLocalChat( tr("GProxy++ is attempting to reconnect... (%1 seconds remain)").arg(TimeRemaining) ); qDebug() << ( "[GPROXY] attempting to reconnect" ); m_RemoteSocket->reset(); m_RemoteSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_RemoteSocket->connectToHost( m_RemoteServerIP, m_ReconnectPort ); m_LastConnectionAttemptTime = GetTime( ); } } else { m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } } if( m_RemoteSocket->state() == QTcpSocket::ConnectingState ) { // we are currently attempting to connect if( m_RemoteSocket->waitForConnected(10000) ) { // the connection attempt completed if( m_GameIsReliable && m_ActionReceived ) { // this is a reconnection, not a new connection // if the server accepts the reconnect request it will send a GPS_RECONNECT back requesting a certain number of packets SendLocalChat( "GProxy++ reconnected to the server!" ); SendLocalChat( "==================================================" ); qDebug() << ( "[GPROXY] reconnected to remote server" ); // note: even though we reset the socket when we were disconnected, we haven't been careful to ensure we never queued any data in the meantime // therefore it's possible the socket could have data in the send buffer // this is bad because the server will expect us to send a GPS_RECONNECT message first // so we must clear the send buffer before we continue // note: we aren't losing data here, any important messages that need to be sent have been put in the packet buffer // they will be requested by the server if required //m_RemoteSocket->; m_RemoteSocket->write( m_GPSProtocol->SEND_GPSC_RECONNECT( m_PID, m_ReconnectKey, m_TotalPacketsReceivedFromRemote ) ); // we cannot permit any forwarding of local packets until the game is synchronized again // this will disable forwarding and will be reset when the synchronization is complete m_Synchronized = false; } else qDebug() << ( "[GPROXY] connected to remote server" ); } else if( GetTime( ) - m_LastConnectionAttemptTime >= 10 ) { // the connection attempt timed out (10 seconds) qDebug() << ( "[GPROXY] connect to remote server timed out" ); if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 ) { quint32 TimeRemaining = ( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 - ( GetTime( ) - m_LastActionTime ); if( GetTime( ) - m_LastActionTime > quint32( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 ) TimeRemaining = 0; SendLocalChat( tr("GProxy++ is attempting to reconnect... (%1 seconds remain)").arg(TimeRemaining) ); qDebug() << ( "[GPROXY] attempting to reconnect" ); m_RemoteSocket->connectToHost( m_RemoteServerIP, m_ReconnectPort ); m_LastConnectionAttemptTime = GetTime( ); } else { m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } } } } if(!m_LocalSocket || m_LocalSocket->state() != QTcpSocket::ConnectedState || m_RemoteSocket->state() != QTcpSocket::ConnectedState) { if( GetTime( ) - m_LastBroadcastTime >= 3 ) { for(QVector<CGameInfo*>::const_iterator i = games.constBegin(); i != games.constEnd(); ++i) m_RequesterSocket->writeDatagram((*i)->GetPacket(m_ListenPort), QHostAddress::LocalHost, 6112); m_LastBroadcastTime = GetTime( ); } } } void CGProxy::newConnection() { QTcpSocket* newClient = m_LocalServer->nextPendingConnection(); if(m_LocalSocket) { newClient->disconnectFromHost(); return; } while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } while( !m_PacketBuffer.empty( ) ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); } newClient->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_TotalPacketsReceivedFromLocal = 0; m_TotalPacketsReceivedFromRemote = 0; m_LastConnectionAttemptTime = 0; m_GameIsReliable = false; m_GameStarted = false; m_LeaveGameSent = false; m_ActionReceived = false; m_Synchronized = true; m_ReconnectPort = 0; m_PID = 255; m_ChatPID = 255; m_ReconnectKey = 0; m_NumEmptyActions = 0; m_NumEmptyActionsUsed = 0; m_LastAckTime = 0; m_LastActionTime = 0; m_LocalSocket = newClient; connect(m_LocalSocket, SIGNAL(disconnected()), this, SLOT(localDisconnected())); connect(m_LocalSocket, SIGNAL(disconnected()), m_LocalSocket, SLOT(deleteLater())); connect(m_LocalSocket, SIGNAL(readyRead()), this, SLOT(readLocalPackets())); } void CGProxy::localDisconnected() { if( m_GameIsReliable && !m_LeaveGameSent && m_RemoteSocket->state() == QTcpSocket::ConnectedState) { // note: we're not actually 100% ensuring the leavegame message is sent, we'd need to check that DoSend worked, etc... QByteArray LeaveGame; QDataStream ds(&LeaveGame, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_LEAVEGAME; ds << (quint16)0x08; ds << (quint32)PLAYERLEAVE_GPROXY; m_RemoteSocket->write( LeaveGame ); m_RemoteSocket->waitForBytesWritten(); m_LeaveGameSent = true; } m_RemoteSocket->disconnectFromHost(); m_LocalSocket = NULL; m_RemoteBytes.clear(); m_LocalBytes.clear(); while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } while( !m_PacketBuffer.empty( ) ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); } } void CGProxy::remoteDisconnected() { while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } if(m_LeaveGameSent) return; if(m_LocalSocket == NULL || m_LocalSocket->state() != QTcpSocket::ConnectedState) { return; } qDebug() << ( "[GPROXY] disconnected from remote server due to socket error" ); if( m_GameIsReliable && m_ActionReceived && m_ReconnectPort > 0 ) { SendLocalChat( "You have been disconnected from the server due to a socket error." ); quint32 TimeRemaining = ( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 - ( GetTime( ) - m_LastActionTime ); if( GetTime( ) - m_LastActionTime > quint32( m_NumEmptyActions - m_NumEmptyActionsUsed + 1 ) * 60 ) TimeRemaining = 0; SendLocalChat( tr("GProxy++ is attempting to reconnect... (%1 seconds remain)").arg(TimeRemaining) ); qDebug() << ( "[GPROXY] attempting to reconnect" ); m_RemoteSocket->reset(); m_RemoteSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_RemoteSocket->connectToHost( m_RemoteServerIP, m_ReconnectPort ); m_LastConnectionAttemptTime = GetTime( ); } else { m_LocalSocket->disconnectFromHost( ); m_RemoteServerIP.clear( ); } } void CGProxy::readLocalPackets() { QByteArray bytes = m_LocalSocket->readAll(); m_LocalBytes += bytes; while( m_LocalBytes.size( ) >= 4 ) { if( m_LocalBytes.at(0) == W3GS_HEADER_CONSTANT ) { QByteArray LengthBytes; LengthBytes.push_back( m_LocalBytes[2] ); LengthBytes.push_back( m_LocalBytes[3] ); quint16 length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if(length >= 4) { if( m_LocalBytes.size( ) >= length ) { QByteArray data = QByteArray(m_LocalBytes, length); QDataStream ds(data); bool forward = true; if( m_LocalBytes.at(1) == CGameProtocol :: W3GS_CHAT_TO_HOST ) { if( data.size( ) >= 5 ) { int i = 5; char Total = data[4]; if( Total > 0 && data.size( ) >= i + Total ) { i += Total; unsigned char Flag = data[i + 1]; i += 2; QString MessageString; if( Flag == 16 && data.size( ) >= i + 1 ) { ds.skipRawData(i); MessageString = CGameProtocol :: ExtractString(ds); } else if( Flag == 32 && data.size( ) >= i + 5 ) { ds.skipRawData(i+4); MessageString = CGameProtocol :: ExtractString(ds); } QString Command = MessageString.toLower(); if( Command.size( ) >= 1 && Command.at(0) == '/' ) { forward = false; if( Command.size( ) >= 5 && Command.mid( 0, 4 ) == "/re " ) { // if( m_BNET->GetLoggedIn( ) ) // { // //if( !m_BNET->GetReplyTarget( ).empty( ) ) // { // //m_BNET->QueueChatCommand( MessageString.substr( 4 ), m_BNET->GetReplyTarget( ), true ); // SendLocalChat( "Whispered to " + m_BNET->GetReplyTarget( ) + ": " + MessageString.substr( 4 ) ); // } // else // SendLocalChat( "Nobody has whispered you yet." ); // } // else // SendLocalChat( "You are not connected to battle.net." ); } else if( Command == "/status" ) { if( m_LocalSocket ) { if( m_GameIsReliable && m_ReconnectPort > 0 ) SendLocalChat( "GProxy++ disconnect protection: enabled" ); else SendLocalChat( "GProxy++ disconnect protection: disabled" ); } } } } } } if( forward ) { m_LocalPackets.push_back( new CCommandPacket( W3GS_HEADER_CONSTANT, m_LocalBytes[1], data ) ); m_PacketBuffer.push_back( new CCommandPacket( W3GS_HEADER_CONSTANT, m_LocalBytes[1], data ) ); m_TotalPacketsReceivedFromLocal++; } m_LocalBytes = QByteArray(m_LocalBytes.begin( ) + length, m_LocalBytes.size() - length); } else return; } else { qDebug() << "[GPROXY] received invalid packet from local player (bad length)"; m_LeaveGameSent = true; m_LocalSocket->disconnectFromHost( ); return; } } else { qDebug() << ( "[GPROXY] received invalid packet from local player (bad header constant)" ); m_LeaveGameSent = true; m_LocalSocket->disconnectFromHost( ); return; } } processLocalPackets(); } void CGProxy::processLocalPackets() { if(!m_LocalSocket || m_LocalSocket->state() != QTcpSocket::ConnectedState) return; while( !m_LocalPackets.empty( ) ) { CCommandPacket *Packet = m_LocalPackets.front( ); m_LocalPackets.pop_front( ); QByteArray Data = Packet->GetData( ); QDataStream ds(Data); ds.setByteOrder(QDataStream::LittleEndian); if( Packet->GetPacketType( ) == W3GS_HEADER_CONSTANT ) { if( Packet->GetID( ) == CGameProtocol :: W3GS_REQJOIN ) { if( Data.size( ) >= 20 ) { quint32 HostCounter; quint32 EntryKey; quint8 Unknown; quint16 ListenPort; quint32 PeerKey; QString Name; QByteArray Remainder; ds.skipRawData(4); ds >> HostCounter; ds >> EntryKey; ds >> Unknown; ds >> ListenPort; ds >> PeerKey; Name = CGameProtocol::ExtractString(ds); Remainder = QByteArray(Data.begin() + Name.size() + 20, Data.size() - (Name.size() + 20)); if(Remainder.size( ) == 18) { bool GameFound = false; for(QVector<CGameInfo*>::iterator i = games.begin( ); i != games.end( ); ++i) { if((*i)->GetUniqueGameID() == EntryKey) { m_RemoteSocket->reset(); m_RemoteSocket->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_RemoteSocket->connectToHost((*i)->GetIP(), (*i)->GetPort()); if(!m_RemoteSocket->waitForConnected(3000)) { qDebug() << "[GPROXY] player requested to join an expired game. removing from list."; m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); delete (*i); games.erase(i); break; } m_LastConnectionAttemptTime = GetTime(); m_RemoteServerIP = (*i)->GetIP(); m_GameIsReliable = (*i)->GetReliable(); m_GameStarted = false; QByteArray DataRewritten; QDataStream ds(&DataRewritten, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)Packet->GetID(); ds << (quint16)0; ds << (*i)->GetHostCounter(); ds << (*i)->GetEntryKey(); ds << (quint8)Unknown; ds << (quint16)ListenPort; ds << (quint32)PeerKey; ds.writeRawData(Name.toUtf8(), Name.length()); ds << (quint8)0; ds.writeRawData(Remainder.data(), Remainder.length()); CGameProtocol::AssignLength(DataRewritten); Data = DataRewritten; GameFound = true; emit joinedGame((*i)->GetIP(), (*i)->GetGameName()); break; } } if(!GameFound) { qDebug() << "[GPROXY] local player requested unknown game (expired?) sending decreate."; m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME(EntryKey), QHostAddress::Broadcast, 6112); m_LocalSocket->disconnectFromHost(); } } else qDebug() << "[GPROXY] received invalid join request from local player (invalid remainder)"; } else qDebug() << "[GPROXY] received invalid join request from local player (too short)"; } else if(Packet->GetID( ) == CGameProtocol :: W3GS_LEAVEGAME) { QByteArray LeaveGame; QDataStream ds(&LeaveGame, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_LEAVEGAME; ds << (quint16)0x08; ds << (quint32)0x00; m_RemoteSocket->write( LeaveGame ); m_RemoteSocket->waitForBytesWritten(); m_LeaveGameSent = true; m_LocalSocket->disconnectFromHost(); } } if( m_RemoteSocket && m_Synchronized ) m_RemoteSocket->write(Data); delete Packet; } } void CGProxy::readServerPackets() { QByteArray bytes = m_RemoteSocket->readAll(); m_RemoteBytes += bytes; while( m_RemoteBytes.size( ) >= 4 ) { if( m_RemoteBytes.at(0) == W3GS_HEADER_CONSTANT || m_RemoteBytes.at(0) == GPS_HEADER_CONSTANT ) { QByteArray LengthBytes; LengthBytes.push_back( m_RemoteBytes[2] ); LengthBytes.push_back( m_RemoteBytes[3] ); quint16 length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if( length >= 4 ) { if( m_RemoteBytes.size( ) >= length ) { QByteArray data = QByteArray(m_RemoteBytes.begin(), length); m_RemotePackets.push_back(new CCommandPacket( m_RemoteBytes.at(0), m_RemoteBytes.at(1), data )); if( m_RemoteBytes.at(0) == W3GS_HEADER_CONSTANT ) m_TotalPacketsReceivedFromRemote++; m_RemoteBytes = QByteArray(m_RemoteBytes.begin( ) + length, m_RemoteBytes.size() - length); } else return; } else { qDebug() << "[GPROXY] received invalid packet from remote server (bad length)"; m_RemoteSocket->disconnectFromHost(); return; } } else { qDebug() << "[GPROXY] received invalid packet from remote server (bad header constant)"; m_RemoteSocket->disconnectFromHost(); return; } } processServerPackets(); } void CGProxy::processServerPackets() { if(!m_LocalSocket || m_LocalSocket->state() != QTcpSocket::ConnectedState || m_RemoteSocket->state() != QTcpSocket::ConnectedState) return; while( !m_RemotePackets.empty( ) ) { CCommandPacket *Packet = m_RemotePackets.front( ); m_RemotePackets.pop_front( ); QByteArray Data = Packet->GetData( ); QDataStream ds(Data); ds.setByteOrder(QDataStream::LittleEndian); ds.skipRawData(4); if( Packet->GetPacketType( ) == W3GS_HEADER_CONSTANT ) { if( Packet->GetID( ) == CGameProtocol :: W3GS_SLOTINFOJOIN ) { if( Data.size( ) >= 6 ) { quint16 SlotInfoSize; ds >> SlotInfoSize; if( Data.size( ) >= 7 + SlotInfoSize ) m_ChatPID = Data[6 + SlotInfoSize]; } // send a GPS_INIT packet // if the server doesn't recognize it (e.g. it isn't GHost++) we should be kicked qDebug() << ( "[GPROXY] join request accepted by remote server" ); if( m_GameIsReliable ) { qDebug() << ( "[GPROXY] detected reliable game, starting GPS handshake" ); m_RemoteSocket->write( m_GPSProtocol->SEND_GPSC_INIT( 1 ) ); } else qDebug() << ( "[GPROXY] detected standard game, disconnect protection disabled" ); } else if( Packet->GetID( ) == CGameProtocol :: W3GS_COUNTDOWN_END ) { if( m_GameIsReliable && m_ReconnectPort > 0 ) qDebug() << ( "[GPROXY] game started, disconnect protection enabled" ); else { if( m_GameIsReliable ) qDebug() << ( "[GPROXY] game started but GPS handshake not complete, disconnect protection disabled" ); else qDebug() << ( "[GPROXY] game started" ); } for( QVector<CGameInfo*>::iterator i = games.begin( ); i != games.end( ); ++i ) m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); while( !games.empty( ) ) { delete games.front( ); games.pop_front( ); } QSettings settings("DotaCash", "DCClient X"); if(settings.value("GameStartedSound", true).toBool()) QSound::play("./sounds/GameStarted.wav"); m_GameStarted = true; } else if( Packet->GetID( ) == CGameProtocol :: W3GS_INCOMING_ACTION ) { if( m_GameIsReliable ) { // we received a game update which means we can reset the number of empty actions we have to work with // we also must send any remaining empty actions now // note: the lag screen can't be up right now otherwise the server made a big mistake, so we don't need to check for it QByteArray EmptyAction; EmptyAction.append( (char)0xF7 ); EmptyAction.append( (char)0x0C ); EmptyAction.append( (char)0x06 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); for( unsigned char i = m_NumEmptyActionsUsed; i < m_NumEmptyActions; i++ ) m_LocalSocket->write( EmptyAction ); m_NumEmptyActionsUsed = 0; } m_ActionReceived = true; m_LastActionTime = GetTime( ); } else if( Packet->GetID( ) == CGameProtocol :: W3GS_START_LAG ) { if( m_GameIsReliable ) { QByteArray Data = Packet->GetData( ); if( Data.size( ) >= 5 ) { quint8 NumLaggers = Data[4]; if( Data.size( ) == 5 + NumLaggers * 5 ) { for( quint8 i = 0; i < NumLaggers; i++ ) { bool LaggerFound = false; for( QVector<quint8>::iterator j = m_Laggers.begin( ); j != m_Laggers.end( ); j++ ) { if( *j == Data[5 + i * 5] ) LaggerFound = true; } if( LaggerFound ) qDebug() << ( "[GPROXY] warning - received start_lag on known lagger" ); else m_Laggers.push_back( Data[5 + i * 5] ); } } else qDebug() << ( "[GPROXY] warning - unhandled start_lag (2)" ); } else qDebug() << ( "[GPROXY] warning - unhandled start_lag (1)" ); } } else if( Packet->GetID( ) == CGameProtocol :: W3GS_STOP_LAG ) { if( m_GameIsReliable ) { QByteArray Data = Packet->GetData( ); if( Data.size( ) == 9 ) { bool LaggerFound = false; for( QVector<quint8>::iterator i = m_Laggers.begin( ); i != m_Laggers.end( ); ) { if( *i == Data[4] ) { i = m_Laggers.erase( i ); LaggerFound = true; } else i++; } if( !LaggerFound ) qDebug() << ( "[GPROXY] warning - received stop_lag on unknown lagger" ); } else qDebug() << ( "[GPROXY] warning - unhandled stop_lag" ); } } else if( Packet->GetID( ) == CGameProtocol :: W3GS_INCOMING_ACTION2 ) { if( m_GameIsReliable ) { // we received a fractured game update which means we cannot use any empty actions until we receive the subsequent game update // we also must send any remaining empty actions now // note: this means if we get disconnected right now we can't use any of our buffer time, which would be very unlucky // it still gives us 60 seconds total to reconnect though // note: the lag screen can't be up right now otherwise the server made a big mistake, so we don't need to check for it QByteArray EmptyAction; EmptyAction.append( (char)0xF7 ); EmptyAction.append( (char)0x0C ); EmptyAction.append( (char)0x06 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); for( unsigned char i = m_NumEmptyActionsUsed; i < m_NumEmptyActions; i++ ) m_LocalSocket->write( EmptyAction ); m_NumEmptyActionsUsed = m_NumEmptyActions; } } // forward the data m_LocalSocket->write( Packet->GetData( ) ); // we have to wait until now to send the status message since otherwise the slotinfojoin itself wouldn't have been forwarded if( Packet->GetID( ) == CGameProtocol :: W3GS_SLOTINFOJOIN ) { if( m_GameIsReliable ) SendLocalChat( tr("This is a reliable game. Requesting GProxy++ disconnect protection from server...") ); else SendLocalChat( tr("This is an unreliable game. GProxy++ disconnect protection is disabled.") ); } } else if( Packet->GetPacketType( ) == GPS_HEADER_CONSTANT ) { if( m_GameIsReliable ) { QByteArray Data = Packet->GetData( ); if( Packet->GetID( ) == CGPSProtocol :: GPS_INIT && Data.size( ) == 12 ) { ds >> m_ReconnectPort; ds >> m_PID; ds >> m_ReconnectKey; ds >> m_NumEmptyActions; SendLocalChat( tr("GProxy++ disconnect protection is ready (%1 second buffer).").arg( ( m_NumEmptyActions + 1 ) * 60 ) ); } else if( Packet->GetID( ) == CGPSProtocol :: GPS_RECONNECT && Data.size( ) == 8 ) { quint32 LastPacket; ds >> LastPacket; quint32 PacketsAlreadyUnqueued = m_TotalPacketsReceivedFromLocal - m_PacketBuffer.size( ); if( LastPacket > PacketsAlreadyUnqueued ) { int PacketsToUnqueue = LastPacket - PacketsAlreadyUnqueued; if( PacketsToUnqueue > m_PacketBuffer.size( ) ) { qDebug() << ( "[GPROXY] received GPS_RECONNECT with last packet > total packets sent" ); PacketsToUnqueue = m_PacketBuffer.size( ); } while( PacketsToUnqueue > 0 ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); PacketsToUnqueue--; } } // send remaining packets from buffer, preserve buffer // note: any packets in m_LocalPackets are still sitting at the end of this buffer because they haven't been processed yet // therefore we must check for duplicates otherwise we might (will) cause a desync QQueue<CCommandPacket *> TempBuffer; while( !m_PacketBuffer.empty( ) ) { if( m_PacketBuffer.size( ) > m_LocalPackets.size( ) ) m_RemoteSocket->write( m_PacketBuffer.front( )->GetData( ) ); TempBuffer.push_back( m_PacketBuffer.front( ) ); m_PacketBuffer.pop_front( ); } m_PacketBuffer = TempBuffer; // we can resume forwarding local packets again // doing so prior to this point could result in an out-of-order stream which would probably cause a desync m_Synchronized = true; } else if( Packet->GetID( ) == CGPSProtocol :: GPS_ACK && Data.size( ) == 8 ) { quint32 LastPacket; ds >> LastPacket; quint32 PacketsAlreadyUnqueued = m_TotalPacketsReceivedFromLocal - m_PacketBuffer.size( ); if( LastPacket > PacketsAlreadyUnqueued ) { int PacketsToUnqueue = LastPacket - PacketsAlreadyUnqueued; if( PacketsToUnqueue > m_PacketBuffer.size( ) ) { qDebug() << ( "[GPROXY] received GPS_ACK with last packet > total packets sent" ); PacketsToUnqueue = m_PacketBuffer.size( ); } while( PacketsToUnqueue > 0 ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); PacketsToUnqueue--; } } } else if( Packet->GetID( ) == CGPSProtocol :: GPS_REJECT && Data.size( ) == 8 ) { quint32 Reason; ds >> Reason; if( Reason == REJECTGPS_INVALID ) qDebug() << ( "[GPROXY] rejected by remote server: invalid data" ); else if( Reason == REJECTGPS_NOTFOUND ) qDebug() << ( "[GPROXY] rejected by remote server: player not found in any running games" ); m_LocalSocket->disconnectFromHost( ); } } } delete Packet; } } void CGProxy::requestGame(QString host) { m_RequesterSocket->writeDatagram(QByteArray("rcon_broadcast"), QHostAddress(host), 6969); } void CGProxy::readPendingDatagrams() { while (m_RequesterSocket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(m_RequesterSocket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; m_RequesterSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); parsePacket(sender.toString(), datagram); } } void CGProxy::parsePacket(QString IP, QByteArray datagram) { if( datagram.at(0) == W3GS_HEADER_CONSTANT ) { if( datagram.at(1) == CGameProtocol :: W3GS_GAMEINFO ) { CGameInfo* gameInfo = m_GameProtocol->RECEIVE_W3GS_GAMEINFO(datagram); gameInfo->SetIP(IP); bool DuplicateFound = false; for(QVector<CGameInfo*>::iterator i = games.begin(); i != games.end(); ++i) { if((*i)->GetIP() == IP && (*i)->GetPort() == gameInfo->GetPort()) { m_RequesterSocket->writeDatagram(m_GameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetUniqueGameID()), QHostAddress::Broadcast, 6112); delete *i; *i = gameInfo; DuplicateFound = true; break; } } if(!DuplicateFound) games.push_back(gameInfo); for(QVector<CGameInfo*>::const_iterator i = games.constBegin(); i != games.constEnd(); ++i) m_RequesterSocket->writeDatagram((*i)->GetPacket(m_ListenPort), QHostAddress::LocalHost, 6112); m_LastBroadcastTime = GetTime( ); } } } void CGProxy::SendLocalChat( QString message ) { QByteArray toPIDs; toPIDs.append(m_ChatPID); if( m_LocalSocket ) { if( m_GameStarted ) { if( message.size( ) > 127 ) message = message.left(127); m_LocalSocket->write( m_GameProtocol->SEND_W3GS_CHAT_FROM_HOST( m_ChatPID, toPIDs, 32, 0, message ) ); } else { if( message.size( ) > 254 ) message = message.left(254); m_LocalSocket->write( m_GameProtocol->SEND_W3GS_CHAT_FROM_HOST( m_ChatPID, toPIDs, 16, -1, message ) ); } } } void CGProxy::SendEmptyAction( ) { // we can't send any empty actions while the lag screen is up // so we keep track of who the lag screen is currently showing (if anyone) and we tear it down, send the empty action, and put it back up for( QVector<quint8>::iterator i = m_Laggers.begin( ); i != m_Laggers.end( ); i++ ) { QByteArray StopLag; QDataStream ds(&StopLag, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_STOP_LAG; ds << (quint16)9; ds << (quint8)0; ds << (quint8)*i; ds << (quint32)60000; m_LocalSocket->write( StopLag ); } QByteArray EmptyAction; EmptyAction.append( (char)0xF7 ); EmptyAction.append( (char)0x0C ); EmptyAction.append( (char)0x06 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); EmptyAction.append( (char)0x00 ); m_LocalSocket->write( EmptyAction ); if( !m_Laggers.empty( ) ) { QByteArray StartLag; QDataStream ds(&StartLag, QIODevice::ReadWrite); ds.setByteOrder(QDataStream::LittleEndian); ds << (quint8)W3GS_HEADER_CONSTANT; ds << (quint8)CGameProtocol::W3GS_START_LAG; ds << (quint16)0; ds << (quint8)m_Laggers.size(); for( QVector<quint8>::iterator i = m_Laggers.begin( ); i != m_Laggers.end( ); i++ ) { // using a lag time of 60000 ms means the counter will start at zero // hopefully warcraft 3 doesn't care about wild variations in the lag time in subsequent packets ds << (quint8)*i; ds << (quint32)60000; } CGameProtocol::AssignLength(StartLag); m_LocalSocket->write( StartLag ); } }
12ayhuang-mac-experiment
qgproxy.cpp
C++
asf20
33,739
/* Copyright 2011 Gene Chen 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. */ #include "dcapifetcher.h" ApiFetcher::ApiFetcher(QWidget* parent) : QObject(parent), currentReply(0) { connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*))); connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(deleteLater())); } ApiFetcher::~ApiFetcher() { } void ApiFetcher::fetch(QString url) { QUrl nUrl(url); get(nUrl); } void ApiFetcher::get(const QUrl &url) { QNetworkRequest request(url); if (currentReply) { currentReply->disconnect(this); currentReply->deleteLater(); } currentReply = manager.get(request); connect(currentReply, SIGNAL(readyRead()), this, SLOT(readyRead())); connect(currentReply, SIGNAL(metaDataChanged()), this, SLOT(metaDataChanged())); connect(currentReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); } void ApiFetcher::metaDataChanged() { QUrl redirectionTarget = currentReply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (redirectionTarget.isValid()) { get(redirectionTarget); } } void ApiFetcher::readyRead() { int statusCode = currentReply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode >= 200 && statusCode < 300) { QByteArray data = currentReply->readAll(); QString str(data); result += str; } } void ApiFetcher::error(QNetworkReply::NetworkError) { qWarning("apifetcher network error"); currentReply->disconnect(this); currentReply->deleteLater(); currentReply = 0; } void ApiFetcher::finished(QNetworkReply *reply) { Q_UNUSED(reply); emit fetchComplete(result); }
12ayhuang-mac-experiment
dcapifetcher.cpp
C++
asf20
2,197
/* Copyright 2010 Trevor Hogan 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. */ #include "gpsprotocol.h" #include <QtEndian> // // CGPSProtocol // CGPSProtocol :: CGPSProtocol( ) { } CGPSProtocol :: ~CGPSProtocol( ) { } /////////////////////// // RECEIVE FUNCTIONS // /////////////////////// //////////////////// // SEND FUNCTIONS // //////////////////// QByteArray CGPSProtocol :: SEND_GPSC_INIT( quint32 version ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_INIT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&version, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSC_RECONNECT( quint8 PID, quint32 reconnectKey, quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_RECONNECT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char)PID ); packet.append( (char*)&reconnectKey, 4 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSC_ACK( quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_ACK ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_INIT( quint16 reconnectPort, quint8 PID, quint32 reconnectKey, quint8 numEmptyActions ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_INIT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&reconnectPort, 2 ); packet.append( (char)PID ); packet.append( (char*)&reconnectKey, 4 ); packet.push_back( numEmptyActions ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_RECONNECT( quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_RECONNECT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_ACK( quint32 lastPacket ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_ACK ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&lastPacket, 4 ); AssignLength( packet ); return packet; } QByteArray CGPSProtocol :: SEND_GPSS_REJECT( quint32 reason ) { QByteArray packet; packet.append( (char)GPS_HEADER_CONSTANT ); packet.append( (char)GPS_REJECT ); packet.append( (char)0 ); packet.append( (char)0 ); packet.append( (char*)&reason, 4 ); AssignLength( packet ); return packet; } ///////////////////// // OTHER FUNCTIONS // ///////////////////// bool CGPSProtocol :: AssignLength( QByteArray &content ) { // insert the actual length of the content array into bytes 3 and 4 (indices 2 and 3) if( content.size( ) >= 4 && content.size( ) <= 65535 ) { QByteArray LengthBytes; uchar dest[2]; qToLittleEndian<quint16>(content.size(), dest); LengthBytes = QByteArray((char*)dest, 2); content[2] = LengthBytes[0]; content[3] = LengthBytes[1]; return true; } return false; } bool CGPSProtocol :: ValidateLength( QByteArray &content ) { // verify that bytes 3 and 4 (indices 2 and 3) of the content array describe the length quint16 Length; QByteArray LengthBytes; if( content.size( ) >= 4 && content.size( ) <= 65535 ) { LengthBytes.push_back( content[2] ); LengthBytes.push_back( content[3] ); Length = qFromLittleEndian<quint16>((uchar*)LengthBytes.data()); if( Length == content.size( ) ) return true; } return false; }
12ayhuang-mac-experiment
gpsprotocol.cpp
C++
asf20
4,269
/* Copyright 2011 Gene Chen 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. */ #ifndef IRCHANDLER_H #define IRCHANDLER_H #include <QTabWidget> #include <QMap> #include <QStringList> #include <QUrl> #define COMMUNI_STATIC #include <Irc> #include <IrcMessage> #include <IrcSession> #include <IrcCommand> #include <ircprefix.h> class ChannelHandler; class FriendsHandler; enum MessageType { Normal, Sys, Err, Friends }; class IrcHandler : public QTabWidget { Q_OBJECT public: IrcHandler(QWidget* parent); void connectToIrc(QString name); void part(QString channel) { if(irc) irc->sendCommand(IrcCommand::createPart(channel)); } public slots: void connected(); void disconnected(); void messageReceived(IrcMessage *message); void handleChat(QString&, QString&); void myCloseTab(int); void showTextCurrentTab(QString, MessageType=Normal); void reloadSkin(); void joinedGame(QString, QString); void handleUrl(QUrl); signals: void showMessage(QString, int timeout=3000); void requestGame(QString); private: IrcSession *irc; QMap<QString, ChannelHandler*> m_ChannelMap; QMap<QString, FriendsHandler*> m_FriendsMap; QString m_Username; QStringList m_Friends; void removeTabName(QString name); void joinedChannel(IrcPrefix origin, IrcJoinMessage* joinMsg); void partedChannel(IrcPrefix origin, IrcPartMessage* partMsg); void quitMessage(IrcPrefix origin, IrcQuitMessage* quitMsg); void privateMessage(IrcPrefix origin, IrcPrivateMessage* privMsg); void noticeMessage(IrcPrefix origin, IrcNoticeMessage* noticeMsg); void nickMessage(IrcPrefix origin, IrcNickMessage* nickMsg); void numericMessage(IrcNumericMessage* numMsg); }; #endif
12ayhuang-mac-experiment
irchandler.h
C++
asf20
2,182
/* Copyright 2011 Gene Chen 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. */ #include "updateform.h" #include "downloaderform.h" #include "dcapifetcher.h" #include "xdcc_version.h" #include <QDir> UpdateForm::UpdateForm(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags) { ui.setupUi(this); connect(ui.okButton, SIGNAL(clicked()), this, SLOT(updateNow())); m_Version = QSettings("DotaCash", "DCClient X").value("version", XDCC_VERSION).toString(); m_Downloader = new DownloaderForm(this); connect(m_Downloader, SIGNAL(downloadsComplete()), this, SLOT(beginUpdate())); } void UpdateForm::updateNow() { QDir updateFolder("./updates/"); QStringList list = updateFolder.entryList(QDir::Files); for (int i = 0; i < list.size(); ++i) updateFolder.remove(list.at(i)); m_Downloader->addFile("http://www.dotacash.com/xdcc/file_list.xml"); m_Downloader->addFile(m_Latest["url"]); m_Downloader->beginDownloads(); } void UpdateForm::beginUpdate() { emit updateFromURL(m_Latest["url"]); } void UpdateForm::checkForUpdates(QString appCastURL, bool alwaysShow) { m_AlwaysShow = alwaysShow; ApiFetcher* updateFetcher = new ApiFetcher(this); connect(updateFetcher, SIGNAL(fetchComplete(QString&)), this, SLOT(parseUpdateData(QString&))); updateFetcher->fetch(appCastURL); } void UpdateForm::parseUpdateData(QString& data) { QXmlStreamReader xml(data); while(!xml.atEnd() && !xml.hasError()) { xml.readNext(); if(xml.isStartDocument()) continue; if(xml.isStartElement()) { if(xml.name() == "channel") continue; if(xml.name() == "item") { m_Latest = parseUpdateItem(xml); break; } } } if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml.lineNumber() << ": " << xml.errorString(); } bool isNewer = isUpdateRequired(m_Latest["version"]); if(isNewer) { ui.label->setText("<span style=\" font-size:14pt; color:#17069c;\">" + m_Latest["title"] + "</span>"); ui.lblChangelog->setText(m_Latest["description"].replace("</br>", "<br>")); ui.cancelButton->setText(tr("Later")); ui.okButton->show(); } else { ui.label->setText("<span style=\" font-size:14pt; color:#17069c;\">" + tr("You're up to date!") + "</span>"); ui.lblChangelog->setText(tr("DCClient v%1 is the newest version currently available.").arg(m_Version)); ui.cancelButton->setText(tr("OK")); ui.okButton->hide(); } if(isNewer || m_AlwaysShow) this->show(); } bool UpdateForm::isUpdateRequired(QString& latestVer) { QStringList vals1 = m_Version.split('.'); QStringList vals2 = latestVer.split('.'); int i=0; while(i < vals1.length() && i < vals2.length() && vals1[i] == vals2[i]) { i++; } if (i < vals1.length() && i < vals2.length()) { if(vals1[i].toInt() < vals2[i].toInt()) return true; } return false; } QMap<QString, QString> UpdateForm::parseUpdateItem(QXmlStreamReader& xml) { QMap<QString, QString> mapData; if(!xml.isStartElement() || xml.name() != "item") return mapData; xml.readNext(); while(!(xml.isEndElement() && xml.name() == "item")) { if(xml.isStartElement()) { if(xml.name() == "channel") continue; if(xml.name() == "title") addElementDataToMap(xml, mapData); else if(xml.name() == "description") addElementDataToMap(xml, mapData); else if(xml.name() == "enclosure") { QXmlStreamAttributes attrs = xml.attributes(); mapData["url"] = attrs.value("url").toString(); mapData["version"] = attrs.value("sparkle:version").toString(); mapData["os"] = attrs.value("sparkle:os").toString(); mapData["type"] = attrs.value("type").toString(); mapData["size"] = attrs.value("size").toString(); } } xml.readNext(); } return mapData; } void UpdateForm::addElementDataToMap(QXmlStreamReader& xml, QMap<QString, QString>& map) { if(!xml.isStartElement()) return; QString elementName = xml.name().toString(); xml.readNext(); if(!xml.isCharacters() || xml.isWhitespace()) return; map.insert(elementName, xml.text().toString()); }
12ayhuang-mac-experiment
updateform.cpp
C++
asf20
4,600
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_SETTINGS_H #define XDCC_SETTINGS_H #include <QtGui/QMainWindow> #include <QSettings> #include "xdcc.h" #include "ui_xdcc_options.h" class SettingsForm : public QDialog { Q_OBJECT public: SettingsForm(QWidget *parent = 0, Qt::WFlags flags = 0); ~SettingsForm(); public slots: void saveSettings(); signals: void reloadSkin(); private: Ui_SettingsForm ui; QSettings* settings; bool m_SoundOnGameStart; bool m_FriendFollow; bool m_Refresh; QString m_Skin; }; #endif // XDCC_SETTINGS_H
12ayhuang-mac-experiment
settingsform.h
C++
asf20
1,104
TEMPLATE = app TARGET = xdcc DESTDIR = ../ QT += core gui network webkit CONFIG += release DEFINES += QT_LARGEFILE_SUPPORT QT_NETWORK_LIB QT_WEBKIT_LIB INCLUDEPATH += ./GeneratedFiles \ ./GeneratedFiles/Release \ ./include \ . LIBS += -Llib -lircclient-qt DEPENDPATH += . MOC_DIR += ./GeneratedFiles/release OBJECTS_DIR += release UI_DIR += ./GeneratedFiles RCC_DIR += ./GeneratedFiles include(xdcc.pri) win32: { RC_FILE = xdcc.rc LIBS += -lwinmm -lWinSparkle } QMAKE_CXXFLAGS += /J
12ayhuang-mac-experiment
xdcc.pro
QMake
asf20
512
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_DOWNLOADERFORM_H #define XDCC_DOWNLOADERFORM_H #include <QtGui/QMainWindow> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QQueue> #include <QFile> #include <QTime> #include "xdcc.h" #include "ui_xdcc_downloader.h" class DownloaderForm : public QDialog { Q_OBJECT public: DownloaderForm(QWidget *parent = 0, Qt::WFlags flags = 0); void addFile(QString url); void beginDownloads(); public slots: void startNextDownload(); void downloadProgress(qint64 bytesReceived, qint64 bytesTotal); void downloadFinished(); void downloadReadyRead(); signals: void downloadsComplete(); private: Ui_DownloaderForm ui; QNetworkAccessManager manager; QQueue<QUrl> downloadQueue; QNetworkReply* currentDownload; QFile output; QTime downloadTime; int downloadedCount; int totalCount; QString DownloaderForm::saveFileName(const QUrl &url); }; #endif // XDCC_DOWNLOADERFORM_H
12ayhuang-mac-experiment
downloaderform.h
C++
asf20
1,533
/* Copyright 2011 Gene Chen 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. */ #include "friendshandler.h" FriendsHandler::FriendsHandler(QString nFriendName, QWidget *parent) : m_FriendName(nFriendName), QObject(parent) { m_Status = false; if(parent) { connect(this, SIGNAL(showMessage(QString, MessageType)), parent, SLOT(showTextCurrentTab(QString, MessageType))); connect(this, SIGNAL(requestGame(QString)), parent, SIGNAL(requestGame(QString))); } /* if(m_Buffer) { connect(m_Buffer, SIGNAL(joined(const QString)), this, SLOT(joined(const QString))); connect(m_Buffer, SIGNAL(parted(const QString, const QString)), this, SLOT(parted(const QString, const QString))); connect(m_Buffer, SIGNAL(quit(const QString, const QString)), this, SLOT(parted(const QString, const QString))); connect(m_Buffer, SIGNAL(nickChanged(const QString, const QString)), this, SLOT(nickChanged(const QString, const QString))); connect(m_Buffer, SIGNAL(messageReceived(const QString, const QString, Irc::Buffer::MessageFlags)), this, SLOT(messageReceived(const QString, const QString, Irc::Buffer::MessageFlags))); connect(m_Buffer, SIGNAL(noticeReceived(const QString, const QString, Irc::Buffer::MessageFlags)), this, SLOT(noticeReceived(const QString, const QString, Irc::Buffer::MessageFlags))); } */ } void FriendsHandler::nickChanged(const QString user, const QString nick) { if(user.toLower() == m_FriendName.toLower()) m_FriendName = nick; } void FriendsHandler::joined(const QString user) { if(user.toLower() == m_FriendName.toLower()) { m_Status = true; emit showMessage(tr("Your friend %1 is now online.").arg(user), Friends); } } void FriendsHandler::parted(const QString user, const QString reason) { if(user.toLower() == m_FriendName.toLower()) { m_Status = false; emit showMessage(tr("Your friend %1 is now offline.").arg(user), Friends); } } void FriendsHandler::messageReceived(const QString &origin, const QString &message) { if(origin.toLower() == m_FriendName.toLower()) { emit showMessage(QString("&lt;%1&gt; %2").arg(origin).arg(message), Friends); } } void FriendsHandler::noticeReceived(const QString &origin, const QString &message) { if(origin.toLower() == m_FriendName.toLower()) { if(message.startsWith("xdcc://")) { int idx = message.indexOf(";"); QString IP = message.mid(7).left(idx-7); QString gameName = message.mid(idx+1); emit showMessage(tr("Your friend %1 has joined the game <a href=xdcc://%2>%3</a>").arg(origin).arg(IP).arg(gameName), Friends); QSettings settings("DotaCash", "DCClient X"); if(settings.value("FriendFollow", true).toBool()) emit requestGame(IP); } } }
12ayhuang-mac-experiment
friendshandler.cpp
C++
asf20
3,190
/* Copyright 2011 Gene Chen 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. */ #include "xdcc.h" #include "loginform.h" #include <QtGui/QMainWindow> #include <QSharedMemory> #include <QTranslator> #include <QLibraryInfo> #include <QFile> #include <qlocalserver.h> #include <qlocalsocket.h> QSharedMemory* _singular; QtMsgHandler oldHandler = NULL; void msgHandler(QtMsgType type, const char *msg) { oldHandler(type, msg); QFile logfile("dcclog.txt"); if(logfile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) { QTextStream out(&logfile); out << msg << "\n"; logfile.close(); } } #define _CRTDBG_MAP_ALLOC int main(int argc, char *argv[]) { //_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF ); //oldHandler = qInstallMsgHandler(msgHandler); QApplication a(argc, argv); QTranslator qtTranslator; qtTranslator.load(":/lang/qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); a.installTranslator(&qtTranslator); QTranslator myappTranslator; myappTranslator.load(":/lang/xdcc_" + QLocale::system().name()); a.installTranslator(&myappTranslator); _singular = new QSharedMemory("DCClient"); if(_singular->attach(QSharedMemory::ReadWrite)) { _singular->detach(); if(argc >= 2) { QLocalSocket socket; socket.connectToServer("DCClientIPC"); if(socket.waitForConnected()) { QDataStream out(&socket); out << QString(argv[1]); socket.waitForBytesWritten(); } } return 0; } _singular->create(1); XDCC xdcc; int ret = a.exec(); delete _singular; return ret; }
12ayhuang-mac-experiment
main.cpp
C++
asf20
2,149
/* Copyright 2011 Gene Chen 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. */ #include "downloaderform.h" #include <QMessageBox> #include <QFileInfo> DownloaderForm::DownloaderForm(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags) { ui.setupUi(this); ui.progressBar->setValue(0); downloadedCount = 1; totalCount = 0; } void DownloaderForm::addFile(QString url) { downloadQueue.enqueue(url); totalCount++; } void DownloaderForm::beginDownloads() { this->show(); QTimer::singleShot(0, this, SLOT(startNextDownload())); } void DownloaderForm::startNextDownload() { if (downloadQueue.isEmpty()) { emit downloadsComplete(); return; } QUrl url = downloadQueue.dequeue(); QString filename = saveFileName(url); output.setFileName("updates/" + filename); if (!output.open(QIODevice::WriteOnly)) { QMessageBox::warning(this, tr("Update Error"), tr("Problem opening save file '%1' for download '%2': %3") .arg(qPrintable(filename)) .arg(url.toEncoded().constData()) .arg(qPrintable(output.errorString()))); downloadedCount++; startNextDownload(); return; // skip this download } QNetworkRequest request(url); currentDownload = manager.get(request); connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)), SLOT(downloadProgress(qint64,qint64))); connect(currentDownload, SIGNAL(finished()), SLOT(downloadFinished())); connect(currentDownload, SIGNAL(readyRead()), SLOT(downloadReadyRead())); downloadTime.start(); } QString DownloaderForm::saveFileName(const QUrl &url) { QString path = url.path(); QString basename = QFileInfo(path).fileName(); if (basename.isEmpty()) basename = "download"; if (QFile::exists(basename)) { // already exists, don't overwrite int i = 0; basename += '.'; while (QFile::exists(basename + QString::number(i))) ++i; basename += QString::number(i); } return basename; } void DownloaderForm::downloadFinished() { downloadedCount++; output.close(); if (currentDownload->error()) { QFile::remove(output.fileName()); QMessageBox::warning(this, tr("Update Error"), tr("Failed: %1").arg(qPrintable(currentDownload->errorString()))); } currentDownload->deleteLater(); startNextDownload(); } void DownloaderForm::downloadProgress(qint64 bytesReceived, qint64 bytesTotal) { ui.progressBar->setMaximum(bytesTotal); ui.progressBar->setValue(bytesReceived); // calculate the download speed double speed = bytesReceived * 1000.0 / downloadTime.elapsed(); QString unit; if (speed < 1024) { unit = "bytes/sec"; } else if (speed < 1024*1024) { speed /= 1024; unit = "kB/s"; } else { speed /= 1024*1024; unit = "MB/s"; } ui.lblStatus->setText(tr("Downloading file %1 at %2 %3").arg(currentDownload->url().toString()).arg(speed, 3, 'f', 1).arg(unit)); ui.progressBar->update(); ui.label->setText(tr("Downloading Updates (%1 of %2)").arg(downloadedCount).arg(totalCount)); } void DownloaderForm::downloadReadyRead() { output.write(currentDownload->readAll()); }
12ayhuang-mac-experiment
downloaderform.cpp
C++
asf20
3,538
/* Copyright 2010 Trevor Hogan 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. */ #ifndef GPSPROTOCOL_H #define GPSPROTOCOL_H #include <QByteArray> // // CGameProtocol // #define GPS_HEADER_CONSTANT 248 #define REJECTGPS_INVALID 1 #define REJECTGPS_NOTFOUND 2 class CGPSProtocol { public: enum Protocol { GPS_INIT = 1, GPS_RECONNECT = 2, GPS_ACK = 3, GPS_REJECT = 4 }; CGPSProtocol( ); ~CGPSProtocol( ); // receive functions // send functions QByteArray SEND_GPSC_INIT( quint32 version ); QByteArray SEND_GPSC_RECONNECT( quint8 PID, quint32 reconnectKey, quint32 lastPacket ); QByteArray SEND_GPSC_ACK( quint32 lastPacket ); QByteArray SEND_GPSS_INIT( quint16 reconnectPort, quint8 PID, quint32 reconnectKey, quint8 numEmptyActions ); QByteArray SEND_GPSS_RECONNECT( quint32 lastPacket ); QByteArray SEND_GPSS_ACK( quint32 lastPacket ); QByteArray SEND_GPSS_REJECT( quint32 reason ); // other functions private: bool AssignLength( QByteArray &content ); bool ValidateLength( QByteArray &content ); }; #endif
12ayhuang-mac-experiment
gpsprotocol.h
C++
asf20
1,556
/* Copyright 2011 Gene Chen 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. */ #include "settingsform.h" #include <QMessageBox> #include <QDir> SettingsForm::SettingsForm(QWidget *parent, Qt::WFlags flags) : QDialog(parent, flags) { ui.setupUi(this); connect(ui.btnSave, SIGNAL(clicked()), this, SLOT(saveSettings())); settings = new QSettings("DotaCash", "DCClient X"); m_SoundOnGameStart = settings->value("GameStartedSound", true).toBool(); ui.optionSoundGameStart->setCheckState(m_SoundOnGameStart ? Qt::Checked : Qt::Unchecked); m_FriendFollow = settings->value("FriendFollow", true).toBool(); ui.optionFriendFollow->setCheckState(m_FriendFollow ? Qt::Checked : Qt::Unchecked); m_Refresh = settings->value("InactiveRefresh", false).toBool(); ui.optionFriendFollow->setCheckState(m_Refresh ? Qt::Checked : Qt::Unchecked); m_Skin = settings->value("Skin", "default").toString(); QDir skinsDir("./skins/"); QStringList skinsList = skinsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); ui.cmbSkin->addItems(skinsList); int idx = ui.cmbSkin->findText(m_Skin); if(idx != -1) ui.cmbSkin->setCurrentIndex(idx); } SettingsForm::~SettingsForm() { delete settings; } void SettingsForm::saveSettings() { m_SoundOnGameStart = ui.optionSoundGameStart->isChecked(); settings->setValue("GameStartedSound", m_SoundOnGameStart); m_FriendFollow = ui.optionFriendFollow->isChecked(); settings->setValue("FriendFollow", m_FriendFollow); m_Refresh = ui.optionRefresh->isChecked(); settings->setValue("InactiveRefresh", m_Refresh); m_Skin = ui.cmbSkin->currentText(); settings->setValue("Skin", m_Skin); QFile styleSheet(QString("./skins/%1/style.css").arg(m_Skin)); QString style; if(styleSheet.open(QFile::ReadOnly)) { QTextStream styleIn(&styleSheet); style = styleIn.readAll(); styleSheet.close(); QMainWindow* parent = (QMainWindow*)this->parent(); parent->setStyleSheet(style); emit reloadSkin(); } this->close(); }
12ayhuang-mac-experiment
settingsform.cpp
C++
asf20
2,480
/* Copyright 2011 Gene Chen 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. */ #ifndef GAMEINFO_H #define GAMEINFO_H #include "xdcc.h" struct GameInfo { QString name; QString ip; QString players; QString id; }; struct QueueInfo { QString position; QString name; }; struct PlayerInfo { QString name; QString slot; QString realm; QString elo; QString games; QString kdr; QString wins; }; #endif
12ayhuang-mac-experiment
xmlstructs.h
C
asf20
960
/* Copyright 2011 Gene Chen 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. */ #include <QObject> #include <QFile> #define COMMUNI_STATIC #include <ircutil.h> #include "channelhandler.h" ChannelHandler::ChannelHandler(bool showUserlist, QWidget* parent) : QObject(parent), lstUsers(0) { m_Tab = new QWidget(parent); QHBoxLayout* horizontalLayout = new QHBoxLayout(m_Tab); horizontalLayout->setSpacing(10); txtChat = new QTextBrowser(m_Tab); txtChat->setMinimumWidth(560); txtChat->setOpenLinks(false); horizontalLayout->addWidget(txtChat); if(showUserlist) { lstUsers = new QListWidget(m_Tab); lstUsers->setSortingEnabled(true); lstUsers->setMaximumWidth(180); lstUsers->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); lstUsers->setAlternatingRowColors(true); horizontalLayout->addWidget(lstUsers); } connect(txtChat, SIGNAL(anchorClicked(QUrl)), parent, SLOT(handleUrl(QUrl))); reloadSkin(); } void ChannelHandler::reloadSkin() { QString skin = QSettings("DotaCash", "DCClient X", this).value("Skin", "default").toString(); QFile styleSheet(QString("./skins/%1/style.css").arg(skin)); QString style; if(styleSheet.open(QFile::ReadOnly)) { QTextStream styleIn(&styleSheet); style = styleIn.readAll(); styleSheet.close(); txtChat->document()->setDefaultStyleSheet(style); } } void ChannelHandler::UpdateNames(QStringList& names) { if(!lstUsers) return; lstUsers->addItems(names); } void ChannelHandler::nickChanged(const QString user, const QString nick) { if(!lstUsers) return; QList<QListWidgetItem*> list = lstUsers->findItems(user, Qt::MatchFixedString); for(int i = 0; i < list.size(); i++) { list.at(i)->setText(nick); } txtChat->append(tr("<span class = \"sysmsg\">%1 is now known as %2</span>").arg(user).arg(nick)); } void ChannelHandler::joined(const QString user) { if(!lstUsers) return; QList<QListWidgetItem*> list = lstUsers->findItems(user, Qt::MatchFixedString); if(list.isEmpty()) { lstUsers->addItem(user); } } void ChannelHandler::parted(const QString user, const QString reason) { if(!lstUsers) return; QList<QListWidgetItem*> list = lstUsers->findItems(user, Qt::MatchFixedString); for(int i = 0; i < list.size(); i++) { lstUsers->removeItemWidget(list.at(i)); delete list.at(i); } } void ChannelHandler::messageReceived(const QString &origin, const QString &message) { QString txt = QString("<span class = \"msg\">&lt;%1&gt; %2</span>").arg(origin).arg(IrcUtil::messageToHtml(message)); txtChat->append(txt); } void ChannelHandler::noticeReceived(const QString &origin, const QString &message) { QString txt = QString("<span class = \"notice\">-%1- %2</span>").arg(origin).arg(IrcUtil::messageToHtml(message)); txtChat->append(txt); }
12ayhuang-mac-experiment
channelhandler.cpp
C++
asf20
3,277
/* Copyright 2011 Gene Chen 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. */ #ifndef DCAPIFETCHER_H #define DCAPIFETCHER_H #include "xdcc.h" #include <QObject> #include <QNetworkAccessManager> #include <QNetworkReply> class ApiFetcher : public QObject { Q_OBJECT public: ApiFetcher(QWidget* parent=0); ~ApiFetcher(); void fetch(QString url); signals: void fetchComplete(QString& data); public slots: void finished(QNetworkReply *reply); void readyRead(); void metaDataChanged(); void error(QNetworkReply::NetworkError); private: QNetworkAccessManager manager; QNetworkReply *currentReply; QString result; void get(const QUrl &url); }; #endif
12ayhuang-mac-experiment
dcapifetcher.h
C++
asf20
1,177
/* Copyright 2011 Gene Chen 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. */ #ifndef CHANNELHANDLER_H #define CHANNELHANDLER_H #include "xdcc.h" #include <QObject> #include <QTextBrowser> #include <QListWidget> #define COMMUNI_STATIC #include <Irc> #include <IrcMessage> #include <ircutil.h> class ChannelHandler : public QObject { Q_OBJECT public: ChannelHandler(bool showUserlist=true, QWidget *parent=0); QWidget* GetTab() { return m_Tab; } void showText(QString msg) { txtChat->append(msg); } void UpdateNames(QStringList& names); void reloadSkin(); void joined(const QString); void parted(const QString, const QString); void nickChanged(const QString, const QString); void messageReceived(const QString &origin, const QString &message); void noticeReceived(const QString &origin, const QString &message); private: QWidget* m_Tab; QTextBrowser* txtChat; QListWidget* lstUsers; }; #endif
12ayhuang-mac-experiment
channelhandler.h
C++
asf20
1,428
/* Copyright 2011 Gene Chen 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. */ #ifndef XDCC_VERSION #define XDCC_VERSION "1.8.1\0" const QString API_SERVER = "emma.dotacash.com"; const QString APPCAST_URL = "http://www.dotacash.com/xdcc/appcast.xml"; #endif
12ayhuang-mac-experiment
xdcc_version.h
C
asf20
769
/* Copyright 2010 Trevor Hogan 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. */ #include "commandpacket.h" // // CCommandPacket // CCommandPacket :: CCommandPacket( unsigned char nPacketType, int nID, QByteArray nData ) { m_PacketType = nPacketType; m_ID = nID; m_Data = nData; } CCommandPacket :: ~CCommandPacket( ) { }
12ayhuang-mac-experiment
commandpacket.cpp
C++
asf20
840
#include "gamerequester.h" #include "gameprotocol.h" #include "commandpacket.h" GameRequester::GameRequester(QWidget* parent) : QObject(parent) { socket = new QUdpSocket(this); socket->bind(6969, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint); connect(socket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams())); gameProtocol = new CGameProtocol(); } GameRequester::~GameRequester() { for(auto i = games.begin(); i != games.end(); ++i) { socket->writeDatagram(gameProtocol->SEND_W3GS_DECREATEGAME((*i)->GetEntryKey()), QHostAddress::Broadcast, 6112); delete *i; } }
12ayhuang-mac-experiment
gamerequester.cpp
C++
asf20
596
\subsection{Adaptation or extension of the model} Because our proposed formal model was sufficiently correct on the second deliverable, it was not necessary to adapt our model.
0lcb0-modelling
trunk/work/Adaptation.tex
TeX
gpl3
177
\documentclass[a4paper,11pt]{article} \usepackage{a4wide,graphicx,eurosym} \DeclareGraphicsExtensions{.pdf,.jpeg,.png} \title{Report} \date{\today} \begin{document} \begin{center} { \huge \bf 0LCB0 - Introduction to Modeling \\ Process Modeling Report \\ Flower Contracts 1 } \\\bigskip \begin{tabular}{rcl} Jairiz Phelipa Reynalde & 0869800 & j.u.phelipa@student.tue.nl \\ Guido Santegoeds & 0890429 & g.h.santegoeds@student.tue.nl \\ Floris Schippers & 0779908 & f.w.schippers@student.tue.nl \\ Martijn Verbakel & 0848610 & m.h.verbakel@student.tue.nl \end{tabular} \\\bigskip Supervisor: George Fletcher \\\bigskip Hand-in date: \today \end{center} \vfill \begin{abstract} This document contains the report for the Flower Contracts assignment for the Process Modeling section of the course Introduction to Modeling. There is 1 attachment included in the \texttt{ZIP} file, this is our CPN model. \end{abstract} \newpage \tableofcontents \newpage \section{Defining phase} \input{ProblemStatement} \input{Subquestions} \clearpage \section{Conceptualizing phase} \input{ConceptualModel} \clearpage \section{Formalizing phase} \input{AssumptionsApproximations} \input{FormalModel} \clearpage \section{Executing phase} \input{Operations} \input{ValidityAccuracyUsefulness} \clearpage \section{Concluding phase} \input{Interpretation} \input{Adaptation} \clearpage \section{Evaluating phase} \input{Reflection} \end{document}
0lcb0-modelling
trunk/work/Report.tex
TeX
gpl3
1,535
\subsection{Reflection of the modeling process} \begin{center} \emph{This applies to section 23-27.} \end{center} Our model is still far from perfect. If we had more time to work on this assignment, we would try to implement the determination of the winner, such that after 30 minutes, the lowest bid would be chosen as the fulfiller. This would make the model more capable of showing more flaws in the original system.\\ \\ The main purpose of our model is verification. The criteria relevant for the purpose verification are in this case, scalability, convincingness and impact. \begin{itemize} \item[-] {\bf Scalability} Our model can be used on a range of different scales for modeled systems. In our case we have a scale of approximately 8500 orders a day. It is easy to change the size of the model without affecting the outcomes or usability of said model. The scalability of our model is not an area in which we seek improvement. \item[-] {\bf Convincingness} Our model could be made slightly more convincing by using real quantities and estimates of Floral Direct. In our model we used statistics provided by Rabobank and CBS. Using these figures we assumed a 40\% marketshare and a partner size of 40\% of all florists in the Netherlands. These quantities are quite optimistic but are most likely not so high in reality. This would’t have affected our model, rather the severity of the problem. \\ Using these figures nonetheless anticipated problems which may occur using a bigger scale. \item[-] {\bf Impact:} The impact of our model also depends partly on the assumptions we made. Using a larger scale implies more errors during the ordering process, which can lead to a loss of lower bids and eventually lower profits. The impact of our model depends on the scale we use. Using existing numbers would minimise the impact or at least gave a better estimation of the profit loss. \end{itemize} We are very proud of the model we created. CPN tools is a pretty complicated program, so we are proud of this working model. We have made the model timed, and we implemented a new (better) lock system. \\ During this project we have learned how to analyze malfunctioning systems, how to make conceptual and Entity-Relationship models, how to use CPN tools and how to work on documentation together using \LaTeX\ and subversion (SVN).
0lcb0-modelling
trunk/work/Reflection.tex
TeX
gpl3
2,363
\subsection{Operations with the model} \begin{center} \emph{This should apply to section 12, 16 and 21, but these do not apply to our model.} \end{center} Because we do not have any calculations, we can not answer any questions about our calculations.
0lcb0-modelling
trunk/work/Operations.tex
TeX
gpl3
256
{\rtf1\ansi\ansicpg1252\cocoartf1265\cocoasubrtf190 {\fonttbl\f0\fswiss\fcharset0 Helvetica;} {\colortbl;\red255\green255\blue255;\red47\green53\blue59;\red245\green245\blue245;} \paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0 \deftab720 \pard\pardeftab720 \f0\fs24 \cf2 \cb3 \shad\shadx0\shady-20\shadr0\shado0 \shadc0 In our formal model we made the assumption that 40% of all flower stores are partners with Floral direct. Furthermore we assumed that we have 40% marketschare of all flower online orders. These assumptions gave us enough figures to create a model that represented the errors occurring in the order process of Floral Direct. Due to this rough calculations we were able to reproduce and correct the internal error of the order process of Flower Direct. By focussing on the Dutch market we narrowed the product to a more concrete region. The model is a smaller scale than the order system of FlowerDIrect but it gave us nonetheless a good understanding of the problems.\ \ \ \ ^ }
0lcb0-modelling
trunk/work/20 - van jairiz.rtf
Rich Text Format
gpl3
1,027
\subsection{Assumptions and approximations} \begin{center} \emph{This applies to section 9, 11 and 14.} \end{center} There are a lot of ambiguities about the environment of the company Floral Direct in the given assignment description. It is unclear how many clients use Floral Direct and how many companies fulfill these orders. In our model, we are mainly focusing on the market in the Netherlands.\\ \\ Given the relatively short bidding time of 30 minutes that companies have and the fact that flowers are preferably delivered within a short range of the local companies, we initially expected that Floral Direct would have over 1000 associated local companies. To fulfill this demand, we thought that Floral Direct will have about ten thousand orders per day. \\ \\ In The Netherlands, we spend \euro 1.1 billion on flowers and plants. With 5365 flower stores in The Netherlands, the average turnover per store is about \euro $205$ thousand. The average spending per customer is about \euro30-\euro35. On a yearly basis, this brings us to $31,428,571$ orders. We assume 25\% of these orders are done via the internet. This means $7,857,143$ orders per year over the internet.\\ \\ In The Netherlands, we have 3 big online flower stores. One of them is much better graded than the other two, with an appropriately big conversion. We assume we have 40\% market share, so we have 40\% of the flower stores in our chain, which is 2146 stores. We also have 40\% of the online orders through our website, which is $7,857,143*40\%=3,142,857$ orders per year, so $3,142,857/365=8610$ orders per day.
0lcb0-modelling
trunk/work/AssumptionsApproximations.tex
TeX
gpl3
1,607
\subsection{Formulating sub-questions} \begin{center} \emph{This applies to section 8.} \end{center} Formulating the subquestions will help us identify the different problem areas and allow us to solve the problem as a whole by focusing on one problem at a time. We formulated these subquestions based on our expectations of what might be causing the current main issues. We used the information given and our assumptions to achieve this. \begin{itemize} \item[-] Is the order handling system capable of handling the large amounts of data simultaneously coming in during the whole day? \item[-]Are companies aware of the fact that they can only have one active bid on the entire site at the same time? \item[-]Are companies, willingly or accidentally, placing bids on more than one order at the same time? Thereby overwriting their previous bids on different orders and causing undesired results. \item[-]Does the distinct attribute \texttt{Company\_ID} in the bids table, meaning that there can only be one row in the active \texttt{Bids} table at any given time, cause previous bids to be removed unintentionally? \item[-]How is the flow of the queue being ensured? Could it happen that the queue locks up when more than one bid is on pause in the queue? \item[-]Are bids on a certain order sometimes still held in the queue at the time the winning bid is selected for that order? \end{itemize}
0lcb0-modelling
trunk/work/Subquestions.tex
TeX
gpl3
1,415
\subsection{Conceptual model} \begin{center} \emph{This applies to section 9 and 19.} \end{center} Our conceptual model is simplified as much as possible. The model now consists of two entities with one attribute each and a relation between those two entities with three attribute. \begin{center} \includegraphics[scale=1.7]{Model} \end{center} The first thing we did after reading the initial assignment description was making various models. These were extensive, informal models which included all factors we thought were important for the process. \\ \\ From there we started to strip these models until we eventually got what we thought was a potential conceptual model. We discussed this model with our supervisor, but he informed us that the conceptual model was supposed to be much more simple and less detailed. \\ \\ We removed various entities from the model like Floral Direct which just published the orders received from the clients onto their website, a database with lock system as described in the assignment (receiving and sending data from the Floral Direct website) and a lowest bidder who receives an email if he wins the bidding. These were removed because they only had something to do with the total picture of the model, but not with the specific part of the model we were investigating. \\ \\ We ended up with a conceptual model consisting of a \texttt{Client} which places an order to an \texttt{Order Handling System}, a \texttt{Local Company} which bids on these orders, a big 'black box' called \texttt{Order Handling System} which organizes everything and an \texttt{Order Contract} which is determined by the \texttt{Order Handling System}. \\ \\ In a final review, we decided together with our supervisor to change the conceptual model into an Entity-Relationship model. We created entities \texttt{Company} and \texttt{Order}, each with their own unique \texttt{ID} attributes with a \texttt{Bid} relation between them. This bid relation also has \texttt{Timestamp} and \texttt{Price} attributes.
0lcb0-modelling
trunk/work/ConceptualModel.tex
TeX
gpl3
2,048