diff --git a/projects/mtg/Android/src/net/wagic/utils/ImgDownloader.java b/projects/mtg/Android/src/net/wagic/utils/ImgDownloader.java index dace8e583..490f2079b 100644 --- a/projects/mtg/Android/src/net/wagic/utils/ImgDownloader.java +++ b/projects/mtg/Android/src/net/wagic/utils/ImgDownloader.java @@ -4,9 +4,11 @@ import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; + import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.Enumeration; + import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.model.enums.CompressionMethod; @@ -25,30 +27,31 @@ public class ImgDownloader { private static String convertStreamToString(java.io.InputStream inputStream) { final int bufferSize = 1024; - final char[] buffer = new char[bufferSize]; - final StringBuilder out = new StringBuilder(); - try { - Reader in = new InputStreamReader(inputStream, StandardCharsets.ISO_8859_1); - for (; ; ) { - int rsz = in.read(buffer, 0, buffer.length); + final char[] buffer = new char[bufferSize]; + final StringBuilder out = new StringBuilder(); + try { + Reader in = new InputStreamReader(inputStream, StandardCharsets.ISO_8859_1); + for (; ; ) { + int rsz = in.read(buffer, 0, buffer.length); if (rsz < 0) break; out.append(buffer, 0, rsz); } - } catch (Exception e) {} + } catch (Exception e) { + } return out.toString(); } private static String readLineByLineJava8(String filePath) { StringBuilder contentBuilder = new StringBuilder(); - try { - File file = new File(filePath); - BufferedReader br = new BufferedReader(new FileReader(file)); - - String st; - while ((st = br.readLine()) != null) - contentBuilder.append(st).append("\n"); + try { + File file = new File(filePath); + BufferedReader br = new BufferedReader(new FileReader(file)); + + String st; + while ((st = br.readLine()) != null) + contentBuilder.append(st).append("\n"); } catch (Exception e) { e.printStackTrace(); } @@ -56,32 +59,32 @@ public class ImgDownloader { return contentBuilder.toString(); } - public static String getSetInfo(String setName, boolean zipped, String path){ + public static String getSetInfo(String setName, boolean zipped, String path) { String cardsfilepath = ""; boolean todelete = false; - if(zipped){ + if (zipped) { File resFolder = new File(path + File.separator); - File [] listOfFile = resFolder.listFiles(); + File[] listOfFile = resFolder.listFiles(); ZipFile zipFile = null; InputStream stream = null; java.nio.file.Path filePath = null; try { - for (int i = 0; i < listOfFile.length; i++){ - if (listOfFile[i].getName().contains(".zip")){ - zipFile = new ZipFile(path + File.separator + listOfFile[i].getName()); - break; - } - } - if(zipFile == null) - return ""; + for (int i = 0; i < listOfFile.length; i++) { + if (listOfFile[i].getName().contains(".zip")) { + zipFile = new ZipFile(path + File.separator + listOfFile[i].getName()); + break; + } + } + if (zipFile == null) + return ""; Enumeration e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryName = entry.getName(); - if(entryName.contains("sets/")){ - if(entryName.contains("_cards.dat")){ + if (entryName.contains("sets/")) { + if (entryName.contains("_cards.dat")) { String[] names = entryName.split("/"); - if(setName.equalsIgnoreCase(names[1])){ + if (setName.equalsIgnoreCase(names[1])) { stream = zipFile.getInputStream(entry); byte[] buffer = new byte[1]; java.nio.file.Path outDir = Paths.get(path + File.separator); @@ -97,26 +100,28 @@ public class ImgDownloader { bos.close(); cardsfilepath = filePath.toString(); todelete = true; - } catch (Exception ex) {} + } catch (Exception ex) { + } break; - } + } } } - } - } catch (IOException ioe){ } - finally { + } + } catch (IOException ioe) { + } finally { try { - if (zipFile!=null) { + if (zipFile != null) { zipFile.close(); } - } catch (IOException ioe) {} + } catch (IOException ioe) { + } } } else { File setFolder = new File(path + File.separator + "sets" + File.separator + setName + File.separator); cardsfilepath = setFolder.getAbsolutePath() + File.separator + "_cards.dat"; } String lines = readLineByLineJava8(cardsfilepath); - if(todelete) { + if (todelete) { File del = new File(cardsfilepath); del.delete(); } @@ -131,48 +136,52 @@ public class ImgDownloader { return name + " (" + totalcards + " cards)"; } - public static Document findTokenPage(String imageurl, String name, String set, String [] availableSets, String tokenstats) throws Exception { + public static Document findTokenPage(String imageurl, String name, String set, String[] availableSets, String tokenstats) throws Exception { Document doc = null; Elements outlinks = null; try { doc = Jsoup.connect(imageurl + "t" + set.toLowerCase()).get(); outlinks = doc.select("body a"); - for (int k = 0; k < outlinks.size(); k++){ + for (int k = 0; k < outlinks.size(); k++) { String linktoken = outlinks.get(k).attributes().get("href"); try { Document tokendoc = Jsoup.connect(linktoken).get(); Elements stats = tokendoc.select("head meta"); - for (int j = 0; j < stats.size(); j++){ + for (int j = 0; j < stats.size(); j++) { String a = stats.get(j).attributes().get("content"); - if(stats.get(j).attributes().get("content").contains(tokenstats) && stats.get(j).attributes().get("content").toLowerCase().contains(name.toLowerCase())){ + if (stats.get(j).attributes().get("content").contains(tokenstats) && stats.get(j).attributes().get("content").toLowerCase().contains(name.toLowerCase())) { return tokendoc; } } - } catch (Exception e) {} + } catch (Exception e) { + } } - } catch (Exception e){} + } catch (Exception e) { + } System.out.println("Warning: Token " + name + " has not been found between " + set + " tokens, i will search for it between any other set..."); - for (int i = 1; i < availableSets.length; i++){ + for (int i = 1; i < availableSets.length; i++) { String currentSet = availableSets[i].toLowerCase().split(" - ")[0]; - if(!currentSet.equalsIgnoreCase(set)){ + if (!currentSet.equalsIgnoreCase(set)) { try { doc = Jsoup.connect(imageurl + "t" + currentSet).get(); outlinks = doc.select("body a"); - for (int k = 0; k < outlinks.size(); k++){ + for (int k = 0; k < outlinks.size(); k++) { String linktoken = outlinks.get(k).attributes().get("href"); try { Document tokendoc = Jsoup.connect(linktoken).get(); Elements stats = tokendoc.select("head meta"); - for (int j = 0; j < stats.size(); j++){ + for (int j = 0; j < stats.size(); j++) { String a = stats.get(j).attributes().get("content"); - if(stats.get(j).attributes().get("content").contains(tokenstats) && stats.get(j).attributes().get("content").toLowerCase().contains(name.toLowerCase())){ + if (stats.get(j).attributes().get("content").contains(tokenstats) && stats.get(j).attributes().get("content").toLowerCase().contains(name.toLowerCase())) { System.out.println("Token " + name + " has been found between " + currentSet.toUpperCase() + " tokens, i will use this one"); return tokendoc; } } - } catch (Exception e) {} + } catch (Exception e) { + } } - } catch (Exception e) {} + } catch (Exception e) { + } } } System.err.println("Error: Token " + name + " has not been found between any set of " + imageurl); @@ -181,8 +190,8 @@ public class ImgDownloader { public static String DownloadCardImages(String set, String[] availableSets, String targetres, String basePath, String destinationPath) throws IOException { String res = ""; - - String baseurl = "https://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid="; + + String baseurl = "https://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid="; String imageurl = "https://scryfall.com/sets/"; Integer ImgX = 0; @@ -201,57 +210,57 @@ public class ImgDownloader { ThumbX = 45; ThumbY = 64; } - + File baseFolder = new File(basePath); File[] listOfFiles = baseFolder.listFiles(); - String currentSet = ""; + String currentSet = ""; for (int f = 1; f < availableSets.length; f++) { - if(set.equalsIgnoreCase("*.*")) - currentSet = availableSets[f]; - else - currentSet = set; - Map mappa = new HashMap(); - ZipFile zipFile = null; - InputStream stream = null; - java.nio.file.Path filePath = null; - try { + if (set.equalsIgnoreCase("*.*")) + currentSet = availableSets[f]; + else + currentSet = set; + Map mappa = new HashMap(); + ZipFile zipFile = null; + InputStream stream = null; + java.nio.file.Path filePath = null; + try { zipFile = new ZipFile(basePath + "/" + listOfFiles[0].getName()); Enumeration e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryName = entry.getName(); - if(entryName.contains("sets/")){ - if(entryName.contains("_cards.dat")){ - String[] names = entryName.split("/"); - if(currentSet.equalsIgnoreCase(names[1])){ - stream = zipFile.getInputStream(entry); - byte[] buffer = new byte[1]; - java.nio.file.Path outDir = Paths.get(basePath); - filePath = outDir.resolve("_cards.dat"); + if (entryName.contains("sets/")) { + if (entryName.contains("_cards.dat")) { + String[] names = entryName.split("/"); + if (currentSet.equalsIgnoreCase(names[1])) { + stream = zipFile.getInputStream(entry); + byte[] buffer = new byte[1]; + java.nio.file.Path outDir = Paths.get(basePath); + filePath = outDir.resolve("_cards.dat"); try { - FileOutputStream fos = new FileOutputStream(filePath.toFile()); - BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length); - int len; - while ((len = stream.read(buffer)) != -1) { - bos.write(buffer, 0, len); - } - fos.close(); - bos.close(); - } catch (Exception ex) { - System.out.println("Error extracting zip file" + ex); - } - if(!set.equalsIgnoreCase("*.*")) - f = availableSets.length; - break; - } + FileOutputStream fos = new FileOutputStream(filePath.toFile()); + BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length); + int len; + while ((len = stream.read(buffer)) != -1) { + bos.write(buffer, 0, len); + } + fos.close(); + bos.close(); + } catch (Exception ex) { + System.out.println("Error extracting zip file" + ex); + } + if (!set.equalsIgnoreCase("*.*")) + f = availableSets.length; + break; + } } - } - } - } catch (IOException ioe){ + } + } + } catch (IOException ioe) { System.out.println("Error opening zip file" + ioe); } finally { try { - if (zipFile!=null) { + if (zipFile != null) { zipFile.close(); } } catch (IOException ioe) { @@ -260,27 +269,27 @@ public class ImgDownloader { } String lines = readLineByLineJava8(filePath.toString()); - File del = new File(filePath.toString()); - del.delete(); - int totalcards = 0; + File del = new File(filePath.toString()); + del.delete(); + int totalcards = 0; String findStr = "total="; int lastIndex = lines.indexOf(findStr); String totals = lines.substring(lastIndex, lines.indexOf("\n", lastIndex)); - totalcards = Integer.parseInt(totals.split("=")[1]); - for (int i = 0; i < totalcards; i++) { + totalcards = Integer.parseInt(totals.split("=")[1]); + while (lines.contains("[card]")) { findStr = "[card]"; - lastIndex = lines.indexOf(findStr); - String id = null; - String primitive = null; - int a = lines.indexOf("primitive=",lastIndex); - if(a > 0) - primitive = lines.substring(a, lines.indexOf("\n",a)).replace("//", "-").split("=")[1]; - int b = lines.indexOf("id=",lastIndex); - if(b > 0) - id = lines.substring(b, lines.indexOf("\n",b)).replace("-", "").split("=")[1]; - int c = lines.indexOf("[/card]",lastIndex); - if(c > 0) - lines = lines.substring(c + 8); + lastIndex = lines.indexOf(findStr); + String id = null; + String primitive = null; + int a = lines.indexOf("primitive=", lastIndex); + if (a > 0) + primitive = lines.substring(a, lines.indexOf("\n", a)).replace("//", "-").split("=")[1]; + int b = lines.indexOf("id=", lastIndex); + if (b > 0) + id = lines.substring(b, lines.indexOf("\n", b)).replace("-", "").split("=")[1]; + int c = lines.indexOf("[/card]", lastIndex); + if (c > 0) + lines = lines.substring(c + 8); if (primitive != null && id != null && !id.equalsIgnoreCase("null")) mappa.put(id, primitive); } @@ -321,57 +330,57 @@ public class ImgDownloader { String id = mappa.keySet().toArray()[y].toString(); Document doc = Jsoup.connect(baseurl + id).get(); Elements divs = doc.select("body div"); - String scryset = currentSet; - if(scryset.equalsIgnoreCase("MRQ")) + String scryset = currentSet; + if (scryset.equalsIgnoreCase("MRQ")) scryset = "MMQ"; - else if(scryset.equalsIgnoreCase("AVN")) + else if (scryset.equalsIgnoreCase("AVN")) scryset = "DDH"; - else if(scryset.equalsIgnoreCase("BVC")) + else if (scryset.equalsIgnoreCase("BVC")) scryset = "DDQ"; - else if(scryset.equalsIgnoreCase("CFX")) + else if (scryset.equalsIgnoreCase("CFX")) scryset = "CON"; - else if(scryset.equalsIgnoreCase("DM")) + else if (scryset.equalsIgnoreCase("DM")) scryset = "DKM"; - else if(scryset.equalsIgnoreCase("EVK")) + else if (scryset.equalsIgnoreCase("EVK")) scryset = "DDO"; - else if(scryset.equalsIgnoreCase("EVT")) + else if (scryset.equalsIgnoreCase("EVT")) scryset = "DDF"; - else if(scryset.equalsIgnoreCase("FVD")) + else if (scryset.equalsIgnoreCase("FVD")) scryset = "DRB"; - else if(scryset.equalsIgnoreCase("FVE")) + else if (scryset.equalsIgnoreCase("FVE")) scryset = "V09"; - else if(scryset.equalsIgnoreCase("FVL")) + else if (scryset.equalsIgnoreCase("FVL")) scryset = "V11"; - else if(scryset.equalsIgnoreCase("FVR")) + else if (scryset.equalsIgnoreCase("FVR")) scryset = "V10"; - else if(scryset.equalsIgnoreCase("HVM")) + else if (scryset.equalsIgnoreCase("HVM")) scryset = "DDL"; - else if(scryset.equalsIgnoreCase("IVG")) + else if (scryset.equalsIgnoreCase("IVG")) scryset = "DDJ"; - else if(scryset.equalsIgnoreCase("JVV")) + else if (scryset.equalsIgnoreCase("JVV")) scryset = "DDM"; - else if(scryset.equalsIgnoreCase("KVD")) + else if (scryset.equalsIgnoreCase("KVD")) scryset = "DDG"; - else if(scryset.equalsIgnoreCase("PDS")) + else if (scryset.equalsIgnoreCase("PDS")) scryset = "H09"; - else if(scryset.equalsIgnoreCase("PVC")) + else if (scryset.equalsIgnoreCase("PVC")) scryset = "DDE"; - else if(scryset.equalsIgnoreCase("RV")) + else if (scryset.equalsIgnoreCase("RV")) scryset = "3ED"; - else if(scryset.equalsIgnoreCase("SVT")) + else if (scryset.equalsIgnoreCase("SVT")) scryset = "DDK"; - else if(scryset.equalsIgnoreCase("VVK")) + else if (scryset.equalsIgnoreCase("VVK")) scryset = "DDI"; - else if(scryset.equalsIgnoreCase("ZVE")) + else if (scryset.equalsIgnoreCase("ZVE")) scryset = "DDP"; - try { + try { doc = Jsoup.connect(imageurl + scryset.toLowerCase()).get(); } catch (Exception e) { System.err.println("Problem downloading card: " + mappa.get(id) + " (" + id + ") from " + scryset + " on ScryFall"); - res = mappa.get(id) + "-" + currentSet + "/" + id + ".jpg\n" + res; + res = mappa.get(id) + "-" + currentSet + "/" + id + ".jpg\n" + res; continue; } - try { + try { doc = Jsoup.connect(imageurl + scryset.toLowerCase()).get(); } catch (Exception e) { System.err.println("Error: Problem downloading card: " + mappa.get(id) + "-" + id + " from " + scryset + " on ScryFall, i will retry 2 times more..."); @@ -383,7 +392,7 @@ public class ImgDownloader { doc = Jsoup.connect(imageurl + scryset.toLowerCase()).get(); } catch (Exception e3) { System.err.println("Error: Problem downloading card: " + mappa.get(id) + "-" + id + " from " + scryset + " on ScryFall, i will not retry anymore..."); - res = mappa.get(id) + " - " + currentSet + "/" + id + ".jpg\n" + res; + res = mappa.get(id) + " - " + currentSet + "/" + id + ".jpg\n" + res; continue; } } @@ -420,17 +429,17 @@ public class ImgDownloader { fos.write(response); fos.close(); - Bitmap yourBitmap = BitmapFactory.decodeFile(cardimage); - Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, ImgX, ImgY, true); + Bitmap yourBitmap = BitmapFactory.decodeFile(cardimage); + Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, ImgX, ImgY, true); try { - FileOutputStream fout = new FileOutputStream(cardimage); - resized.compress(Bitmap.CompressFormat.JPEG, 100, fout); - } catch (IOException e) { - e.printStackTrace(); - } - Bitmap resizedThumb = Bitmap.createScaledBitmap(yourBitmap, ThumbX, ThumbY, true); + FileOutputStream fout = new FileOutputStream(cardimage); + resized.compress(Bitmap.CompressFormat.JPEG, 100, fout); + } catch (IOException e) { + e.printStackTrace(); + } + Bitmap resizedThumb = Bitmap.createScaledBitmap(yourBitmap, ThumbX, ThumbY, true); try { - FileOutputStream fout = new FileOutputStream(thumbcardimage); + FileOutputStream fout = new FileOutputStream(thumbcardimage); resizedThumb.compress(Bitmap.CompressFormat.JPEG, 100, fout); } catch (IOException e) { e.printStackTrace(); @@ -494,28 +503,28 @@ public class ImgDownloader { String nametoken = ""; String nametocheck = ""; String tokenstats = ""; - for (int l = 1; l < arrays.length - 1; l++) { - if (arrays[l].equalsIgnoreCase("creature") && arrays[l + 1].toLowerCase().contains("token")) { - nametoken = arrays[l - 1]; - if(l - 3 > 0) - tokenstats = arrays[l - 3]; - if(nametoken.equalsIgnoreCase("artifact")){ - if(l - 2 > 0) - nametoken = arrays[l - 2]; - if(l - 4 > 0) - tokenstats = arrays[l - 4]; - } - break; - } else if (arrays[l].equalsIgnoreCase("put") && arrays[l + 3].toLowerCase().contains("token")) { - nametoken = arrays[l + 2]; - for (int j = 1; j < arrays.length - 1; j++) { - if (arrays[j].contains("/")) - tokenstats = arrays[j]; - } - break; - } - } - if (nametoken.isEmpty() || tokenstats.isEmpty()) { + for (int l = 1; l < arrays.length - 1; l++) { + if (arrays[l].equalsIgnoreCase("creature") && arrays[l + 1].toLowerCase().contains("token")) { + nametoken = arrays[l - 1]; + if (l - 3 > 0) + tokenstats = arrays[l - 3]; + if (nametoken.equalsIgnoreCase("artifact")) { + if (l - 2 > 0) + nametoken = arrays[l - 2]; + if (l - 4 > 0) + tokenstats = arrays[l - 4]; + } + break; + } else if (arrays[l].equalsIgnoreCase("put") && arrays[l + 3].toLowerCase().contains("token")) { + nametoken = arrays[l + 2]; + for (int j = 1; j < arrays.length - 1; j++) { + if (arrays[j].contains("/")) + tokenstats = arrays[j]; + } + break; + } + } + if (nametoken.isEmpty() || tokenstats.isEmpty()) { tokenfound = false; nametoken = "Unknown"; nametocheck = mappa.get(id); @@ -525,7 +534,7 @@ public class ImgDownloader { doc = findTokenPage(imageurl, nametoken, scryset, availableSets, tokenstats); tokenfound = true; nametocheck = nametoken; - } catch(Exception e) { + } catch (Exception e) { tokenfound = false; nametocheck = mappa.get(id); doc = Jsoup.connect(imageurl + scryset.toLowerCase()).get(); @@ -557,28 +566,28 @@ public class ImgDownloader { } else { tokenimage = imgPath + "/" + id + "t.jpg"; tokenthumbimage = thumbPath + "/" + id + "t.jpg"; - System.err.println("Error: Problem downloading token: " + nametoken + " (" + id + "t) i will use the same image of its source card"); - res = nametoken + " - " + currentSet + "/" + id + "t.jpg\n" + res; + System.err.println("Error: Problem downloading token: " + nametoken + " (" + id + "t) i will use the same image of its source card"); + res = nametoken + " - " + currentSet + "/" + id + "t.jpg\n" + res; } FileOutputStream fos2 = new FileOutputStream(tokenimage); fos2.write(responsetoken); fos2.close(); - - Bitmap yourBitmapToken = BitmapFactory.decodeFile(tokenimage); + + Bitmap yourBitmapToken = BitmapFactory.decodeFile(tokenimage); Bitmap resizedToken = Bitmap.createScaledBitmap(yourBitmapToken, ImgX, ImgY, true); - try { - FileOutputStream fout = new FileOutputStream(tokenimage); + try { + FileOutputStream fout = new FileOutputStream(tokenimage); resizedToken.compress(Bitmap.CompressFormat.JPEG, 100, fout); - } catch (IOException e) { - e.printStackTrace(); - } - Bitmap resizedThumbToken = Bitmap.createScaledBitmap(yourBitmapToken, ThumbX, ThumbY, true); - try { - FileOutputStream fout = new FileOutputStream(tokenthumbimage); + } catch (IOException e) { + e.printStackTrace(); + } + Bitmap resizedThumbToken = Bitmap.createScaledBitmap(yourBitmapToken, ThumbX, ThumbY, true); + try { + FileOutputStream fout = new FileOutputStream(tokenthumbimage); resizedThumbToken.compress(Bitmap.CompressFormat.JPEG, 100, fout); - } catch (IOException e) { - e.printStackTrace(); - } + } catch (IOException e) { + e.printStackTrace(); + } break; } @@ -589,39 +598,40 @@ public class ImgDownloader { } } } - try { - try { - File oldzip = new File(destinationPath + "/" + set + "/" + set + ".zip"); - oldzip.delete(); - } catch (Exception e) {} - ZipParameters zipParameters = new ZipParameters(); - zipParameters.setCompressionMethod(CompressionMethod.STORE); - File folder = new File(destinationPath + set + "/"); - File[] listOfFile = folder.listFiles(); - net.lingala.zip4j.ZipFile zipped = new net.lingala.zip4j.ZipFile(destinationPath + "/" + set + "/" + set + ".zip"); - for (int i = 0 ; i < listOfFile.length; i++){ - if(listOfFile[i].isDirectory()){ - zipped.addFolder(listOfFile[i],zipParameters); - } else { - zipped.addFile(listOfFile[i], zipParameters); - } - } - File destFolder = new File(destinationPath + set + "/"); + try { + try { + File oldzip = new File(destinationPath + "/" + set + "/" + set + ".zip"); + oldzip.delete(); + } catch (Exception e) { + } + ZipParameters zipParameters = new ZipParameters(); + zipParameters.setCompressionMethod(CompressionMethod.STORE); + File folder = new File(destinationPath + set + "/"); + File[] listOfFile = folder.listFiles(); + net.lingala.zip4j.ZipFile zipped = new net.lingala.zip4j.ZipFile(destinationPath + "/" + set + "/" + set + ".zip"); + for (int i = 0; i < listOfFile.length; i++) { + if (listOfFile[i].isDirectory()) { + zipped.addFolder(listOfFile[i], zipParameters); + } else { + zipped.addFile(listOfFile[i], zipParameters); + } + } + File destFolder = new File(destinationPath + set + "/"); listOfFiles = destFolder.listFiles(); - for(int u = 0; u < listOfFiles.length; u++){ - if (!listOfFiles[u].getName().contains(".zip")){ - if(listOfFiles[u].isDirectory()){ + for (int u = 0; u < listOfFiles.length; u++) { + if (!listOfFiles[u].getName().contains(".zip")) { + if (listOfFiles[u].isDirectory()) { File[] listOfSubFiles = listOfFiles[u].listFiles(); - for(int j = 0; j < listOfSubFiles.length; j++) + for (int j = 0; j < listOfSubFiles.length; j++) listOfSubFiles[j].delete(); } listOfFiles[u].delete(); } } - } catch (Exception e) { - e.printStackTrace(); - } - } - return res; + } catch (Exception e) { + e.printStackTrace(); + } + } + return res; } } diff --git a/projects/mtg/Android/src/org/libsdl/app/SDLActivity.java b/projects/mtg/Android/src/org/libsdl/app/SDLActivity.java index 397254b0a..991757db9 100644 --- a/projects/mtg/Android/src/org/libsdl/app/SDLActivity.java +++ b/projects/mtg/Android/src/org/libsdl/app/SDLActivity.java @@ -3,6 +3,7 @@ package org.libsdl.app; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.Enumeration; + import android.os.StrictMode; import java.io.BufferedInputStream; @@ -69,67 +70,63 @@ import android.widget.FrameLayout.LayoutParams; /** * SDL Activity */ -public class SDLActivity extends Activity implements OnKeyListener -{ - private static final String TAG = SDLActivity.class.getCanonicalName(); +public class SDLActivity extends Activity implements OnKeyListener { + private static final String TAG = SDLActivity.class.getCanonicalName(); //import deck globals - public ArrayList myresult = new ArrayList(); - public String myclickedItem = ""; + public ArrayList myresult = new ArrayList(); + public String myclickedItem = ""; // Main components private static SDLActivity mSingleton; - private static SDLSurface mSurface; + private static SDLSurface mSurface; // Audio - private static Thread mAudioThread; - private static AudioTrack mAudioTrack; + private static Thread mAudioThread; + private static AudioTrack mAudioTrack; // Resource download - public static final int DIALOG_DOWNLOAD_PROGRESS = 0; - public static final int DIALOG_DOWNLOAD_ERROR = 1; - private ProgressDialog mProgressDialog; - private AlertDialog mErrorDialog; - public String mErrorMessage = ""; - public Boolean mErrorHappened = false; - public final static String RES_FOLDER = Environment.getExternalStorageDirectory().getPath() + "/Wagic/Res/"; - public static String RES_FILENAME = "core_0211.zip"; - public static String RES_URL = "https://github.com/Vitty85/wagic/releases/download/wagic-v0.21.1/core_0211.zip"; + public static final int DIALOG_DOWNLOAD_PROGRESS = 0; + public static final int DIALOG_DOWNLOAD_ERROR = 1; + private ProgressDialog mProgressDialog; + private AlertDialog mErrorDialog; + public String mErrorMessage = ""; + public Boolean mErrorHappened = false; + public final static String RES_FOLDER = Environment.getExternalStorageDirectory().getPath() + "/Wagic/Res/"; + public static String RES_FILENAME = "core_0211.zip"; + public static String RES_URL = "https://github.com/Vitty85/wagic/releases/download/wagic-v0.21.1/core_0211.zip"; - public String systemFolder = Environment.getExternalStorageDirectory().getPath() + "/Wagic/Res/"; - private String userFolder = Environment.getExternalStorageDirectory().getPath() + "/Wagic/User/"; + public String systemFolder = Environment.getExternalStorageDirectory().getPath() + "/Wagic/Res/"; + private String userFolder = Environment.getExternalStorageDirectory().getPath() + "/Wagic/User/"; // path to the onboard sd card that is not removable (typically /mnt/sdcard ) - private String internalPath = ""; + private String internalPath = ""; // path to removable sd card (on motorala devices /mnt/sdcard-ext, samsung devices: /mnt/sdcard/external_sd ) - private String sdcardPath = ""; + private String sdcardPath = ""; // Android only supports internal memory and internal sdcard. removable media is not currently accessible via API // using StorageOptions for now gives us a temporary interface to scan all available mounted drives. - private Context mContext; + private Context mContext; // Preferences - public static final String kWagicSharedPreferencesKey = "net.wagic.app.preferences.wagic"; + public static final String kWagicSharedPreferencesKey = "net.wagic.app.preferences.wagic"; public static final String kStoreDataOnRemovableSdCardPreference = "StoreDataOnRemovableStorage"; - public static final String kSaveDataPathPreference = "StorageDataLocation"; - public static final String kWagicDataStorageOptionsKey = "dataStorageOptions"; - public static final int kStorageDataOptionsMenuId = 2000; - public static final int kOtherOptionsMenuId = 3000; + public static final String kSaveDataPathPreference = "StorageDataLocation"; + public static final String kWagicDataStorageOptionsKey = "dataStorageOptions"; + public static final int kStorageDataOptionsMenuId = 2000; + public static final int kOtherOptionsMenuId = 3000; // Accessors - public String getSystemStorageLocation() - { + public String getSystemStorageLocation() { return systemFolder; } - public String getUserStorageLocation() - { + public String getUserStorageLocation() { return userFolder; } // setters - public void updateStorageLocations() - { + public void updateStorageLocations() { boolean usesInternalSdCard = (!getSharedPreferences(kWagicSharedPreferencesKey, MODE_PRIVATE).getBoolean(kStoreDataOnRemovableSdCardPreference, false)) && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); systemFolder = (usesInternalSdCard ? internalPath : sdcardPath) + "/Res/"; @@ -138,11 +135,10 @@ public class SDLActivity extends Activity implements OnKeyListener /** * checks to see if the device has a memory card to write to that is in a valid state. - * + * * @return true if the device can write to the sdcard, false if not. */ - public boolean checkStorageState() - { + public boolean checkStorageState() { SharedPreferences settings = getSharedPreferences(kWagicSharedPreferencesKey, MODE_PRIVATE); boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; @@ -150,14 +146,12 @@ public class SDLActivity extends Activity implements OnKeyListener boolean useSdCard = (!settings.getBoolean(kStoreDataOnRemovableSdCardPreference, false)) && mExternalStorageWriteable; String systemStoragePath = getSystemStorageLocation(); - if (useSdCard && (systemStoragePath.indexOf(sdcardPath) != -1)) - { + if (useSdCard && (systemStoragePath.indexOf(sdcardPath) != -1)) { Log.i(TAG, "Data will be written to sdcard."); return true; } - if (!useSdCard && (systemStoragePath.indexOf(internalPath) != -1)) - { + if (!useSdCard && (systemStoragePath.indexOf(internalPath) != -1)) { Log.i(TAG, "Data will be written to internal storage."); return true; } @@ -173,15 +167,13 @@ public class SDLActivity extends Activity implements OnKeyListener // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; - } - + } + return (mExternalStorageAvailable && mExternalStorageWriteable); } - private boolean getRemovableMediaStorageState() - { - for (String extMediaPath : StorageOptions.paths) - { + private boolean getRemovableMediaStorageState() { + for (String extMediaPath : StorageOptions.paths) { File mediaPath = new File(extMediaPath); if (mediaPath.canWrite()) return true; @@ -190,23 +182,18 @@ public class SDLActivity extends Activity implements OnKeyListener return false; } - private void displayStorageOptions() - { + private void displayStorageOptions() { AlertDialog.Builder setStorage = new AlertDialog.Builder(this); setStorage.setTitle("Where would you like to store your data? On your removable SD Card or the built-in memory?"); StorageOptions.determineStorageOptions(); - setStorage.setSingleChoiceItems(StorageOptions.labels, -1, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int item) - { + setStorage.setSingleChoiceItems(StorageOptions.labels, -1, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int item) { savePathPreference(item); } }); - setStorage.setPositiveButton("OK", new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { + setStorage.setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { initStorage(); if (mSurface == null) mSingleton.initializeGame(); @@ -215,36 +202,30 @@ public class SDLActivity extends Activity implements OnKeyListener setStorage.create().show(); } - - private void importDeckOptions() - { + + private void importDeckOptions() { AlertDialog.Builder importDeck = new AlertDialog.Builder(this); importDeck.setTitle("Choose Deck to Import:"); - File root = new File(System.getenv("EXTERNAL_STORAGE")+"/Download"); + File root = new File(System.getenv("EXTERNAL_STORAGE") + "/Download"); File[] files = root.listFiles(); - for( File f : files) - { - if( !myresult.contains(f.toString()) && (f.toString().contains(".txt")||f.toString().contains(".dck")||f.toString().contains(".dec"))) + for (File f : files) { + if (!myresult.contains(f.toString()) && (f.toString().contains(".txt") || f.toString().contains(".dck") || f.toString().contains(".dec"))) myresult.add(f.toString()); } - + //get first item? - if(!myresult.isEmpty()) + if (!myresult.isEmpty()) myclickedItem = myresult.get(0).toString(); - - importDeck.setSingleChoiceItems(myresult.toArray(new String[myresult.size()]), 0, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int item) - { + + importDeck.setSingleChoiceItems(myresult.toArray(new String[myresult.size()]), 0, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int item) { myclickedItem = myresult.get(item).toString(); } }); - importDeck.setPositiveButton("Import Deck", new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { - processSelectedDeck( myclickedItem ); + importDeck.setPositiveButton("Import Deck", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + processSelectedDeck(myclickedItem); if (mSurface == null) mSingleton.initializeGame(); } @@ -252,46 +233,39 @@ public class SDLActivity extends Activity implements OnKeyListener importDeck.create().show(); } - - private void processSelectedDeck(String mypath) - { + + private void processSelectedDeck(String mypath) { AlertDialog.Builder infoDialog = new AlertDialog.Builder(this); infoDialog.setTitle("Imported Deck:"); String activePath = sdcardPath; - if(activePath == ""){ + if (activePath == "") { activePath = internalPath; } - + File f = new File(mypath); //Call the deck importer.... String state = DeckImporter.importDeck(f, mypath, activePath); infoDialog.setMessage(state); infoDialog.show(); } - - private void checkStorageLocationPreference() - { + + private void checkStorageLocationPreference() { SharedPreferences settings = getSharedPreferences(kWagicSharedPreferencesKey, MODE_PRIVATE); final SharedPreferences.Editor prefsEditor = settings.edit(); boolean hasRemovableMediaMounted = getRemovableMediaStorageState(); - if (!settings.contains(kStoreDataOnRemovableSdCardPreference)) - { - if (hasRemovableMediaMounted) - { + if (!settings.contains(kStoreDataOnRemovableSdCardPreference)) { + if (hasRemovableMediaMounted) { displayStorageOptions(); - } else - { + } else { prefsEditor.putBoolean(kStoreDataOnRemovableSdCardPreference, false); prefsEditor.commit(); initStorage(); mSingleton.initializeGame(); } - } else - { + } else { boolean storeOnRemovableMedia = settings.getBoolean(kStoreDataOnRemovableSdCardPreference, false); - if (storeOnRemovableMedia && !hasRemovableMediaMounted) - { + if (storeOnRemovableMedia && !hasRemovableMediaMounted) { AlertDialog setStorage = new AlertDialog.Builder(this).create(); setStorage.setTitle("Storage Preference"); setStorage.setMessage("Removable Sd Card not detected. Saving data to internal memory."); @@ -302,21 +276,18 @@ public class SDLActivity extends Activity implements OnKeyListener initStorage(); mSingleton.initializeGame(); setStorage.show(); - } else - { + } else { initStorage(); mSingleton.initializeGame(); } } } - private void initStorage() - { + private void initStorage() { // check the state of the external storage to ensure we can even write to it. // we are going to assume that if an external location exists, and can be written to, use it. // Otherwise use internal storage - try - { + try { // // initialize where all the files are going to be stored. // @@ -324,14 +295,12 @@ public class SDLActivity extends Activity implements OnKeyListener // String packageName = mContext.getPackageName(); // possibly use this to differentiate between different mods of Wagic. File externalFilesDir = Environment.getExternalStorageDirectory(); - if (externalFilesDir != null) - { + if (externalFilesDir != null) { internalPath = externalFilesDir.getAbsolutePath() + "/Wagic"; } String state = Environment.getExternalStorageState(); - if (Environment.MEDIA_MOUNTED.equals(state)) - { + if (Environment.MEDIA_MOUNTED.equals(state)) { wagicMediaPath = new File(internalPath); if (wagicMediaPath.canWrite()) wagicMediaPath.mkdirs(); @@ -340,27 +309,22 @@ public class SDLActivity extends Activity implements OnKeyListener // initialize the external mount SharedPreferences settings = getSharedPreferences(kWagicSharedPreferencesKey, MODE_PRIVATE); String selectedRemovableCardPath = settings.getString(kSaveDataPathPreference, internalPath); - if (selectedRemovableCardPath != null && !internalPath.equalsIgnoreCase(selectedRemovableCardPath)) - { + if (selectedRemovableCardPath != null && !internalPath.equalsIgnoreCase(selectedRemovableCardPath)) { wagicMediaPath = new File(selectedRemovableCardPath); - if (!wagicMediaPath.exists() || !wagicMediaPath.canWrite()) - { + if (!wagicMediaPath.exists() || !wagicMediaPath.canWrite()) { Log.e(TAG, "Error in initializing system folder: " + selectedRemovableCardPath); - } else - { // found a removable media location + } else { // found a removable media location sdcardPath = selectedRemovableCardPath + "/Wagic"; } } updateStorageLocations(); - } catch (Exception ioex) - { + } catch (Exception ioex) { Log.e(TAG, "An error occurred in setting up the storage locations."); } } - private void savePathPreference(int selectedOption) - { + private void savePathPreference(int selectedOption) { SharedPreferences settings = getSharedPreferences(kWagicSharedPreferencesKey, MODE_PRIVATE); String selectedMediaPath = StorageOptions.paths[selectedOption]; final SharedPreferences.Editor prefsEditor = settings.edit(); @@ -372,108 +336,95 @@ public class SDLActivity extends Activity implements OnKeyListener } - private void startDownload() - { + private void startDownload() { //String url = getResourceUrl(); - String url = RES_URL; - if (!checkStorageState()) - { + String url = RES_URL; + if (!checkStorageState()) { Log.e(TAG, "Error in initializing storage space."); mSingleton.downloadError("Failed to initialize storage space for game. Please verify that your sdcard or internal memory is mounted properly."); } new DownloadFileAsync().execute(url); } - public void downloadError(String errorMessage) - { + public void downloadError(String errorMessage) { mErrorHappened = true; mErrorMessage = errorMessage; } - private void buildStorageOptionsMenu(Menu menu) - { + private void buildStorageOptionsMenu(Menu menu) { StorageOptions.determineStorageOptions(); - for (int idx = 0; idx < StorageOptions.count; idx++) - { + for (int idx = 0; idx < StorageOptions.count; idx++) { menu.add(kStorageDataOptionsMenuId, kStorageDataOptionsMenuId + idx, idx, StorageOptions.labels[idx]); } } String set = ""; - String [] availableSets; + String[] availableSets; Integer totalset = 0; - - private void downloadCardImages() - { + + private void downloadCardImages() { AlertDialog.Builder cardDownloader = new AlertDialog.Builder(this); cardDownloader.setTitle("Which Set would you like to download?"); File baseFolder = new File(getSystemStorageLocation()); File[] listOfFiles = baseFolder.listFiles(); ArrayList sets = new ArrayList(); - ZipFile zipFile = null; + ZipFile zipFile = null; try { zipFile = new ZipFile(baseFolder + "/" + listOfFiles[0].getName()); Enumeration e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); String entryName = entry.getName(); - if(entryName.contains("sets/")){ - if(!entryName.equalsIgnoreCase("sets/") && !entryName.contains("primitives") && !entryName.contains(".")){ - String[] names = entryName.split("/"); - sets.add(names[1]); - } - } - } - } - catch (IOException ioe) { - System.out.println("Error opening zip file" + ioe); - } - finally { - try { - if (zipFile!=null) { - zipFile.close(); + if (entryName.contains("sets/")) { + if (!entryName.equalsIgnoreCase("sets/") && !entryName.contains("primitives") && !entryName.contains(".")) { + String[] names = entryName.split("/"); + sets.add(names[1]); + } } } - catch (IOException ioe) { + } catch (IOException ioe) { + System.out.println("Error opening zip file" + ioe); + } finally { + try { + if (zipFile != null) { + zipFile.close(); + } + } catch (IOException ioe) { System.out.println("Error while closing zip file" + ioe); } } - availableSets = new String[sets.size() + 1]; - availableSets[0] = "*.* - All Wagic sets (thousands of cards)"; - for (int i = 1; i < availableSets.length; i++){ - availableSets[i] = sets.get(i-1) + " - " + ImgDownloader.getSetInfo(sets.get(i-1), true, getSystemStorageLocation()); - } - cardDownloader.setSingleChoiceItems(availableSets, -1, new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int item) - { + availableSets = new String[sets.size() + 1]; + availableSets[0] = "*.* - All Wagic sets (thousands of cards)"; + for (int i = 1; i < availableSets.length; i++) { + availableSets[i] = sets.get(i - 1) + " - " + ImgDownloader.getSetInfo(sets.get(i - 1), true, getSystemStorageLocation()); + } + cardDownloader.setSingleChoiceItems(availableSets, -1, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int item) { set = availableSets[item].split(" - ")[0]; - downloadCardStarting(set); + downloadCardStarting(set); } }); - cardDownloader.setPositiveButton("OK", new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int which) - { + cardDownloader.setPositiveButton("OK", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { boolean error = false; - String res = ""; - try{ - res = ImgDownloader.DownloadCardImages(set, availableSets, "HI", getSystemStorageLocation(), getUserStorageLocation() + "sets/"); - } catch(Exception e) { - res = e.getMessage(); - error = true; - } - downloadCardCompleted(error, res, set); + String res = ""; + try { + res = ImgDownloader.DownloadCardImages(set, availableSets, "HI", getSystemStorageLocation(), getUserStorageLocation() + "sets/"); + } catch (Exception e) { + res = e.getMessage(); + error = true; + } + downloadCardCompleted(error, res, set); } }); cardDownloader.create().show(); } - private void downloadCardStarting(String set){ + private void downloadCardStarting(String set) { AlertDialog.Builder infoDialog = new AlertDialog.Builder(this); infoDialog.setTitle("You choose to Download: " + set); infoDialog.setMessage("After you press OK don't turn off phone or wi-fi/data connection and don't close Wagic.\nThe download process can take several minutes according to the number of images contained in the selected set (NOTE: if you choose *.* you will have to wait several hours!!!)"); @@ -481,24 +432,23 @@ public class SDLActivity extends Activity implements OnKeyListener } - private void downloadCardCompleted(boolean error, String res, String set){ + private void downloadCardCompleted(boolean error, String res, String set) { AlertDialog.Builder infoDialog = new AlertDialog.Builder(this); - if(!error){ - infoDialog.setTitle("Download Completed: " + set); - if(!res.isEmpty()) + if (!error) { + infoDialog.setTitle("Download Completed: " + set); + if (!res.isEmpty()) infoDialog.setMessage("Following cards could not be downloaded:\n" + res); - else + else infoDialog.setMessage("All the cards have been successfully downloaded"); } else { - infoDialog.setTitle("Error downloading: " + set); + infoDialog.setTitle("Error downloading: " + set); infoDialog.setMessage(res); - } - infoDialog.create().show(); + } + infoDialog.create().show(); } @Override - public boolean onCreateOptionsMenu(Menu menu) - { + public boolean onCreateOptionsMenu(Menu menu) { SubMenu settingsMenu = menu.addSubMenu(Menu.NONE, 1, 1, "Settings"); menu.add(Menu.NONE, 2, 2, "Import Decks"); menu.add(Menu.NONE, 3, 3, "Download Cards"); @@ -509,21 +459,16 @@ public class SDLActivity extends Activity implements OnKeyListener } @Override - public boolean onOptionsItemSelected(MenuItem item) - { + public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection int itemId = item.getItemId(); - if (itemId == kStorageDataOptionsMenuId) - { + if (itemId == kStorageDataOptionsMenuId) { displayStorageOptions(); - } else if (itemId == 2) - { + } else if (itemId == 2) { importDeckOptions(); - } else if (itemId == 3) - { - downloadCardImages(); - } else if (itemId == 4) - { + } else if (itemId == 3) { + downloadCardImages(); + } else if (itemId == 4) { // display some info about the app AlertDialog.Builder infoDialog = new AlertDialog.Builder(this); infoDialog.setTitle("Wagic Info"); @@ -536,38 +481,33 @@ public class SDLActivity extends Activity implements OnKeyListener } @Override - protected Dialog onCreateDialog(int id) - { - switch (id) - { - case DIALOG_DOWNLOAD_PROGRESS: - mProgressDialog = new ProgressDialog(this); - mProgressDialog.setMessage("Downloading resource files (" + RES_FILENAME + ")"); - mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); - mProgressDialog.setCancelable(false); - mProgressDialog.show(); - return mProgressDialog; - case DIALOG_DOWNLOAD_ERROR: - // prepare alertDialog - AlertDialog.Builder builder = new AlertDialog.Builder(this); - builder.setMessage(mErrorMessage).setCancelable(false).setPositiveButton("Exit", new DialogInterface.OnClickListener() - { - public void onClick(DialogInterface dialog, int id) - { - System.exit(0); - } - }); - mErrorDialog = builder.create(); - mErrorDialog.show(); - return mErrorDialog; - default: - return null; + protected Dialog onCreateDialog(int id) { + switch (id) { + case DIALOG_DOWNLOAD_PROGRESS: + mProgressDialog = new ProgressDialog(this); + mProgressDialog.setMessage("Downloading resource files (" + RES_FILENAME + ")"); + mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + mProgressDialog.setCancelable(false); + mProgressDialog.show(); + return mProgressDialog; + case DIALOG_DOWNLOAD_ERROR: + // prepare alertDialog + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setMessage(mErrorMessage).setCancelable(false).setPositiveButton("Exit", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + System.exit(0); + } + }); + mErrorDialog = builder.create(); + mErrorDialog.show(); + return mErrorDialog; + default: + return null; } } // Load the .so - static - { + static { System.loadLibrary("SDL"); // System.loadLibrary("SDL_image"); // System.loadLibrary("SDL_mixer"); @@ -576,8 +516,7 @@ public class SDLActivity extends Activity implements OnKeyListener } // create main application - public void mainDisplay() - { + public void mainDisplay() { FrameLayout _videoLayout = new FrameLayout(this); // mGLView = new DemoGLSurfaceView(this); @@ -593,37 +532,33 @@ public class SDLActivity extends Activity implements OnKeyListener // mGLView.setFocusableInTouchMode(true); // mGLView.setFocusable(true); // adView.requestFreshAd(); - setContentView(_videoLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); + setContentView(_videoLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); mSurface.requestFocus(); } // Setup @Override - protected void onCreate(Bundle savedInstanceState) - { + protected void onCreate(Bundle savedInstanceState) { //Log.d(TAG, "onCreate()"); super.onCreate(savedInstanceState); - StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); + StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); // So we can call stuff from static callbacks mSingleton = this; mContext = this.getApplicationContext(); //RES_FILENAME = getResourceName(); - StorageOptions.determineStorageOptions(); + StorageOptions.determineStorageOptions(); checkStorageLocationPreference(); } - public void initializeGame() - { + public void initializeGame() { String coreFileLocation = getSystemStorageLocation() + RES_FILENAME; File file = new File(coreFileLocation); - if (file.exists()) - { + if (file.exists()) { mainDisplay(); - } else - { + } else { FrameLayout _videoLayout = new FrameLayout(this); setContentView(_videoLayout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); startDownload(); @@ -632,24 +567,21 @@ public class SDLActivity extends Activity implements OnKeyListener // Events @Override - protected void onPause() - { + protected void onPause() { // Log.d(TAG, "onPause()"); super.onPause(); SDLActivity.nativePause(); } @Override - protected void onResume() - { + protected void onResume() { // Log.d(TAG, "onResume()"); super.onResume(); SDLActivity.nativeResume(); } @Override - public void onDestroy() - { + public void onDestroy() { // Log.d(TAG, "onDestroy()"); super.onDestroy(); mSurface.onDestroy(); @@ -657,36 +589,29 @@ public class SDLActivity extends Activity implements OnKeyListener // Handler for Messages coming from JGE // Suggested syntax for JGE messages is a string separated by the ":" symbol - protected void processJGEMsg(String command) - { - if (null == command) - { + protected void processJGEMsg(String command) { + if (null == command) { return; } } // Messages from the SDLMain thread static int COMMAND_CHANGE_TITLE = 1; - static int COMMAND_JGE_MSG = 2; + static int COMMAND_JGE_MSG = 2; // Handler for the messages - Handler commandHandler = new Handler() - { - public void handleMessage(Message msg) - { - if (msg.arg1 == COMMAND_CHANGE_TITLE) - { - setTitle((String) msg.obj); - } else if (msg.arg1 == COMMAND_JGE_MSG) - { - processJGEMsg((String) msg.obj); - } - } - }; + Handler commandHandler = new Handler() { + public void handleMessage(Message msg) { + if (msg.arg1 == COMMAND_CHANGE_TITLE) { + setTitle((String) msg.obj); + } else if (msg.arg1 == COMMAND_JGE_MSG) { + processJGEMsg((String) msg.obj); + } + } + }; // Send a message from the SDLMain thread - void sendCommand(int command, Object data) - { + void sendCommand(int command, Object data) { Message msg = commandHandler.obtainMessage(); msg.arg1 = command; msg.obj = data; @@ -695,6 +620,7 @@ public class SDLActivity extends Activity implements OnKeyListener // C functions we call public static native String getResourceUrl(); + public static native String getResourceName(); public static native void nativeInit(); @@ -721,33 +647,27 @@ public class SDLActivity extends Activity implements OnKeyListener // Java functions called from C // Receive a message from the SDLMain thread - public static String getSystemFolderPath() - { + public static String getSystemFolderPath() { return mSingleton.getSystemStorageLocation(); } - public static String getUserFolderPath() - { + public static String getUserFolderPath() { return mSingleton.getUserStorageLocation(); } - public static void jgeSendCommand(String command) - { + public static void jgeSendCommand(String command) { mSingleton.sendCommand(COMMAND_JGE_MSG, command); } - public static boolean createGLContext(int majorVersion, int minorVersion) - { + public static boolean createGLContext(int majorVersion, int minorVersion) { return mSurface.initEGL(majorVersion, minorVersion); } - public static void flipBuffers() - { + public static void flipBuffers() { mSurface.flipEGL(); } - public static void setActivityTitle(String title) - { + public static void setActivityTitle(String title) { // Called from SDLMain() thread and can't directly affect the view mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title); } @@ -755,8 +675,7 @@ public class SDLActivity extends Activity implements OnKeyListener // Audio private static Object buf; - public static Object audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) - { + public static Object audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) { int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO; int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT; int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1); @@ -775,22 +694,17 @@ public class SDLActivity extends Activity implements OnKeyListener // Log.d(TAG, "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + ((float)mAudioTrack.getSampleRate() / 1000f) + // "kHz, " + desiredFrames + " frames buffer"); - if (is16Bit) - { + if (is16Bit) { buf = new short[desiredFrames * (isStereo ? 2 : 1)]; - } else - { + } else { buf = new byte[desiredFrames * (isStereo ? 2 : 1)]; } return buf; } - public static void audioStartThread() - { - mAudioThread = new Thread(new Runnable() - { - public void run() - { + public static void audioStartThread() { + mAudioThread = new Thread(new Runnable() { + public void run() { mAudioTrack.play(); nativeRunAudioThread(); } @@ -801,65 +715,47 @@ public class SDLActivity extends Activity implements OnKeyListener mAudioThread.start(); } - public static void audioWriteShortBuffer(short[] buffer) - { - for (int i = 0; i < buffer.length;) - { + public static void audioWriteShortBuffer(short[] buffer) { + for (int i = 0; i < buffer.length; ) { int result = mAudioTrack.write(buffer, i, buffer.length - i); - if (result > 0) - { + if (result > 0) { i += result; - } else if (result == 0) - { - try - { + } else if (result == 0) { + try { Thread.sleep(1); - } catch (InterruptedException e) - { + } catch (InterruptedException e) { // Nom nom } - } else - { + } else { Log.w(TAG, "SDL audio: error return from write(short)"); return; } } } - public static void audioWriteByteBuffer(byte[] buffer) - { - for (int i = 0; i < buffer.length;) - { + public static void audioWriteByteBuffer(byte[] buffer) { + for (int i = 0; i < buffer.length; ) { int result = mAudioTrack.write(buffer, i, buffer.length - i); - if (result > 0) - { + if (result > 0) { i += result; - } else if (result == 0) - { - try - { + } else if (result == 0) { + try { Thread.sleep(1); - } catch (InterruptedException e) - { + } catch (InterruptedException e) { // Nom nom } - } else - { + } else { Log.w(TAG, "SDL audio: error return from write(short)"); return; } } } - public static void audioQuit() - { - if (mAudioThread != null) - { - try - { + public static void audioQuit() { + if (mAudioThread != null) { + try { mAudioThread.join(); - } catch (Exception e) - { + } catch (Exception e) { Log.e(TAG, "Problem stopping audio thread: " + e); } mAudioThread = null; @@ -867,34 +763,29 @@ public class SDLActivity extends Activity implements OnKeyListener // Log.d(TAG, "Finished waiting for audio thread"); } - if (mAudioTrack != null) - { + if (mAudioTrack != null) { mAudioTrack.stop(); mAudioTrack = null; } } - class DownloadFileAsync extends AsyncTask - { + class DownloadFileAsync extends AsyncTask { private final String TAG = DownloadFileAsync.class.getCanonicalName(); @Override - protected void onPreExecute() - { + protected void onPreExecute() { super.onPreExecute(); showDialog(DIALOG_DOWNLOAD_PROGRESS); } @Override - protected Long doInBackground(String... aurl) - { + protected Long doInBackground(String... aurl) { int count; long totalBytes = 0; OutputStream output = null; InputStream input = null; - try - { + try { // // Prepare the sdcard folders in order to download the resource file // @@ -904,8 +795,7 @@ public class SDLActivity extends Activity implements OnKeyListener File resDirectory = new File(storageLocation); File userDirectory = new File(mSingleton.getUserStorageLocation()); - if (!resDirectory.exists() && !resDirectory.mkdirs() || (!userDirectory.exists() && !userDirectory.mkdirs())) - { + if (!resDirectory.exists() && !resDirectory.mkdirs() || (!userDirectory.exists() && !userDirectory.mkdirs())) { throw new Exception("Failed to initialize system and user directories."); } @@ -924,8 +814,7 @@ public class SDLActivity extends Activity implements OnKeyListener output = new FileOutputStream(outputFile); byte data[] = new byte[1024]; - while ((count = input.read(data)) != -1) - { + while ((count = input.read(data)) != -1) { totalBytes += count; publishProgress((int) ((totalBytes * 100) / lengthOfFile)); output.write(data, 0, count); @@ -934,8 +823,7 @@ public class SDLActivity extends Activity implements OnKeyListener output.flush(); output.close(); input.close(); - } catch (Exception e) - { + } catch (Exception e) { String errorMessage = "An error happened while downloading the resources. It could be that our server is temporarily down, that your device is not connected to a network, or that we cannot write to " + mSingleton.getSystemStorageLocation() + ". Please check your phone settings and try again. For more help please go to http://wagic.net"; //mSingleton.downloadError(errorMessage); //Log.e(TAG, errorMessage); @@ -945,20 +833,16 @@ public class SDLActivity extends Activity implements OnKeyListener return Long.valueOf(totalBytes); } - protected void onProgressUpdate(Integer... progress) - { - if (progress[0] != mProgressDialog.getProgress()) - { + protected void onProgressUpdate(Integer... progress) { + if (progress[0] != mProgressDialog.getProgress()) { // Log.d(TAG, "current progress : " + progress[0]); mProgressDialog.setProgress(progress[0]); } } @Override - protected void onPostExecute(Long unused) - { - if (mErrorHappened) - { + protected void onPostExecute(Long unused) { + if (mErrorHappened) { dismissDialog(DIALOG_DOWNLOAD_PROGRESS); showDialog(DIALOG_DOWNLOAD_ERROR); return; @@ -978,14 +862,11 @@ public class SDLActivity extends Activity implements OnKeyListener } } - public boolean onKey(View v, int keyCode, KeyEvent event) - { - if ((keyCode == KeyEvent.KEYCODE_MENU) && (KeyEvent.ACTION_DOWN == event.getAction())) - { + public boolean onKey(View v, int keyCode, KeyEvent event) { + if ((keyCode == KeyEvent.KEYCODE_MENU) && (KeyEvent.ACTION_DOWN == event.getAction())) { super.onKeyDown(keyCode, event); return true; - } else if ((keyCode == KeyEvent.KEYCODE_MENU) && (KeyEvent.ACTION_UP == event.getAction())) - { + } else if ((keyCode == KeyEvent.KEYCODE_MENU) && (KeyEvent.ACTION_UP == event.getAction())) { super.onKeyUp(keyCode, event); return true; } @@ -993,14 +874,11 @@ public class SDLActivity extends Activity implements OnKeyListener return false; } - private String getApplicationCode() - { + private String getApplicationCode() { int v = 0; - try - { + try { v = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; - } catch (NameNotFoundException e) - { + } catch (NameNotFoundException e) { // Huh? Really? v = 184; // shouldn't really happen but we need to default to something } @@ -1009,42 +887,38 @@ public class SDLActivity extends Activity implements OnKeyListener // Empty onConfigurationChanged to stop the Activity from destroying/recreating on screen off @Override - public void onConfigurationChanged(Configuration newConfig) - { + public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } } /** * SDLSurface. This is what we draw on, so we need to know when it's created in order to do anything useful. - * + *

* Because of this, that's where we set up the SDL thread */ -class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnKeyListener, View.OnTouchListener, SensorEventListener -{ - private static final String TAG = SDLSurface.class.getCanonicalName(); +class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnKeyListener, View.OnTouchListener, SensorEventListener { + private static final String TAG = SDLSurface.class.getCanonicalName(); // This is what SDL runs in. It invokes SDL_main(), eventually - private Thread mSDLThread; + private Thread mSDLThread; // EGL private objects - private EGLContext mEGLContext; - private EGLSurface mEGLSurface; - private EGLDisplay mEGLDisplay; - private EGLConfig mEGLConfig; + private EGLContext mEGLContext; + private EGLSurface mEGLSurface; + private EGLDisplay mEGLDisplay; + private EGLConfig mEGLConfig; // Sensors - private static SensorManager mSensorManager; + private static SensorManager mSensorManager; private static VelocityTracker mVelocityTracker; - final private Object mSemSurface; - private Boolean mSurfaceValid; + final private Object mSemSurface; + private Boolean mSurfaceValid; - void startSDLThread() - { - if (mSDLThread == null) - { + void startSDLThread() { + if (mSDLThread == null) { mSDLThread = new Thread(new SDLMain(), "SDLThread"); mSDLThread.start(); } @@ -1053,10 +927,8 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK /** * Simple nativeInit() runnable */ - class SDLMain implements Runnable - { - public void run() - { + class SDLMain implements Runnable { + public void run() { // Runs SDL_main() SDLActivity.nativeInit(); @@ -1070,8 +942,7 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // Startup - public SDLSurface(Context context) - { + public SDLSurface(Context context) { super(context); mSemSurface = new Object(); mSurfaceValid = false; @@ -1087,28 +958,23 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // Called when we have a valid drawing surface - public void surfaceCreated(SurfaceHolder holder) - { + public void surfaceCreated(SurfaceHolder holder) { //Log.d(TAG, "surfaceCreated()"); enableSensor(Sensor.TYPE_ACCELEROMETER, true); } - public void onDestroy() - { + public void onDestroy() { // Send a quit message to the application // should that be in SDLActivity "onDestroy" instead ? SDLActivity.nativeQuit(); // Now wait for the SDL thread to quit - if (mSDLThread != null) - { - try - { + if (mSDLThread != null) { + try { mSDLThread.join(); - } catch (Exception e) - { + } catch (Exception e) { Log.e(TAG, "Problem stopping thread: " + e); } mSDLThread = null; @@ -1118,11 +984,9 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // Called when we lose the surface - public void surfaceDestroyed(SurfaceHolder holder) - { + public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "surfaceDestroyed()"); - synchronized (mSemSurface) - { + synchronized (mSemSurface) { mSurfaceValid = false; mSemSurface.notifyAll(); } @@ -1130,54 +994,52 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // Called when the surface is resized - public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) - { + public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d(TAG, "surfaceChanged()"); int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default - switch (format) - { - case PixelFormat.A_8: - Log.d("TAG", "pixel format A_8"); - break; - case PixelFormat.LA_88: - Log.d("TAG", "pixel format LA_88"); - break; - case PixelFormat.L_8: - Log.d("TAG", "pixel format L_8"); - break; - case PixelFormat.RGBA_4444: - Log.d("TAG", "pixel format RGBA_4444"); - sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444 - break; - case PixelFormat.RGBA_5551: - Log.d(TAG, "pixel format RGBA_5551"); - sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551 - break; - case PixelFormat.RGBA_8888: - Log.d(TAG, "pixel format RGBA_8888"); - sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888 - break; - case PixelFormat.RGBX_8888: - Log.d(TAG, "pixel format RGBX_8888"); - sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888 - break; - case PixelFormat.RGB_332: - Log.d(TAG, "pixel format RGB_332"); - sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332 - break; - case PixelFormat.RGB_565: - Log.d(TAG, "pixel format RGB_565"); - sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 - break; - case PixelFormat.RGB_888: - Log.d(TAG, "pixel format RGB_888"); - // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead? - sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888 - break; - default: - Log.d(TAG, "pixel format unknown " + format); - break; + switch (format) { + case PixelFormat.A_8: + Log.d("TAG", "pixel format A_8"); + break; + case PixelFormat.LA_88: + Log.d("TAG", "pixel format LA_88"); + break; + case PixelFormat.L_8: + Log.d("TAG", "pixel format L_8"); + break; + case PixelFormat.RGBA_4444: + Log.d("TAG", "pixel format RGBA_4444"); + sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444 + break; + case PixelFormat.RGBA_5551: + Log.d(TAG, "pixel format RGBA_5551"); + sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551 + break; + case PixelFormat.RGBA_8888: + Log.d(TAG, "pixel format RGBA_8888"); + sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888 + break; + case PixelFormat.RGBX_8888: + Log.d(TAG, "pixel format RGBX_8888"); + sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888 + break; + case PixelFormat.RGB_332: + Log.d(TAG, "pixel format RGB_332"); + sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332 + break; + case PixelFormat.RGB_565: + Log.d(TAG, "pixel format RGB_565"); + sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 + break; + case PixelFormat.RGB_888: + Log.d(TAG, "pixel format RGB_888"); + // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead? + sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888 + break; + default: + Log.d(TAG, "pixel format unknown " + format); + break; } SDLActivity.onNativeResize(width, height, sdlFormat); @@ -1186,17 +1048,14 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // unused - public void onDraw(Canvas canvas) - { + public void onDraw(Canvas canvas) { } // EGL functions - public boolean initEGL(int majorVersion, int minorVersion) - { + public boolean initEGL(int majorVersion, int minorVersion) { Log.d(TAG, "Starting up OpenGL ES " + majorVersion + "." + minorVersion); - try - { + try { EGL10 egl = (EGL10) EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); @@ -1207,29 +1066,25 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK int EGL_OPENGL_ES_BIT = 1; int EGL_OPENGL_ES2_BIT = 4; int renderableType = 0; - if (majorVersion == 2) - { + if (majorVersion == 2) { renderableType = EGL_OPENGL_ES2_BIT; - } else if (majorVersion == 1) - { + } else if (majorVersion == 1) { renderableType = EGL_OPENGL_ES_BIT; } int[] configSpec = - { - // EGL10.EGL_DEPTH_SIZE, 16, - EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; + { + // EGL10.EGL_DEPTH_SIZE, 16, + EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE}; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; - if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) - { + if (!egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config) || num_config[0] == 0) { Log.e(TAG, "No EGL config available"); return false; } mEGLConfig = configs[0]; EGLContext ctx = egl.eglCreateContext(dpy, mEGLConfig, EGL10.EGL_NO_CONTEXT, null); - if (ctx == EGL10.EGL_NO_CONTEXT) - { + if (ctx == EGL10.EGL_NO_CONTEXT) { Log.e(TAG, "Couldn't create context"); return false; } @@ -1237,16 +1092,13 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK mEGLContext = ctx; mEGLDisplay = dpy; - if (!createSurface(this.getHolder())) - { + if (!createSurface(this.getHolder())) { return false; } - } catch (Exception e) - { + } catch (Exception e) { Log.e(TAG, e + ""); - for (StackTraceElement s : e.getStackTrace()) - { + for (StackTraceElement s : e.getStackTrace()) { Log.e(TAG, s.toString()); } } @@ -1254,14 +1106,12 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK return true; } - public Boolean createSurface(SurfaceHolder holder) - { + public Boolean createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new surface. */ EGL10 egl = (EGL10) EGLContext.getEGL(); - if (mEGLSurface != null) - { + if (mEGLSurface != null) { /* * Unbind and destroy the old EGL surface, if there is one. */ @@ -1273,8 +1123,7 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK * Create an EGL surface we can render into. */ mEGLSurface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, holder, null); - if (mEGLSurface == EGL10.EGL_NO_SURFACE) - { + if (mEGLSurface == EGL10.EGL_NO_SURFACE) { Log.e(TAG, "Couldn't create surface"); return false; } @@ -1282,8 +1131,7 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK /* * Before we can issue GL commands, we need to make sure the context is current and bound to a surface. */ - if (!egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) - { + if (!egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) { Log.e(TAG, "Couldn't make context current"); return false; } @@ -1294,15 +1142,12 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // EGL buffer flip - public void flipEGL() - { - if (!mSurfaceValid) - { + public void flipEGL() { + if (!mSurfaceValid) { createSurface(this.getHolder()); } - try - { + try { EGL10 egl = (EGL10) EGLContext.getEGL(); egl.eglWaitNative(EGL10.EGL_CORE_NATIVE_ENGINE, null); @@ -1313,32 +1158,27 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK egl.eglSwapBuffers(mEGLDisplay, mEGLSurface); - } catch (Exception e) - { + } catch (Exception e) { Log.e(TAG, "flipEGL(): " + e); - for (StackTraceElement s : e.getStackTrace()) - { + for (StackTraceElement s : e.getStackTrace()) { Log.e(TAG, s.toString()); } } } // Key events - public boolean onKey(View v, int keyCode, KeyEvent event) - { + public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) return false; if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) return false; - if (event.getAction() == KeyEvent.ACTION_DOWN) - { + if (event.getAction() == KeyEvent.ACTION_DOWN) { // Log.d(TAG, "key down: " + keyCode); SDLActivity.onNativeKeyDown(keyCode); return true; - } else if (event.getAction() == KeyEvent.ACTION_UP) - { + } else if (event.getAction() == KeyEvent.ACTION_UP) { // Log.d(TAG, "key up: " + keyCode); SDLActivity.onNativeKeyUp(keyCode); return true; @@ -1348,10 +1188,8 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // Touch events - public boolean onTouch(View v, MotionEvent event) - { - for (int index = 0; index < event.getPointerCount(); ++index) - { + public boolean onTouch(View v, MotionEvent event) { + for (int index = 0; index < event.getPointerCount(); ++index) { int action = event.getActionMasked(); float x = event.getX(index); float y = event.getY(index); @@ -1362,18 +1200,14 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // account for 'flick' type gestures by monitoring velocity - if (event.getActionIndex() == 0) - { - if (event.getAction() == MotionEvent.ACTION_DOWN) - { + if (event.getActionIndex() == 0) { + if (event.getAction() == MotionEvent.ACTION_DOWN) { mVelocityTracker = VelocityTracker.obtain(); mVelocityTracker.clear(); mVelocityTracker.addMovement(event); - } else if (event.getAction() == MotionEvent.ACTION_MOVE) - { + } else if (event.getAction() == MotionEvent.ACTION_MOVE) { mVelocityTracker.addMovement(event); - } else if (event.getAction() == MotionEvent.ACTION_UP) - { + } else if (event.getAction() == MotionEvent.ACTION_UP) { mVelocityTracker.addMovement(event); // calc velocity @@ -1391,27 +1225,21 @@ class SDLSurface extends SurfaceView implements SurfaceHolder.Callback, View.OnK } // Sensor events - public void enableSensor(int sensortype, boolean enabled) - { + public void enableSensor(int sensortype, boolean enabled) { // TODO: This uses getDefaultSensor - what if we have >1 accels? - if (enabled) - { + if (enabled) { mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(sensortype), SensorManager.SENSOR_DELAY_GAME, null); - } else - { + } else { mSensorManager.unregisterListener(this, mSensorManager.getDefaultSensor(sensortype)); } } - public void onAccuracyChanged(Sensor sensor, int accuracy) - { + public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO } - public void onSensorChanged(SensorEvent event) - { - if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) - { + public void onSensorChanged(SensorEvent event) { + if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { SDLActivity.onNativeAccel(event.values[0], event.values[1], event.values[2]); } }